Skip to content

Computer use CLI for AI agents

feat: combine multi-agent cursors with core and macOS optimizations (#171)

Lahfir922bb7d5b59f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9bc29c9da..a8fc55e09 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -132,6 +132,11 @@ jobs:
- name: Core and macOS unit tests
run: scripts/cargo-test-isolated-home.sh test --locked -p agent-desktop-core -p agent-desktop-macos --lib
+ - name: Native cursor trail lifecycle
+ run: |
+ clang -fobjc-arc -Werror -framework AppKit -framework QuartzCore -framework CoreGraphics tests/native/cursor_overlay_trail_test.m -o "$RUNNER_TEMP/cursor-trail-test"
+ "$RUNNER_TEMP/cursor-trail-test"
+
- name: Locator benchmark adapter contract
run: scripts/cargo-test-isolated-home.sh test --locked -p agent-desktop-core --example locator_benchmark
diff --git a/.github/workflows/supply-chain.yml b/.github/workflows/supply-chain.yml
index e9be78880..183735d1a 100644
--- a/.github/workflows/supply-chain.yml
+++ b/.github/workflows/supply-chain.yml
@@ -60,7 +60,7 @@ jobs:
# Scan commit history, not just the checked-out tree: a value added
# in one commit and removed in a later one stays reachable in branch
# history, and a tree-only scan would pass it.
- ./gitleaks git . --config .gitleaks.toml --redact --no-banner --exit-code 1
+ ./gitleaks git . --log-opts=HEAD --config .gitleaks.toml --redact --no-banner --exit-code 1
- name: Workflow security audit
uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2
diff --git a/CLAUDE.md b/CLAUDE.md
index 539ed5ae1..4aec8cb0d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -347,6 +347,7 @@ The `error` object may also carry optional `details` and `recovery` objects. Ver
- Drill-down: `--root @ref` starts from a previously-discovered ref with scoped invalidation (only that ref's subtree refs are replaced on re-drill)
- RefMap size check: write-side guard prevents >1MB refmap files
- **Sessions:** `session start` creates and returns a manifest-gated session under `~/.agent-desktop/sessions/<id>/` and enables automatic trace segments by default. It does not activate that session for later processes. Pass the returned ID through `--session` or `AGENT_DESKTOP_SESSION`. Bare `--session <id>` without a manifest scopes only the snapshot namespace — no surprise trace files.
+- **Subagent cursors (macOS):** `session start --cursor --multi-agent` enables independent cursors keyed by session ID and global `--agent-id` (`AGENT_DESKTOP_AGENT_ID` fallback). The harness supplies a stable ID per subagent; desktop UI actions require it in this mode. Agents share session snapshots and use qualified refs. Optional named `cursor-overlay enable` profiles affect presentation only. Disable/end stops every cursor in the session.
- **Trace:** manifest `trace: on` writes per-process JSONL segments under `<session>/trace/<pid>-<procTs>.jsonl`; `--trace <path>` overrides to one file; activation resolves `--session` > `AGENT_DESKTOP_SESSION` > no session. Snapshot lookup is confined to that selected namespace and never searches other sessions.
## PlatformAdapter Trait
diff --git a/CONCEPTS.md b/CONCEPTS.md
index 3815051e8..4c8c81b1f 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -110,7 +110,9 @@ Core owns those preconditions through `HeadedRequirement`: `FocusedWindow` for k
### 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. Headed mode suppresses the overlay. 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 supplies the native renderer while other platforms inherit the adapter's default no-op.
+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. Headed mode retains the overlay. 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 supplies the native renderer while other platforms inherit the adapter's default no-op.
+
+For macOS harness subagents, `session start --cursor --multi-agent` enables a cursor per `(session-id, agent-id)`. 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. Headless and headed actions share the same cursor presentation, including raw physical pointer commands. 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.
### 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/Cargo.toml b/Cargo.toml
index 286d4a783..195a3a204 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -49,6 +49,12 @@ codegen-units = 1
strip = true
panic = "abort"
+[profile.release.package.agent-desktop-core]
+opt-level = 3
+
+[profile.release.package.agent-desktop-macos]
+opt-level = 3
+
[profile.ci]
inherits = "release"
opt-level = 1
diff --git a/README.md b/README.md
index 65aa42630..21b6bb76c 100644
--- a/README.md
+++ b/README.md
@@ -176,6 +176,8 @@ agent-desktop session gc
### Agent cursor overlay (macOS)
+Agent cursors work in both headless and headed mode, including physical pointer commands. Drags follow the cursor’s curved motion and draw an accent-colored trail while held, then fade after release. Each agent retains its own cursor; the existing interaction lease coordinates the shared OS pointer.
+
A presentation-only cursor that shows what the agent is about to do. Off by default.
```bash
@@ -188,13 +190,27 @@ agent-desktop cursor-overlay disable
`session start --cursor` turns it on with the default look. `cursor-overlay enable` does the same for a session that already exists.
-**Style is session-global.** Set it once; every later command uses it. Never pass it per action.
+**Style defaults belong to the session.** Set them once; later commands inherit them. Named agents can save their own style using global `--agent-id`.
```bash
agent-desktop --session "$session_id" cursor-overlay enable --label "Opening the menu"
export AGENT_DESKTOP_SESSION="$session_id"
```
+For harness subagents on macOS, start one shared session and give each worker a stable ID:
+
+```bash
+session_id=$(agent-desktop session start --cursor --multi-agent | jq -r '.data.session_id')
+export AGENT_DESKTOP_SESSION="$session_id"
+# Set a different ID in each subagent's environment:
+export AGENT_DESKTOP_AGENT_ID=researcher
+agent-desktop cursor-overlay enable --label "Checking details" --accent "#FF3B7B"
+agent-desktop snapshot --app Finder -i
+agent-desktop click <qualified-ref-from-snapshot>
+```
+
+The style command is optional and saves settings for the next presentation without creating a cursor. Each distinct agent ID gets its own cursor on first presentation; three IDs produce three cursors, with no extra coordinator cursor. IDs use 1–64 letters, digits, `-` or `_`. Global `--agent-id` overrides the environment. In multi-agent mode, desktop UI actions require an ID; observations, clipboard operations, and session administration do not. Snapshots remain shared by session, so pin qualified refs and coordinate actions on shared UI. `cursor-overlay disable` or `session end` stops every cursor, even when an agent ID is set. To enable this mode on an existing session, run `cursor-overlay enable --multi-agent` without an agent ID.
+
| Flag | Meaning | Default |
|---|---|---|
| `--label TEXT` | Intent text beside the cursor | none |
@@ -209,11 +225,11 @@ export AGENT_DESKTOP_SESSION="$session_id"
**Behaviour**
- The cursor travels a human path in 90–320 ms. It never rotates or resizes.
-- The action waits for it to land, so a window never closes before the cursor arrives. The wait is capped at 900 ms and never blocks an action.
+- The action waits up to 900 ms for cursor arrival confirmation. If the renderer does not confirm in time, a warning is reported and the action proceeds.
- A click plays a ripple, then flashes an accent outline around the element for 0.9 s. Both draw below the cursor.
- Idle for 6 s, it fades out. The next command brings it back.
- `cursor-overlay disable` removes it now. You do not have to end the session.
-- Headed actions hide it. It never moves or intercepts the OS pointer.
+- Headed actions retain it. It never moves or intercepts the OS pointer.
- Overhead is about 150–300 ms per action, all of it the visible travel.
macOS renders it natively. Windows and Linux inherit the adapter's no-op and need only their own renderer against the same core contract.
@@ -378,11 +394,11 @@ agent-desktop --session run-a batch '[
### System
```bash
-agent-desktop session start [--name LABEL] [--no-trace] [--cursor] # create session; pass returned ID explicitly
+agent-desktop session start [--name LABEL] [--no-trace] [--cursor [--multi-agent]] # create session; pass returned ID explicitly
agent-desktop session end [id]
agent-desktop session list
agent-desktop session gc [--older-than SECS] [--ended]
-agent-desktop --session <id> cursor-overlay enable [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]
+agent-desktop --session <id> [--agent-id ID] cursor-overlay enable [--multi-agent] [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]
export AGENT_DESKTOP_SESSION=<id>
agent-desktop cursor-overlay disable
agent-desktop status # platform, permissions, session_id, tracing, latest snapshot
diff --git a/assets/banner.png b/assets/banner.png
new file mode 100644
index 000000000..ec8ca37dd
Binary files /dev/null and b/assets/banner.png differ
diff --git a/crates/core/src/commands/drag.rs b/crates/core/src/commands/drag.rs
index 9b3eb4631..2578bba18 100644
--- a/crates/core/src/commands/drag.rs
+++ b/crates/core/src/commands/drag.rs
@@ -119,7 +119,35 @@ pub fn execute(
drop_delay_ms: args.drop_delay_ms,
};
params.validate(deadline)?;
- adapter.drag(params, &lease)?;
+ crate::cursor_overlay::submit_travel(adapter, context, from.point.clone(), &lease);
+ let drag_tracking = crate::cursor_overlay::submit_drag(
+ adapter,
+ context,
+ from.point.clone(),
+ to.point.clone(),
+ &lease,
+ );
+ let result = adapter.drag(params, &lease);
+ if result.is_ok() && drag_tracking {
+ crate::cursor_overlay::submit_drag_effect(
+ adapter,
+ context,
+ from.point.clone(),
+ to.point.clone(),
+ );
+ } else if result.is_ok() {
+ crate::cursor_overlay::submit(
+ adapter,
+ context,
+ to.point.clone(),
+ None,
+ false,
+ crate::CursorPhase::Effect,
+ );
+ } else {
+ crate::cursor_overlay::cancel_drag(adapter, context);
+ }
+ result?;
let mut response = json!({
"dragged": true,
"from": { "x": from.point.x, "y": from.point.y },
diff --git a/crates/core/src/commands/drag_tests.rs b/crates/core/src/commands/drag_tests.rs
index dc2900518..6ad79aa42 100644
--- a/crates/core/src/commands/drag_tests.rs
+++ b/crates/core/src/commands/drag_tests.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
use crate::{
- AdapterError, DragParams, Rect,
+ AdapterError, CursorOverlayControl, DeliverySemantics, DragParams, Rect,
adapter::NativeHandle,
capability,
commands::stale_retry_test_support::StaleRetryCounter,
@@ -15,18 +15,24 @@ use std::sync::atomic::{AtomicU32, Ordering};
struct DragCaptureAdapter {
captured: Mutex<Option<DragParams>>,
+ presented: Mutex<Vec<CursorOverlayControl>>,
focused_pids: Mutex<Vec<crate::ProcessId>>,
resolve_calls: AtomicU32,
+ presented_before_drag: AtomicU32,
focused_bounds: Option<Rect>,
+ drag_failure: Option<DeliverySemantics>,
}
impl DragCaptureAdapter {
fn new() -> Self {
Self {
captured: Mutex::new(None),
+ presented: Mutex::new(Vec::new()),
focused_pids: Mutex::new(Vec::new()),
resolve_calls: AtomicU32::new(0),
+ presented_before_drag: AtomicU32::new(0),
focused_bounds: None,
+ drag_failure: None,
}
}
@@ -34,6 +40,11 @@ impl DragCaptureAdapter {
self.focused_bounds = Some(bounds);
self
}
+
+ fn with_drag_failure(mut self, disposition: DeliverySemantics) -> Self {
+ self.drag_failure = Some(disposition);
+ self
+ }
}
impl ObservationOps for DragCaptureAdapter {
@@ -82,7 +93,15 @@ impl InputOps for DragCaptureAdapter {
params: DragParams,
_lease: &crate::InteractionLease,
) -> Result<(), AdapterError> {
+ self.presented_before_drag.store(
+ self.presented.lock().unwrap().len() as u32,
+ Ordering::SeqCst,
+ );
*self.captured.lock().unwrap() = Some(params);
+ if let Some(disposition) = self.drag_failure {
+ return Err(AdapterError::internal("drag completion was uncertain")
+ .with_disposition(disposition));
+ }
Ok(())
}
}
@@ -106,6 +125,11 @@ impl SystemOps for DragCaptureAdapter {
self.focused_pids.lock().unwrap().push(window.pid);
Ok(())
}
+
+ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ self.presented.lock().unwrap().push(control.clone());
+ Ok(())
+ }
}
fn xy_args(drop_delay_ms: Option<u64>) -> DragArgs {
@@ -160,6 +184,69 @@ fn drop_delay_omitted_uses_adapter_default_and_no_response_field() {
assert_eq!(captured.drop_delay_ms, None);
}
+#[test]
+fn successful_drag_effect_carries_the_complete_path() {
+ let adapter = DragCaptureAdapter::new();
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let context = CommandContext::default()
+ .with_headed(true)
+ .with_cursor_overlay_session("test-session", config);
+
+ execute(xy_args(None), &adapter, &context).expect("drag succeeds");
+
+ let presented = adapter.presented.lock().unwrap();
+ assert_eq!(adapter.presented_before_drag.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ presented[1]
+ .instruction()
+ .expect("drag instruction")
+ .phase(),
+ crate::CursorPhase::Drag
+ );
+ let effect = presented
+ .last()
+ .and_then(CursorOverlayControl::instruction)
+ .expect("effect instruction");
+ assert_eq!(effect.phase(), crate::CursorPhase::Effect);
+ assert_eq!(effect.drag_from(), Some(&crate::Point { x: 1.0, y: 2.0 }));
+ assert_eq!(effect.destination(), &crate::Point { x: 3.0, y: 4.0 });
+}
+
+#[test]
+fn uncertain_drag_hides_the_overlay_without_claiming_a_landing() {
+ let adapter = DragCaptureAdapter::new().with_drag_failure(DeliverySemantics::uncertain());
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let context = CommandContext::default()
+ .with_agent_id(Some("agent-a".into()))
+ .expect("valid agent")
+ .with_headed(true)
+ .with_cursor_overlay_session("test-session", config);
+
+ execute(xy_args(None), &adapter, &context).expect_err("drag is uncertain");
+
+ let presented = adapter.presented.lock().unwrap();
+ let cancel = presented.last().expect("cancel control");
+ assert!(cancel.is_hide());
+ assert!(cancel.instruction().is_none());
+ assert_eq!(cancel.agent_id(), Some("agent-a"));
+}
+
+#[test]
+fn expired_action_deadline_does_not_suppress_drag_cancellation() {
+ let adapter = DragCaptureAdapter::new();
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let context = CommandContext::default()
+ .with_headed(true)
+ .with_cursor_overlay_session("test-session", config);
+ let expired = crate::Deadline::detached_after(1).expect("valid deadline");
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ let _scope = crate::deadline::enter_scope(Some(expired));
+
+ crate::cursor_overlay::cancel_drag(&adapter, &context);
+
+ assert!(adapter.presented.lock().unwrap()[0].is_hide());
+}
+
fn ref_entry(pid: u32) -> RefEntry {
RefEntry {
process: crate::RefProcess {
diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs
index 04e77a62b..a4b65ebe5 100644
--- a/crates/core/src/commands/helpers.rs
+++ b/crates/core/src/commands/helpers.rs
@@ -159,6 +159,25 @@ pub(crate) fn apply_post_action_wait(
entry: Option<&RefEntry>,
adapter: &dyn PlatformAdapter,
context: &CommandContext,
+) -> Result<Value, AppError> {
+ if context.wait_selector().is_none() {
+ return Ok(result);
+ }
+ apply_scoped_post_action_wait(
+ result,
+ entry.and_then(|entry| probe_app_name(adapter, entry)),
+ entry.and_then(|entry| entry.source.source_window_id.clone()),
+ adapter,
+ context,
+ )
+}
+
+pub(crate) fn apply_scoped_post_action_wait(
+ result: Value,
+ app: Option<String>,
+ window_id: Option<String>,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
) -> Result<Value, AppError> {
let Some(wait) = context.wait_selector() else {
return Ok(result);
@@ -167,8 +186,8 @@ pub(crate) fn apply_post_action_wait(
WaitSelectorInput {
query_raw: wait.query_raw.clone(),
gone: wait.gone,
- app: entry.and_then(|entry| probe_app_name(adapter, entry)),
- window_id: entry.and_then(|entry| entry.source.source_window_id.clone()),
+ app,
+ window_id,
opts: TreeOptions::default(),
timeout_ms: wait.timeout_ms,
},
diff --git a/crates/core/src/commands/hover.rs b/crates/core/src/commands/hover.rs
index cc94d6008..81b42094a 100644
--- a/crates/core/src/commands/hover.rs
+++ b/crates/core/src/commands/hover.rs
@@ -81,15 +81,19 @@ pub fn execute(
"point": { "x": resolved.point.x, "y": resolved.point.y }
})),
)?;
- adapter.mouse_event(
+ let result = crate::cursor_overlay::dispatch_mouse_event_with_cursor(
+ adapter,
+ context,
MouseEvent {
kind: MouseEventKind::Move,
point: resolved.point.clone(),
button: MouseButton::Left,
modifiers: Vec::new(),
},
+ false,
&lease,
- )?;
+ );
+ result?;
let mut response = json!({ "hovered": true, "x": resolved.point.x, "y": resolved.point.y });
if resolved.focused {
response["focused"] = json!(true);
diff --git a/crates/core/src/commands/mouse_click.rs b/crates/core/src/commands/mouse_click.rs
index 8685080cd..aba3d7655 100644
--- a/crates/core/src/commands/mouse_click.rs
+++ b/crates/core/src/commands/mouse_click.rs
@@ -25,15 +25,19 @@ pub fn execute(
y: args.y,
};
point.validate()?;
- adapter.mouse_event(
+ let result = crate::cursor_overlay::dispatch_mouse_event_with_cursor(
+ adapter,
+ context,
MouseEvent {
kind: MouseEventKind::Click { count: args.count },
point,
button: args.button,
modifiers: args.modifiers,
},
+ true,
&lease,
- )?;
+ );
+ result?;
Ok(json!({ "clicked": true, "x": args.x, "y": args.y, "count": args.count }))
}
diff --git a/crates/core/src/commands/mouse_click_tests.rs b/crates/core/src/commands/mouse_click_tests.rs
index 125cd1cb2..aecd1c3d0 100644
--- a/crates/core/src/commands/mouse_click_tests.rs
+++ b/crates/core/src/commands/mouse_click_tests.rs
@@ -5,14 +5,14 @@ use std::sync::Mutex;
struct ModifierCaptureAdapter {
captured: Mutex<Option<MouseEvent>>,
- presented: Mutex<Option<crate::CursorOverlayControl>>,
+ presented: Mutex<Vec<crate::CursorOverlayControl>>,
}
impl ModifierCaptureAdapter {
fn new() -> Self {
Self {
captured: Mutex::new(None),
- presented: Mutex::new(None),
+ presented: Mutex::new(Vec::new()),
}
}
}
@@ -26,7 +26,7 @@ impl SystemOps for ModifierCaptureAdapter {
&self,
control: &crate::CursorOverlayControl,
) -> Result<(), AdapterError> {
- *self.presented.lock().unwrap() = Some(control.clone());
+ self.presented.lock().unwrap().push(control.clone());
Ok(())
}
}
@@ -92,9 +92,19 @@ fn no_modifiers_requested_dispatches_empty_modifiers() {
}
#[test]
-fn headed_mouse_click_suppresses_cursor_overlay() {
+fn headed_mouse_click_presents_agent_cursor_after_delivery() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
let adapter = ModifierCaptureAdapter::new();
- let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let session = crate::session::start_session(Default::default()).expect("session starts");
+ let config = crate::CursorOverlayConfig::enabled(None, 6)
+ .expect("valid config")
+ .with_multi_agent(true);
+ 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)
+ .with_agent_id(Some("agent-a".into()))
+ .expect("valid agent id");
execute(
MouseClickArgs {
@@ -105,13 +115,18 @@ fn headed_mouse_click_suppresses_cursor_overlay() {
modifiers: Vec::new(),
},
&adapter,
- &CommandContext::default()
- .with_headed(true)
- .with_cursor_overlay(config),
+ &context,
)
.expect("mouse click succeeds");
- assert!(adapter.presented.lock().unwrap().is_none());
+ let presented = adapter.presented.lock().unwrap();
+ assert_eq!(presented.len(), 2);
+ assert!(presented[0].is_travel());
+ let control = &presented[1];
+ let instruction = control.instruction().expect("present instruction");
+ assert_eq!(instruction.destination(), &Point { x: 10.0, y: 20.0 });
+ assert!(instruction.is_click());
+ assert_eq!(control.agent_id(), Some("agent-a"));
}
#[test]
diff --git a/crates/core/src/commands/mouse_move.rs b/crates/core/src/commands/mouse_move.rs
index d4699d13f..85b458892 100644
--- a/crates/core/src/commands/mouse_move.rs
+++ b/crates/core/src/commands/mouse_move.rs
@@ -21,14 +21,18 @@ pub fn execute(
y: args.y,
};
point.validate()?;
- adapter.mouse_event(
+ let result = crate::cursor_overlay::dispatch_mouse_event_with_cursor(
+ adapter,
+ context,
MouseEvent {
kind: MouseEventKind::Move,
point,
button: MouseButton::Left,
modifiers: Vec::new(),
},
+ false,
&lease,
- )?;
+ );
+ result?;
Ok(json!({ "moved": true, "x": args.x, "y": args.y }))
}
diff --git a/crates/core/src/commands/mouse_wheel.rs b/crates/core/src/commands/mouse_wheel.rs
index 365e44839..985fd407e 100644
--- a/crates/core/src/commands/mouse_wheel.rs
+++ b/crates/core/src/commands/mouse_wheel.rs
@@ -29,7 +29,9 @@ pub fn execute(
y: args.y,
};
point.validate()?;
- adapter.mouse_event(
+ let result = crate::cursor_overlay::dispatch_mouse_event_with_cursor(
+ adapter,
+ context,
MouseEvent {
kind: MouseEventKind::Wheel {
delta_x: args.dx,
@@ -39,8 +41,10 @@ pub fn execute(
button: MouseButton::Left,
modifiers: args.modifiers,
},
+ false,
&lease,
- )?;
+ );
+ result?;
Ok(json!({ "scrolled": true, "dy": args.dy, "dx": args.dx }))
}
diff --git a/crates/core/src/commands/mouse_wheel_tests.rs b/crates/core/src/commands/mouse_wheel_tests.rs
index 4b989e8bd..6db83d86a 100644
--- a/crates/core/src/commands/mouse_wheel_tests.rs
+++ b/crates/core/src/commands/mouse_wheel_tests.rs
@@ -15,21 +15,32 @@ struct WheelCall {
struct WheelCaptureAdapter {
captured: Mutex<Option<WheelCall>>,
- fail: bool,
+ presented: Mutex<Vec<crate::CursorOverlayControl>>,
+ failure: Option<crate::DeliverySemantics>,
}
impl WheelCaptureAdapter {
fn recording() -> Self {
Self {
captured: Mutex::new(None),
- fail: false,
+ presented: Mutex::new(Vec::new()),
+ failure: None,
}
}
fn failing() -> Self {
Self {
captured: Mutex::new(None),
- fail: true,
+ presented: Mutex::new(Vec::new()),
+ failure: Some(crate::DeliverySemantics::not_delivered()),
+ }
+ }
+
+ fn failing_after_delivery() -> Self {
+ Self {
+ captured: Mutex::new(None),
+ presented: Mutex::new(Vec::new()),
+ failure: Some(crate::DeliverySemantics::delivered_unverified()),
}
}
}
@@ -38,6 +49,14 @@ impl ObservationOps for WheelCaptureAdapter {}
impl ActionOps for WheelCaptureAdapter {}
impl SystemOps for WheelCaptureAdapter {
crate::adapter::guarded_interaction_lease!();
+
+ fn update_cursor_overlay(
+ &self,
+ control: &crate::CursorOverlayControl,
+ ) -> Result<(), AdapterError> {
+ self.presented.lock().unwrap().push(control.clone());
+ Ok(())
+ }
}
impl InputOps for WheelCaptureAdapter {
@@ -56,8 +75,8 @@ impl InputOps for WheelCaptureAdapter {
dx: delta_x,
modifiers: event.modifiers,
});
- if self.fail {
- return Err(AdapterError::not_supported("mouse_wheel"));
+ if let Some(disposition) = self.failure {
+ return Err(AdapterError::not_supported("mouse_wheel").with_disposition(disposition));
}
Ok(())
}
@@ -119,6 +138,7 @@ fn returns_scrolled_envelope_with_requested_deltas() {
#[test]
fn adapter_error_propagates_as_err() {
let adapter = WheelCaptureAdapter::failing();
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
let result = execute(
MouseWheelArgs {
@@ -129,10 +149,44 @@ fn adapter_error_propagates_as_err() {
modifiers: Vec::new(),
},
&adapter,
- &CommandContext::default().with_headed(true),
+ &CommandContext::default()
+ .with_headed(true)
+ .with_cursor_overlay_session("test-session", config),
);
assert!(result.is_err());
+ let presented = adapter.presented.lock().unwrap();
+ assert_eq!(presented.len(), 1);
+ assert!(presented[0].is_travel());
+}
+
+#[test]
+fn delivered_error_still_presents_effect_before_propagating() {
+ let adapter = WheelCaptureAdapter::failing_after_delivery();
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+
+ let result = execute(
+ MouseWheelArgs {
+ x: 1.0,
+ y: 2.0,
+ dy: 1.0,
+ dx: 0.0,
+ modifiers: Vec::new(),
+ },
+ &adapter,
+ &CommandContext::default()
+ .with_headed(true)
+ .with_cursor_overlay_session("test-session", config),
+ );
+
+ assert!(result.is_err());
+ let presented = adapter.presented.lock().unwrap();
+ assert_eq!(presented.len(), 2);
+ assert!(presented[0].is_travel());
+ assert_eq!(
+ presented[1].instruction().unwrap().phase(),
+ crate::CursorPhase::Effect
+ );
}
#[test]
diff --git a/crates/core/src/commands/press.rs b/crates/core/src/commands/press.rs
index 258d3f87c..a09f1555e 100644
--- a/crates/core/src/commands/press.rs
+++ b/crates/core/src/commands/press.rs
@@ -18,11 +18,12 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
+ super::helpers::validate_post_action_wait(context)?;
let combo = parse_combo_normalized(&args.combo)?;
ensure_combo_allowed(&combo, &args.combo, args.force, adapter)?;
let deadline = crate::Deadline::standard()?;
- if let Some(app_name) = &args.app {
+ let result = if let Some(app_name) = &args.app {
let expected = crate::commands::helpers::resolve_app(Some(app_name), adapter, deadline)?;
let lease = adapter.acquire_interaction_lease(deadline)?;
let live = crate::commands::helpers::revalidate_app_for_mutation(
@@ -34,19 +35,23 @@ pub fn execute(
if context.physical_input_policy().is_headed() {
crate::headed_focus::focus_process_window(process.clone(), adapter, context, &lease)?;
}
- let result =
- adapter.press_key_for_app(process, &combo, context.physical_input_policy(), &lease)?;
- return Ok(serde_json::to_value(result)?);
- }
-
- let lease = adapter.acquire_interaction_lease(deadline)?;
- let handle = crate::adapter::NativeHandle::null();
- let result = adapter.execute_action(
- &handle,
- context.request_base(Action::PressKey(combo)),
- &lease,
- )?;
- Ok(serde_json::to_value(result)?)
+ adapter.press_key_for_app(process, &combo, context.physical_input_policy(), &lease)?
+ } else {
+ let lease = adapter.acquire_interaction_lease(deadline)?;
+ let handle = crate::adapter::NativeHandle::null();
+ adapter.execute_action(
+ &handle,
+ context.request_base(Action::PressKey(combo)),
+ &lease,
+ )?
+ };
+ super::helpers::apply_scoped_post_action_wait(
+ serde_json::to_value(result)?,
+ args.app,
+ None,
+ adapter,
+ context,
+ )
}
#[cfg(test)]
diff --git a/crates/core/src/commands/press_tests.rs b/crates/core/src/commands/press_tests.rs
index e5054ab02..1fe8c5f56 100644
--- a/crates/core/src/commands/press_tests.rs
+++ b/crates/core/src/commands/press_tests.rs
@@ -57,9 +57,29 @@ impl SystemOps for AllowingAdapter {
struct CapturingAdapter {
global_policy: Mutex<Option<crate::InteractionPolicy>>,
app_policy: Mutex<Option<crate::InteractionPolicy>>,
+ dispatches: std::sync::atomic::AtomicUsize,
+ expect_scoped_windows: bool,
}
impl ObservationOps for CapturingAdapter {
+ fn observe_tree(
+ &self,
+ root: crate::live_locator::ObservationRoot<'_>,
+ _request: &crate::live_locator::ObservationRequest,
+ ) -> Result<crate::live_locator::ObservedTree, AdapterError> {
+ assert_eq!(self.dispatches.load(std::sync::atomic::Ordering::SeqCst), 1);
+ crate::adapter::observed_tree(&root, saved_tree())
+ }
+
+ fn get_tree(
+ &self,
+ _window: &crate::WindowInfo,
+ _opts: &crate::adapter::TreeOptions,
+ _deadline: crate::Deadline,
+ ) -> Result<crate::AccessibilityNode, AdapterError> {
+ Ok(saved_tree())
+ }
+
fn list_apps(&self, _deadline: crate::Deadline) -> Result<Vec<crate::AppInfo>, AdapterError> {
Ok(vec![crate::AppInfo {
name: "Editor".into(),
@@ -72,9 +92,12 @@ impl ObservationOps for CapturingAdapter {
fn list_windows(
&self,
- _filter: &crate::WindowFilter,
+ filter: &crate::WindowFilter,
_deadline: crate::Deadline,
) -> Result<Vec<crate::WindowInfo>, AdapterError> {
+ if self.expect_scoped_windows {
+ assert_eq!(filter.app.as_deref(), Some("Editor"));
+ }
Ok(vec![crate::WindowInfo {
id: "w-42".into(),
title: "Editor".into(),
@@ -115,6 +138,8 @@ impl SystemOps for CapturingAdapter {
policy: crate::InteractionPolicy,
_lease: &crate::InteractionLease,
) -> Result<ActionResult, AdapterError> {
+ self.dispatches
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
*self.app_policy.lock().unwrap() = Some(policy);
Ok(ActionResult::delivered_unverified("PressKey"))
}
@@ -210,3 +235,71 @@ fn app_targeted_press_threads_focus_authorization_to_adapter() {
Some(crate::InteractionPolicy::headed())
);
}
+
+fn saved_tree() -> crate::AccessibilityNode {
+ crate::AccessibilityNode {
+ ref_id: None,
+ role: "window".into(),
+ identity: crate::NodeIdentity {
+ name: Some("Saved!".into()),
+ ..Default::default()
+ },
+ presentation: Default::default(),
+ children_count: None,
+ subtree_truncated: false,
+ children: vec![],
+ }
+}
+
+#[test]
+fn press_waits_in_requested_app_without_repeating_delivery() {
+ let _home = crate::refs_test_support::HomeGuard::new();
+ for (query, gone, expected_error) in [
+ (":Saved!", false, None),
+ (":Missing", true, None),
+ (":Missing", false, Some("TIMEOUT")),
+ ("", false, Some("INVALID_ARGS")),
+ ] {
+ let adapter = CapturingAdapter {
+ expect_scoped_windows: true,
+ ..Default::default()
+ };
+ let mut request = args("a", false);
+ request.app = Some("Editor".into());
+ let context =
+ CommandContext::default().with_wait_selector(Some(crate::context::WaitSelector {
+ query_raw: query.into(),
+ gone,
+ timeout_ms: 20,
+ }));
+ let result = execute(request, &adapter, &context);
+ if let Some(code) = expected_error {
+ let error = result.unwrap_err();
+ assert_eq!(error.code(), code);
+ if code == "TIMEOUT" {
+ let crate::AppError::Adapter(error) = error else {
+ panic!("adapter error")
+ };
+ assert_eq!(
+ error.disposition,
+ crate::DeliverySemantics::delivered_unverified()
+ );
+ assert_eq!(
+ error.details.unwrap()["after_action"]["disposition"]["delivery"],
+ "delivered_unverified"
+ );
+ }
+ } else {
+ let value = result.unwrap();
+ assert_eq!(value["matched_selector"], query);
+ assert_eq!(
+ value["after_action"]["disposition"]["delivery"],
+ "delivered_unverified"
+ );
+ }
+ assert_eq!(
+ adapter.dispatches.load(std::sync::atomic::Ordering::SeqCst),
+ usize::from(expected_error != Some("INVALID_ARGS"))
+ );
+ }
+}
diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs
index 6f0571013..9b9ea3506 100644
--- a/crates/core/src/commands/wait.rs
+++ b/crates/core/src/commands/wait.rs
@@ -81,7 +81,7 @@ pub fn execute(
adapter,
context,
),
- WaitMode::Window(title) => wait_for_window(title, timeout_ms, adapter),
+ WaitMode::Window { title, app } => wait_for_window(title, app, timeout_ms, adapter),
WaitMode::Text { text, count, app } => wait_for_text(
TextWaitInput {
text,
@@ -133,6 +133,7 @@ fn wait_for_menu(
fn wait_for_window(
title: String,
+ app: Option<String>,
timeout_ms: u64,
adapter: &dyn PlatformAdapter,
) -> Result<Value, AppError> {
@@ -140,20 +141,28 @@ fn wait_for_window(
let deadline = crate::Deadline::at(start, timeout_ms)?;
let filter = WindowFilter {
focused_only: false,
- app: None,
+ app,
};
let mut last_error = None;
+ let mut last_observed = None;
loop {
if deadline.is_expired() {
- return wait_timeout::window(&title, timeout_ms, last_error);
+ return wait_timeout::window(
+ &title,
+ filter.app.as_deref(),
+ timeout_ms,
+ last_error,
+ last_observed,
+ );
}
match adapter.list_windows(&filter, deadline) {
Ok(windows) => {
- if let Some(win) = windows.into_iter().find(|w| w.title.contains(&title)) {
+ if let Some(win) = windows.iter().find(|w| w.title.contains(&title)) {
let elapsed = start.elapsed().as_millis();
return Ok(json!({ "found": true, "window": win, "elapsed_ms": elapsed }));
}
+ last_observed = Some(wait_timeout::window_observation(&windows));
}
Err(err) if is_retryable_wait_poll_error(&err.code) => {
last_error = Some(json!({
@@ -164,12 +173,7 @@ fn wait_for_window(
Err(err) => return Err(AppError::Adapter(err)),
}
- let remaining = deadline.remaining();
- if remaining.is_zero() {
- return wait_timeout::window(&title, timeout_ms, last_error);
- }
-
- std::thread::sleep(remaining.min(Duration::from_millis(100)));
+ std::thread::sleep(deadline.remaining().min(Duration::from_millis(100)));
}
}
diff --git a/crates/core/src/commands/wait_mode.rs b/crates/core/src/commands/wait_mode.rs
index 8c7cd48ae..a364db5c5 100644
--- a/crates/core/src/commands/wait_mode.rs
+++ b/crates/core/src/commands/wait_mode.rs
@@ -11,7 +11,10 @@ pub(crate) enum WaitMode {
snapshot_id: Option<String>,
predicate: wait_predicate::ElementPredicate,
},
- Window(String),
+ Window {
+ title: String,
+ app: Option<String>,
+ },
Text {
text: String,
count: Option<usize>,
@@ -82,7 +85,10 @@ impl WaitMode {
});
}
if let Some(title) = args.mode.window {
- return Ok(Self::Window(title));
+ return Ok(Self::Window {
+ title,
+ app: args.app,
+ });
}
if let Some(text) = args.mode.text {
return Ok(Self::Text {
diff --git a/crates/core/src/commands/wait_scenario_tests.rs b/crates/core/src/commands/wait_scenario_tests.rs
index b010d3d29..604f069c7 100644
--- a/crates/core/src/commands/wait_scenario_tests.rs
+++ b/crates/core/src/commands/wait_scenario_tests.rs
@@ -74,6 +74,86 @@ impl InputOps for TextlessTreeAdapter {}
impl SystemOps for TextlessTreeAdapter {}
+struct WindowWaitAdapter(Vec<WindowInfo>);
+
+impl ObservationOps for WindowWaitAdapter {
+ fn list_windows(
+ &self,
+ filter: &WindowFilter,
+ _deadline: crate::Deadline,
+ ) -> Result<Vec<WindowInfo>, AdapterError> {
+ Ok(self
+ .0
+ .iter()
+ .filter(|window| filter.app.as_ref().is_none_or(|app| &window.app == app))
+ .cloned()
+ .collect())
+ }
+}
+
+impl ActionOps for WindowWaitAdapter {}
+impl InputOps for WindowWaitAdapter {}
+impl SystemOps for WindowWaitAdapter {}
+
+#[test]
+fn window_wait_scopes_matches_and_missing_window_diagnostics_to_the_app() {
+ let mut project = TextlessTreeAdapter
+ .list_windows(
+ &WindowFilter::default(),
+ crate::Deadline::standard().unwrap(),
+ )
+ .unwrap()
+ .remove(0);
+ project.app = "GarageBand".into();
+ project.title = "Project".into();
+ let mut unrelated = project.clone();
+ unrelated.app = "OtherApp".into();
+ unrelated.title = "Musical Typing".into();
+ let adapter = WindowWaitAdapter(vec![project, unrelated]);
+ let mut args = WaitArgs {
+ mode: WaitModeArgs {
+ window: Some("Musical Typing".into()),
+ ..wait_args().mode
+ },
+ timeout_ms: 20,
+ ..wait_args()
+ };
+ let result = execute(args.clone(), &adapter, &CommandContext::default()).unwrap();
+ assert_eq!(result["window"]["app_name"], "OtherApp");
+
+ args.app = Some("GarageBand".into());
+ let error = execute(args.clone(), &adapter, &CommandContext::default()).unwrap_err();
+ let AppError::Adapter(error) = error else {
+ panic!("adapter error expected")
+ };
+ assert_eq!(error.code, ErrorCode::Timeout);
+ let details = error.details.unwrap();
+ assert_eq!(details["title"], "Musical Typing");
+ assert_eq!(details["app"], "GarageBand");
+ assert_eq!(details["last_observed"]["count"], 1);
+ assert_eq!(details["last_observed"]["titles"], json!(["Project"]));
+
+ args.mode.window = Some("Pro".into());
+ let result = execute(args, &adapter, &CommandContext::default()).unwrap();
+ assert_eq!(result["window"]["app_name"], "GarageBand");
+}
+
+#[test]
+fn missing_window_diagnostics_bound_count_and_unicode_title_length() {
+ let mut windows = TextlessTreeAdapter
+ .list_windows(
+ &WindowFilter::default(),
+ crate::Deadline::standard().unwrap(),
+ )
+ .unwrap();
+ windows[0].title = "é".repeat(150);
+ let observed = wait_timeout::window_observation(&vec![windows[0].clone(); 10]);
+ assert_eq!(observed["count"], 10);
+ assert_eq!(observed["titles"].as_array().unwrap().len(), 8);
+ assert_eq!(observed["titles"][0].as_str().unwrap().chars().count(), 120);
+ assert_eq!(observed["truncated"], true);
+}
+
#[test]
fn text_wait_with_count_zero_detects_absence() {
let _guard = crate::refs_test_support::HomeGuard::new();
diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs
index d1ba8c3d1..ee06b5b50 100644
--- a/crates/core/src/commands/wait_timeout.rs
+++ b/crates/core/src/commands/wait_timeout.rs
@@ -41,25 +41,42 @@ fn with_last_error(mut details: Value, last_error: Option<Value>) -> Value {
pub(crate) fn window(
title: &str,
+ app: Option<&str>,
timeout_ms: u64,
last_error: Option<Value>,
+ last_observed: Option<Value>,
) -> Result<Value, AppError> {
+ let mut details = json!({
+ "predicate": "window",
+ "title": title,
+ "timeout_ms": timeout_ms,
+ });
+ if let Some(app) = app {
+ details["app"] = json!(app);
+ }
+ if let Some(last_observed) = last_observed {
+ details["last_observed"] = last_observed;
+ }
timeout_err(
format!(
"Window title ({} chars) not found within {timeout_ms}ms",
title.chars().count()
),
- with_last_error(
- json!({
- "predicate": "window",
- "title": title,
- "timeout_ms": timeout_ms,
- }),
- last_error,
- ),
+ with_last_error(details, last_error),
)
}
+pub(crate) fn window_observation(windows: &[crate::WindowInfo]) -> Value {
+ json!({
+ "count": windows.len(),
+ "titles": windows.iter().take(8)
+ .map(|window| window.title.chars().take(120).collect::<String>())
+ .collect::<Vec<_>>(),
+ "truncated": windows.len() > 8 || windows.iter().take(8)
+ .any(|window| window.title.chars().nth(120).is_some()),
+ })
+}
+
pub(crate) fn text(
text: &str,
timeout_ms: u64,
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index 5080a46db..5b9dad27a 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -8,6 +8,7 @@ use std::cell::Cell;
use std::path::PathBuf;
use std::time::Instant;
+mod cursor;
mod options;
mod session_scope;
mod wait_selector;
@@ -100,6 +101,7 @@ impl CommandContext {
artifacts_full,
options: CommandOptions {
cursor_overlay,
+ agent_id: None,
..CommandOptions::default()
},
})
@@ -140,12 +142,6 @@ impl CommandContext {
&self.options.cursor_overlay
}
- #[cfg(test)]
- pub(crate) fn with_cursor_overlay(mut self, cursor_overlay: CursorOverlayConfig) -> Self {
- self.options.cursor_overlay = cursor_overlay;
- self
- }
-
#[cfg(test)]
pub(crate) fn with_cursor_overlay_session(
mut self,
@@ -255,7 +251,10 @@ impl CommandContext {
let cursor_overlay = if reuses_parent_session {
self.options.cursor_overlay.clone()
} else {
- session::cursor_overlay_for_session(session.as_ref().map(|scope| scope.id.as_str()))?
+ session::cursor_overlay_for_session_agent(
+ session.as_ref().map(|scope| scope.id.as_str()),
+ self.agent_id(),
+ )?
};
Ok(Self {
session,
diff --git a/crates/core/src/context/cursor.rs b/crates/core/src/context/cursor.rs
new file mode 100644
index 000000000..9cbf6ce04
--- /dev/null
+++ b/crates/core/src/context/cursor.rs
@@ -0,0 +1,29 @@
+use super::CommandContext;
+use crate::{AppError, session};
+
+impl CommandContext {
+ pub fn with_agent_id(mut self, agent_id: Option<String>) -> Result<Self, AppError> {
+ if self.options.agent_id == agent_id {
+ return Ok(self);
+ }
+ if let Some(id) = agent_id.as_deref() {
+ session::validate_agent_id(id)?;
+ }
+ self.options.agent_id = agent_id;
+ if let Some(session_id) = self.session_id() {
+ self.options.cursor_overlay = session::cursor_overlay_for_session_agent(
+ Some(session_id),
+ self.options.agent_id.as_deref(),
+ )?;
+ }
+ Ok(self)
+ }
+
+ pub fn agent_id(&self) -> Option<&str> {
+ self.options.agent_id.as_deref()
+ }
+
+ pub fn multi_agent(&self) -> bool {
+ self.options.cursor_overlay.is_multi_agent()
+ }
+}
diff --git a/crates/core/src/context/options.rs b/crates/core/src/context/options.rs
index 21b5f5052..5a7db7c21 100644
--- a/crates/core/src/context/options.rs
+++ b/crates/core/src/context/options.rs
@@ -8,6 +8,7 @@ pub(super) struct CommandOptions {
pub wait_selector: Option<WaitSelector>,
pub event_baseline: Option<Result<SignalBaseline, AdapterError>>,
pub cursor_overlay: CursorOverlayConfig,
+ pub agent_id: Option<String>,
}
impl CommandOptions {
@@ -17,6 +18,7 @@ impl CommandOptions {
wait_selector: None,
event_baseline: None,
cursor_overlay,
+ agent_id: self.agent_id.clone(),
}
}
}
diff --git a/crates/core/src/cursor_overlay/config.rs b/crates/core/src/cursor_overlay/config.rs
index 0866e249b..014ec2d66 100644
--- a/crates/core/src/cursor_overlay/config.rs
+++ b/crates/core/src/cursor_overlay/config.rs
@@ -17,6 +17,8 @@ pub struct CursorOverlayConfig {
max_words: usize,
#[serde(default)]
style: CursorOverlayStyle,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ multi_agent: bool,
}
impl CursorOverlayConfig {
@@ -26,6 +28,7 @@ impl CursorOverlayConfig {
label,
max_words,
style: CursorOverlayStyle::default(),
+ multi_agent: false,
}
.validated()
}
@@ -35,6 +38,15 @@ impl CursorOverlayConfig {
Ok(self)
}
+ pub fn with_multi_agent(mut self, enabled: bool) -> Self {
+ self.multi_agent = enabled;
+ self
+ }
+
+ pub const fn is_multi_agent(&self) -> bool {
+ self.multi_agent
+ }
+
pub const fn style(&self) -> &CursorOverlayStyle {
&self.style
}
@@ -96,6 +108,7 @@ impl Default for CursorOverlayConfig {
label: None,
max_words: DEFAULT_CURSOR_LABEL_WORDS,
style: CursorOverlayStyle::default(),
+ multi_agent: false,
}
}
}
diff --git a/crates/core/src/cursor_overlay/control.rs b/crates/core/src/cursor_overlay/control.rs
index f0d7fffcb..65529ec7b 100644
--- a/crates/core/src/cursor_overlay/control.rs
+++ b/crates/core/src/cursor_overlay/control.rs
@@ -1,5 +1,5 @@
use super::{CursorOverlayInstruction, CursorOverlayStyle, CursorPhase};
-use crate::{AdapterError, ErrorCode, context::validate_session_id};
+use crate::{AdapterError, ErrorCode, context::validate_session_id, session::validate_agent_id};
use serde::{Deserialize, Serialize};
pub const CURSOR_OVERLAY_GREETING: &str = "Hey, let's play with this computer!";
@@ -10,20 +10,28 @@ pub enum CursorOverlayControl {
Enable {
session_id: String,
label: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
#[serde(default)]
style: CursorOverlayStyle,
},
Present {
session_id: String,
instruction: CursorOverlayInstruction,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
#[serde(default)]
style: CursorOverlayStyle,
},
Hide {
session_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
},
Show {
session_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
},
Disable {
session_id: String,
@@ -35,6 +43,7 @@ impl CursorOverlayControl {
Self::Enable {
session_id,
label: CURSOR_OVERLAY_GREETING.into(),
+ agent_id: None,
style,
}
}
@@ -58,6 +67,7 @@ impl CursorOverlayControl {
Self::Present {
session_id,
instruction,
+ agent_id: None,
style,
}
}
@@ -67,17 +77,49 @@ impl CursorOverlayControl {
}
pub fn hide(session_id: String) -> Self {
- Self::Hide { session_id }
+ Self::Hide {
+ session_id,
+ agent_id: None,
+ }
}
pub fn show(session_id: String) -> Self {
- Self::Show { session_id }
+ Self::Show {
+ session_id,
+ agent_id: None,
+ }
+ }
+
+ pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
+ match &mut self {
+ Self::Enable { agent_id: id, .. }
+ | Self::Present { agent_id: id, .. }
+ | Self::Hide { agent_id: id, .. }
+ | Self::Show { agent_id: id, .. } => *id = agent_id,
+ Self::Disable { .. } => {}
+ }
+ self
+ }
+
+ pub fn agent_id(&self) -> Option<&str> {
+ match self {
+ Self::Enable { agent_id, .. }
+ | Self::Present { agent_id, .. }
+ | Self::Hide { agent_id, .. }
+ | Self::Show { agent_id, .. } => agent_id.as_deref(),
+ Self::Disable { .. } => None,
+ }
}
pub fn validate(&self) -> Result<(), AdapterError> {
validate_session_id(self.session_id()).map_err(|_| {
AdapterError::new(ErrorCode::InvalidArgs, "Invalid cursor overlay session id")
})?;
+ if let Some(agent_id) = self.agent_id() {
+ validate_agent_id(agent_id).map_err(|_| {
+ AdapterError::new(ErrorCode::InvalidArgs, "Invalid cursor overlay agent id")
+ })?;
+ }
if let Self::Present { instruction, .. } = self {
instruction.validate()?;
}
@@ -88,8 +130,8 @@ impl CursorOverlayControl {
match self {
Self::Enable { session_id, .. }
| Self::Present { session_id, .. }
- | Self::Hide { session_id }
- | Self::Show { session_id }
+ | Self::Hide { session_id, .. }
+ | Self::Show { session_id, .. }
| Self::Disable { session_id } => session_id,
}
}
@@ -114,12 +156,11 @@ impl CursorOverlayControl {
matches!(self, Self::Hide { .. } | Self::Show { .. })
}
- /// A travel control moves the cursor and carries no click effect. Every
- /// platform renderer must acknowledge it once the cursor lands, because the
- /// action waits for that acknowledgement before it dispatches.
+ /// A pre-dispatch control must be acknowledged before its action dispatches.
pub fn is_travel(&self) -> bool {
- self.instruction()
- .is_some_and(|instruction| instruction.phase() == CursorPhase::Travel)
+ self.instruction().is_some_and(|instruction| {
+ matches!(instruction.phase(), CursorPhase::Travel | CursorPhase::Drag)
+ })
}
pub const fn is_hide(&self) -> bool {
diff --git a/crates/core/src/cursor_overlay/instruction.rs b/crates/core/src/cursor_overlay/instruction.rs
index 3a0477434..f9aa95d4d 100644
--- a/crates/core/src/cursor_overlay/instruction.rs
+++ b/crates/core/src/cursor_overlay/instruction.rs
@@ -6,6 +6,8 @@ use serde::{Deserialize, Serialize};
#[serde(deny_unknown_fields)]
pub struct CursorOverlayInstruction {
destination: Point,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ drag_from: Option<Point>,
#[serde(skip_serializing_if = "Option::is_none")]
label: Option<String>,
click: bool,
@@ -30,6 +32,7 @@ impl CursorOverlayInstruction {
}
Ok(Self {
destination,
+ drag_from: None,
label: config.label().map(str::to_owned),
click,
target: None,
@@ -42,6 +45,15 @@ impl CursorOverlayInstruction {
self
}
+ pub fn with_drag_from(mut self, drag_from: Option<Point>) -> Self {
+ self.drag_from = drag_from;
+ self
+ }
+
+ pub const fn drag_from(&self) -> Option<&Point> {
+ self.drag_from.as_ref()
+ }
+
pub const fn phase(&self) -> CursorPhase {
self.phase
}
@@ -57,7 +69,11 @@ impl CursorOverlayInstruction {
}
pub fn validate(&self) -> Result<(), AdapterError> {
- self.destination.validate()
+ self.destination.validate()?;
+ if let Some(drag_from) = &self.drag_from {
+ drag_from.validate()?;
+ }
+ Ok(())
}
pub fn destination(&self) -> &Point {
diff --git a/crates/core/src/cursor_overlay/mod.rs b/crates/core/src/cursor_overlay/mod.rs
index 9bc33bec7..4069e6c35 100644
--- a/crates/core/src/cursor_overlay/mod.rs
+++ b/crates/core/src/cursor_overlay/mod.rs
@@ -18,7 +18,10 @@ pub use motion::CursorMotion;
pub use phase::CursorPhase;
pub use pose::CursorPose;
pub use style::CursorOverlayStyle;
-pub(crate) use submit::submit;
+pub(crate) use submit::{
+ cancel_drag, confirms_delivery, dispatch_mouse_event_with_cursor, input_was_delivered, submit,
+ submit_drag, submit_drag_effect, submit_travel,
+};
pub use timing::{CURSOR_ARRIVAL_TIMEOUT_MS, CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS};
#[cfg(test)]
diff --git a/crates/core/src/cursor_overlay/phase.rs b/crates/core/src/cursor_overlay/phase.rs
index 1fff06c88..1cf713ed3 100644
--- a/crates/core/src/cursor_overlay/phase.rs
+++ b/crates/core/src/cursor_overlay/phase.rs
@@ -2,13 +2,14 @@ use serde::{Deserialize, Serialize};
/// Which half of an action a cursor instruction represents.
///
-/// `Travel` is sent before the action dispatches and every platform renderer
-/// must acknowledge it once the cursor lands. `Effect` is sent after dispatch
-/// confirms and is fire-and-forget.
+/// `Travel` is sent before an action and acknowledged once the cursor lands.
+/// `Drag` arms pointer tracking and is acknowledged once the renderer is ready.
+/// `Effect` is sent after dispatch and is fire-and-forget.
#[derive(Debug, Clone, Copy, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CursorPhase {
#[default]
Travel,
+ Drag,
Effect,
}
diff --git a/crates/core/src/cursor_overlay/submit.rs b/crates/core/src/cursor_overlay/submit.rs
index 2a7acf8da..0470a3608 100644
--- a/crates/core/src/cursor_overlay/submit.rs
+++ b/crates/core/src/cursor_overlay/submit.rs
@@ -1,5 +1,57 @@
use super::CursorPhase;
-use crate::{CommandContext, PlatformAdapter, Point, Rect};
+use crate::{
+ AdapterError, CommandContext, DeliveryDisposition, DeliverySemantics, MouseEvent,
+ PlatformAdapter, Point, Rect,
+};
+
+const DISPATCH_RESERVE_MS: u64 = 100;
+
+pub(crate) fn travel_scope(
+ lease: &crate::InteractionLease,
+) -> Option<crate::deadline::DeadlineScope> {
+ if lease.deadline().remaining_ms()
+ <= crate::CURSOR_ARRIVAL_TIMEOUT_MS.saturating_add(DISPATCH_RESERVE_MS)
+ {
+ return None;
+ }
+ Some(crate::deadline::enter_scope(Some(lease.deadline().capped(
+ std::time::Duration::from_millis(crate::CURSOR_ARRIVAL_TIMEOUT_MS),
+ ))))
+}
+
+pub(crate) fn submit_travel(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ destination: Point,
+ lease: &crate::InteractionLease,
+) {
+ let Some(_scope) = travel_scope(lease) else {
+ return;
+ };
+ submit(
+ adapter,
+ context,
+ destination,
+ None,
+ false,
+ CursorPhase::Travel,
+ );
+}
+
+pub(crate) fn input_was_delivered(result: &Result<(), AdapterError>) -> bool {
+ result
+ .as_ref()
+ .map_or_else(|error| confirms_delivery(error.disposition), |_| true)
+}
+
+pub(crate) fn confirms_delivery(disposition: DeliverySemantics) -> bool {
+ matches!(
+ disposition.delivery(),
+ DeliveryDisposition::DeliveryUncertain
+ | DeliveryDisposition::DeliveredUnverified
+ | DeliveryDisposition::DeliveredVerified
+ )
+}
pub(crate) fn submit(
adapter: &dyn PlatformAdapter,
@@ -9,26 +61,123 @@ pub(crate) fn submit(
click: bool,
phase: CursorPhase,
) {
- if context.is_headed() || !context.cursor_overlay().is_enabled() {
+ let instruction =
+ super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), click)
+ .map(|instruction| instruction.with_target(target).with_phase(phase));
+ let _ = send(adapter, context, instruction);
+}
+
+pub(crate) fn submit_drag(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ drag_from: Point,
+ destination: Point,
+ lease: &crate::InteractionLease,
+) -> bool {
+ let Some(_scope) = travel_scope(lease) else {
+ return false;
+ };
+ let instruction =
+ super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), false).map(
+ |instruction| {
+ instruction
+ .with_drag_from(Some(drag_from))
+ .with_phase(CursorPhase::Drag)
+ },
+ );
+ send(adapter, context, instruction)
+}
+
+pub(crate) fn submit_drag_effect(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ drag_from: Point,
+ destination: Point,
+) {
+ let instruction =
+ super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), false).map(
+ |instruction| {
+ instruction
+ .with_drag_from(Some(drag_from))
+ .with_phase(CursorPhase::Effect)
+ },
+ );
+ let _ = send(adapter, context, instruction);
+}
+
+pub(crate) fn cancel_drag(adapter: &dyn PlatformAdapter, context: &CommandContext) {
+ let Ok(cleanup_deadline) = crate::Deadline::detached_after(crate::CURSOR_ARRIVAL_TIMEOUT_MS)
+ else {
return;
- }
- let Some(session_id) = context.session_id() else {
+ };
+ let _scope = crate::deadline::enter_scope(Some(cleanup_deadline));
+ let Some(session_id) = enabled_session(context) else {
return;
};
- let instruction =
- match super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), click) {
- Ok(instruction) => instruction.with_target(target).with_phase(phase),
- Err(error) => {
- tracing::warn!(code = %error.code.as_str(), "agent cursor instruction was skipped");
- return;
- }
- };
+ let control = super::CursorOverlayControl::hide(session_id.to_owned())
+ .with_agent_id(context.agent_id().map(str::to_owned));
+ let _ = update(adapter, &control);
+}
+
+fn send(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ instruction: Result<super::CursorOverlayInstruction, AdapterError>,
+) -> bool {
+ let Some(session_id) = enabled_session(context) else {
+ return false;
+ };
+ let instruction = match instruction {
+ Ok(instruction) => instruction,
+ Err(error) => {
+ tracing::warn!(code = %error.code.as_str(), "agent cursor instruction was skipped");
+ return false;
+ }
+ };
let control = super::CursorOverlayControl::present_with_style(
session_id.to_owned(),
instruction,
context.cursor_overlay().style().clone(),
- );
- if let Err(error) = adapter.update_cursor_overlay(&control) {
+ )
+ .with_agent_id(context.agent_id().map(str::to_owned));
+ update(adapter, &control)
+}
+
+fn enabled_session(context: &CommandContext) -> Option<&str> {
+ if context.cursor_overlay().is_enabled() {
+ context.session_id()
+ } else {
+ None
+ }
+}
+
+fn update(adapter: &dyn PlatformAdapter, control: &super::CursorOverlayControl) -> bool {
+ if let Err(error) = adapter.update_cursor_overlay(control) {
tracing::warn!(code = %error.code.as_str(), "agent cursor presentation was skipped");
+ return false;
+ }
+ true
+}
+
+pub(crate) fn dispatch_mouse_event_with_cursor(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ event: MouseEvent,
+ click: bool,
+ lease: &crate::InteractionLease,
+) -> Result<(), AdapterError> {
+ let point = event.point.clone();
+ crate::cursor_overlay::submit_travel(adapter, context, point.clone(), lease);
+ let result = adapter.mouse_event(event, lease);
+ if crate::cursor_overlay::input_was_delivered(&result) {
+ crate::cursor_overlay::submit(
+ adapter,
+ context,
+ point,
+ None,
+ click,
+ crate::CursorPhase::Effect,
+ );
}
+ result
}
diff --git a/crates/core/src/cursor_overlay/tests.rs b/crates/core/src/cursor_overlay/tests.rs
index 34b413675..3387f14af 100644
--- a/crates/core/src/cursor_overlay/tests.rs
+++ b/crates/core/src/cursor_overlay/tests.rs
@@ -1,5 +1,11 @@
use super::*;
-use crate::{Point, Rect};
+use crate::{
+ AdapterError, CommandContext, Deadline, DeliverySemantics, InteractionLease, MouseButton,
+ MouseEvent, MouseEventKind, Point, Rect,
+ adapter::{ActionOps, InputOps, ObservationOps, SystemOps},
+};
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicU32, Ordering};
#[test]
fn motion_reaches_both_endpoints_and_curves_between_them() {
@@ -101,6 +107,55 @@ fn instruction_rejects_invalid_destination() {
assert_eq!(error.code, crate::ErrorCode::InvalidArgs);
}
+#[test]
+fn instruction_carries_and_validates_drag_origin() {
+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let origin = Point { x: 1.0, y: 2.0 };
+ let instruction = CursorOverlayInstruction::new(Point { x: 3.0, y: 4.0 }, &config, false)
+ .expect("valid instruction")
+ .with_drag_from(Some(origin.clone()));
+
+ assert_eq!(instruction.drag_from(), Some(&origin));
+ assert_eq!(
+ serde_json::to_value(&instruction).expect("instruction serializes")["drag_from"],
+ serde_json::json!({ "x": 1.0, "y": 2.0 })
+ );
+ assert!(
+ CursorOverlayInstruction::new(Point { x: 3.0, y: 4.0 }, &config, false)
+ .expect("valid instruction")
+ .with_drag_from(Some(Point {
+ x: f64::NAN,
+ y: 2.0,
+ }))
+ .validate()
+ .is_err()
+ );
+ let without_origin = CursorOverlayInstruction::new(Point { x: 3.0, y: 4.0 }, &config, false)
+ .expect("valid instruction");
+ assert!(
+ serde_json::to_value(without_origin)
+ .expect("instruction serializes")
+ .get("drag_from")
+ .is_none()
+ );
+}
+
+#[test]
+fn drag_phase_is_serialized_and_requires_acknowledgement() {
+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let instruction = CursorOverlayInstruction::new(Point { x: 3.0, y: 4.0 }, &config, false)
+ .expect("valid instruction")
+ .with_drag_from(Some(Point { x: 1.0, y: 2.0 }))
+ .with_phase(CursorPhase::Drag);
+ let control = CursorOverlayControl::present("run-1".into(), instruction);
+
+ assert!(control.is_travel());
+ assert_eq!(
+ serde_json::to_value(control).expect("control serializes")["instruction"]["phase"],
+ "drag"
+ );
+}
+
#[test]
fn control_protocol_carries_the_session_lifecycle() {
let enable = CursorOverlayControl::enable("run-1".into(), CursorOverlayStyle::default());
@@ -113,6 +168,20 @@ fn control_protocol_carries_the_session_lifecycle() {
assert!(disable.is_disable());
}
+#[test]
+fn control_protocol_preserves_named_agent_identity() {
+ let control = CursorOverlayControl::hide("run-1".into()).with_agent_id(Some("agent-a".into()));
+ assert_eq!(control.agent_id(), Some("agent-a"));
+ let encoded = serde_json::to_value(control).expect("control serializes");
+ assert_eq!(encoded["agent_id"], "agent-a");
+ assert!(
+ CursorOverlayControl::disable("run-1".into())
+ .with_agent_id(Some("ignored".into()))
+ .agent_id()
+ .is_none()
+ );
+}
+
#[test]
fn present_control_carries_the_session_style() {
let mut style = CursorOverlayStyle::default();
@@ -179,6 +248,125 @@ fn a_disabled_ripple_keeps_the_click_silent() {
assert_eq!(motion.pose(motion.total_ms()).ripple, 0.0);
}
+struct OverlayCaptureAdapter {
+ presented: Mutex<Vec<CursorOverlayControl>>,
+ input_index: AtomicU32,
+ input_failure: Option<DeliverySemantics>,
+}
+
+impl OverlayCaptureAdapter {
+ fn with_failure(input_failure: Option<DeliverySemantics>) -> Self {
+ Self {
+ presented: Mutex::new(Vec::new()),
+ input_index: AtomicU32::new(0),
+ input_failure,
+ }
+ }
+}
+
+impl ObservationOps for OverlayCaptureAdapter {}
+impl ActionOps for OverlayCaptureAdapter {}
+
+impl InputOps for OverlayCaptureAdapter {
+ fn mouse_event(
+ &self,
+ _event: MouseEvent,
+ _lease: &InteractionLease,
+ ) -> Result<(), AdapterError> {
+ self.input_index.store(
+ self.presented.lock().unwrap().len() as u32,
+ Ordering::SeqCst,
+ );
+ if let Some(disposition) = self.input_failure {
+ let error = AdapterError::internal("input failed").with_disposition(disposition);
+ return Err(error);
+ }
+ Ok(())
+ }
+}
+
+impl SystemOps for OverlayCaptureAdapter {
+ crate::adapter::guarded_interaction_lease!();
+
+ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ self.presented.lock().unwrap().push(control.clone());
+ Ok(())
+ }
+}
+
+fn overlay_context() -> CommandContext {
+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ CommandContext::default().with_cursor_overlay_session("test-session", config)
+}
+
+fn lease_with_timeout_ms(timeout_ms: u64) -> InteractionLease {
+ let deadline = Deadline::detached_after(timeout_ms).expect("valid deadline");
+ InteractionLease::guarded(deadline, ()).expect("valid lease")
+}
+
+fn run_travel_helper(
+ input_failure: Option<DeliverySemantics>,
+) -> (Result<(), AdapterError>, Vec<CursorPhase>, u32) {
+ let adapter = OverlayCaptureAdapter::with_failure(input_failure);
+ let context = overlay_context();
+ let lease = lease_with_timeout_ms(5_000);
+ let event = MouseEvent {
+ kind: MouseEventKind::Move,
+ point: Point { x: 10.0, y: 20.0 },
+ button: MouseButton::Left,
+ modifiers: Vec::new(),
+ };
+ let result = dispatch_mouse_event_with_cursor(&adapter, &context, event, true, &lease);
+ let phases = adapter
+ .presented
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|control| control.instruction().expect("cursor instruction").phase())
+ .collect();
+ let input_index = adapter.input_index.load(Ordering::SeqCst);
+ (result, phases, input_index)
+}
+
+#[test]
+fn travel_helper_submits_travel_then_effect_around_delivered_input() {
+ let (result, phases, input_index) = run_travel_helper(None);
+
+ assert!(result.is_ok());
+ assert_eq!(phases, vec![CursorPhase::Travel, CursorPhase::Effect]);
+ assert_eq!(input_index, 1);
+}
+
+#[test]
+fn travel_helper_skips_effect_when_input_is_not_delivered() {
+ let (result, phases, input_index) = run_travel_helper(Some(DeliverySemantics::not_delivered()));
+
+ assert!(result.is_err());
+ assert_eq!(phases, vec![CursorPhase::Travel]);
+ assert_eq!(input_index, 1);
+}
+
+#[test]
+fn travel_helper_still_marks_effect_when_delivery_is_uncertain() {
+ let (result, phases, input_index) = run_travel_helper(Some(DeliverySemantics::uncertain()));
+
+ assert!(result.is_err());
+ assert_eq!(phases, vec![CursorPhase::Travel, CursorPhase::Effect]);
+ assert_eq!(input_index, 1);
+}
+
+/// Pins the arrival guard: remaining exactly covering arrival plus the
+/// dispatch reserve still skips the overlay; a healthy lease enters scope.
+#[test]
+fn travel_scope_decides_arrival_scope_at_the_budget_boundary() {
+ let dispatch_reserve_ms = 100;
+ let starved = lease_with_timeout_ms(CURSOR_ARRIVAL_TIMEOUT_MS + dispatch_reserve_ms);
+ let healthy = lease_with_timeout_ms(5_000);
+
+ assert!(super::submit::travel_scope(&starved).is_none());
+ assert!(super::submit::travel_scope(&healthy).is_some());
+}
+
#[test]
fn a_clicked_target_rect_reaches_the_renderer() {
let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
diff --git a/crates/core/src/file_lock.rs b/crates/core/src/file_lock.rs
index 4d1361a94..b36ed317c 100644
--- a/crates/core/src/file_lock.rs
+++ b/crates/core/src/file_lock.rs
@@ -4,18 +4,15 @@ use std::time::Duration;
use crate::{AdapterError, Deadline, ErrorCode};
-pub(crate) struct FileLock {
- file: File,
+/// A private state-file lock held until this guard is dropped.
+pub struct FileLock {
+ _file: File,
#[cfg(unix)]
contention_count: u64,
}
impl FileLock {
- pub(crate) fn acquire(
- path: &Path,
- deadline: Deadline,
- purpose: &str,
- ) -> Result<Self, AdapterError> {
+ pub fn acquire(path: &Path, deadline: Deadline, purpose: &str) -> Result<Self, AdapterError> {
let file = crate::private_file::open_private_lock(path, true).map_err(io_error)?;
lock_file(file, deadline, purpose, path)
}
@@ -43,7 +40,7 @@ impl FileLock {
pub(crate) fn duplicate_inheritable(&self) -> Result<std::os::fd::OwnedFd, AdapterError> {
use std::os::fd::{AsRawFd, FromRawFd};
- let duplicated = unsafe { libc::fcntl(self.file.as_raw_fd(), libc::F_DUPFD, 3) };
+ let duplicated = unsafe { libc::fcntl(self._file.as_raw_fd(), libc::F_DUPFD, 3) };
if duplicated < 0 {
return Err(io_error(std::io::Error::last_os_error()));
}
@@ -89,12 +86,6 @@ impl FileLock {
}
}
-impl Drop for FileLock {
- fn drop(&mut self) {
- let _ = self.file.unlock();
- }
-}
-
fn lock_file(
file: File,
deadline: Deadline,
@@ -109,11 +100,10 @@ fn lock_file(
match file.try_lock() {
Ok(()) => {
if deadline.is_expired() {
- let _ = file.unlock();
return Err(lock_timeout(deadline, purpose, path, contention_count));
}
return Ok(FileLock {
- file,
+ _file: file,
#[cfg(unix)]
contention_count,
});
diff --git a/crates/core/src/interaction_lease_tests.rs b/crates/core/src/interaction_lease_tests.rs
index 0838ee13b..25f53bbb8 100644
--- a/crates/core/src/interaction_lease_tests.rs
+++ b/crates/core/src/interaction_lease_tests.rs
@@ -174,8 +174,6 @@ fn inherited_descriptor_survives_parent_drop_and_crash_releases() {
)
.spawn()
.unwrap();
- drop(inherited);
- drop(lease);
let ready_deadline = std::time::Instant::now() + Duration::from_secs(2);
while !ready.is_file() && std::time::Instant::now() < ready_deadline {
std::thread::sleep(Duration::from_millis(10));
@@ -184,6 +182,8 @@ fn inherited_descriptor_survives_parent_drop_and_crash_releases() {
ready.is_file(),
"subprocess did not adopt interaction lease"
);
+ drop(inherited);
+ drop(lease);
let error = acquire_unix_interaction_lease_at(Deadline::after(25).unwrap(), &root)
.err()
.expect("adopted descriptor must retain the lease");
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 32b4063e5..3dd3610b9 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -188,6 +188,7 @@ pub use element_identifier::ElementIdentifier;
pub use element_state::ElementState;
pub use error_code::ErrorCode;
pub use event_kind::EventKind;
+pub use file_lock::FileLock;
pub use headed_requirement::HeadedRequirement;
pub use hit_test::HitTestResult;
pub use identifier_kind::IdentifierKind;
diff --git a/crates/core/src/live_locator/evaluate.rs b/crates/core/src/live_locator/evaluate.rs
index 0d8b85731..830b3e6e6 100644
--- a/crates/core/src/live_locator/evaluate.rs
+++ b/crates/core/src/live_locator/evaluate.rs
@@ -8,7 +8,6 @@ use super::{
predicate::{normalize_query, self_text_verdict, self_verdict},
select::{match_data, selected_indices},
selection_completeness::first_is_authoritative,
- tree_order::validated_postorder,
validate::{validate_query, validate_request},
};
use crate::{AdapterError, locator::LocatorQuery};
@@ -24,7 +23,12 @@ pub fn evaluate_locator_tree(
let normalized = normalize_query(query);
let mut clauses = Vec::new();
let root_clause = compile_clauses(&normalized, &mut clauses);
- let (postorder, parents) = validated_postorder(&tree)?;
+ let mut parents = vec![None; tree.nodes.len()];
+ for (index, node) in tree.nodes.iter().enumerate() {
+ for child in &node.children {
+ parents[*child as usize] = Some(index);
+ }
+ }
let cells = tree
.nodes
.len()
@@ -47,7 +51,7 @@ pub fn evaluate_locator_tree(
subtree_text: subtree_text.as_mut_slice(),
stats: &mut stats,
};
- for node_index in postorder {
+ for node_index in (0..tree.nodes.len()).rev() {
evaluate_node(&tree, node_index, &clauses, &mut buffers);
}
}
@@ -61,7 +65,6 @@ pub fn evaluate_locator_tree(
MatchVerdict::NoMatch => {}
}
}
- matched_indices.sort_by_key(|index| tree.nodes[*index].document_order);
stats.evaluation.matched_nodes = matched_indices.len() as u64;
let (selected, truncated) = selected_indices(&matched_indices, request.selection);
let mut complete = tree.structurally_complete && !unknown;
@@ -115,12 +118,12 @@ pub fn evaluate_locator_tree(
let root_verdicts = (0..tree.nodes.len())
.map(|index| matches[cell(index, root_clause, clauses.len())])
.collect::<Vec<_>>();
- tree.nodes
- .iter()
- .position(|node| node.document_order == selected.document_order)
- .is_some_and(|index| {
- first_is_authoritative(&tree, index, &parents, &root_verdicts)
- })
+ first_is_authoritative(
+ &tree,
+ selected.document_order as usize,
+ &parents,
+ &root_verdicts,
+ )
})
};
Ok(LocatorResolution {
diff --git a/crates/core/src/live_locator/evaluator_tests.rs b/crates/core/src/live_locator/evaluator_tests.rs
index 828320b3f..514942554 100644
--- a/crates/core/src/live_locator/evaluator_tests.rs
+++ b/crates/core/src/live_locator/evaluator_tests.rs
@@ -33,9 +33,9 @@ fn named_query(name: &str, exact: bool) -> LocatorQuery {
fn names_tree() -> super::ObservedTree {
tree(
vec![
- node(2, evidence("button", Some("SAVE")), vec![], &[]),
node(0, evidence("button", Some("Save draft")), vec![], &[]),
node(1, evidence("button", Some("save")), vec![], &[]),
+ node(2, evidence("button", Some("SAVE")), vec![], &[]),
],
vec![0, 1, 2],
true,
@@ -67,29 +67,27 @@ fn exact_and_substring_matching_use_normalized_document_order() {
}
fn deep_tree(structurally_complete: bool) -> super::ObservedTree {
- let mut nodes = vec![node(
- 30,
- evidence("button", Some("Deep Needle")),
- vec![],
- &vec![0; 30],
- )];
- let mut child = 0;
- for depth in (0..30).rev() {
+ let mut nodes = Vec::new();
+ for depth in 0..30 {
let name = (depth == 0).then_some("root");
- let index = nodes.len() as u32;
let mut parent = node(
depth,
evidence("group", name),
- vec![child],
+ vec![depth + 1],
&vec![0; depth as usize],
);
if depth == 0 {
parent.completeness.subtree_complete = structurally_complete;
}
nodes.push(parent);
- child = index;
}
- tree(nodes, vec![child], structurally_complete)
+ nodes.push(node(
+ 30,
+ evidence("button", Some("Deep Needle")),
+ vec![],
+ &vec![0; 30],
+ ));
+ tree(nodes, vec![0], structurally_complete)
}
#[test]
@@ -215,7 +213,33 @@ fn candidate_role_with_unknown_name_remains_incomplete() {
}
#[test]
-fn ordinal_selection_uses_document_order_not_arena_order() {
+fn later_known_fields_decide_unknown_predicates() {
+ let mut evidence = evidence("button", Some("Save"));
+ evidence.role = LocatorField::Unknown;
+ evidence.description = LocatorField::Unknown;
+ let mut stats = Default::default();
+ let query = LocatorQuery {
+ identity: IdentityPredicate {
+ role: Some("button".into()),
+ name: Some("missing".into()),
+ ..IdentityPredicate::default()
+ },
+ ..LocatorQuery::default()
+ };
+ assert_eq!(
+ super::predicate::self_verdict(&query, &evidence, &mut stats),
+ super::match_verdict::MatchVerdict::NoMatch
+ );
+ evidence.name = LocatorField::Unknown;
+ evidence.value = LocatorField::Known("SAVE".into());
+ assert_eq!(
+ super::predicate::self_text_verdict(Some("save"), &evidence, false),
+ super::match_verdict::MatchVerdict::Match
+ );
+}
+
+#[test]
+fn ordinal_selection_uses_document_order() {
for (selection, expected) in [
(LocatorSelection::First, 0),
(LocatorSelection::Nth(1), 1),
@@ -231,8 +255,8 @@ fn ordinal_selection_uses_document_order_not_arena_order() {
#[test]
fn strict_classification_preserves_zero_one_many_and_incomplete() {
let zero = evaluate_locator_tree(
- tree(Vec::new(), Vec::new(), true),
- &LocatorQuery::default(),
+ names_tree(),
+ &named_query("missing", false),
&request(LocatorSelection::Strict),
)
.unwrap();
diff --git a/crates/core/src/live_locator/hydrate.rs b/crates/core/src/live_locator/hydrate.rs
index fb78dce96..885718485 100644
--- a/crates/core/src/live_locator/hydrate.rs
+++ b/crates/core/src/live_locator/hydrate.rs
@@ -239,7 +239,7 @@ fn changed_during_hydration() -> AdapterError {
}
fn query_incomplete(validation: &LocatorResolution) -> AdapterError {
- let deterministic = has_deterministic_limit(&validation.stats);
+ let deterministic = super::resolve::has_deterministic_limit(&validation.stats);
AdapterError::timeout("Selected locator query could not be revalidated")
.with_suggestion("Retry against a stable subtree or use a narrower locator")
.with_details(json!({
@@ -256,15 +256,6 @@ fn query_incomplete(validation: &LocatorResolution) -> AdapterError {
.with_disposition(crate::DeliverySemantics::not_delivered())
}
-fn has_deterministic_limit(stats: &super::LocatorStats) -> bool {
- let limits = &stats.traversal.limits;
- limits.node_hits > 0
- || limits.edge_hits > 0
- || limits.child_hits > 0
- || limits.text_hits > 0
- || limits.depth_hits > 0
-}
-
fn evidence_incomplete(
tree: &ObservedTree,
node: Option<&ObservedNode>,
diff --git a/crates/core/src/live_locator/identifier_evidence.rs b/crates/core/src/live_locator/identifier_evidence.rs
index 41970c18b..84262be38 100644
--- a/crates/core/src/live_locator/identifier_evidence.rs
+++ b/crates/core/src/live_locator/identifier_evidence.rs
@@ -26,23 +26,25 @@ impl IdentifierEvidence {
preferred: Option<usize>,
complete: bool,
) -> Self {
- let original = identifiers.into_iter().collect::<Vec<_>>();
- let preferred_value = preferred
- .and_then(|index| original.get(index))
- .filter(|identifier| !identifier.value.trim().is_empty())
- .cloned();
let mut normalized = Vec::new();
- for identifier in original {
- if !identifier.value.trim().is_empty() && !normalized.contains(&identifier) {
+ let mut normalized_preferred = None;
+ for (index, identifier) in identifiers.into_iter().enumerate() {
+ if identifier.value.trim().is_empty() {
+ continue;
+ }
+ let position = normalized
+ .iter()
+ .position(|candidate| candidate == &identifier);
+ if preferred == Some(index) {
+ normalized_preferred = Some(position.unwrap_or(normalized.len()));
+ }
+ if position.is_none() {
normalized.push(identifier);
}
}
- let preferred = preferred_value
- .as_ref()
- .and_then(|value| normalized.iter().position(|candidate| candidate == value));
Self {
identifiers: normalized,
- preferred,
+ preferred: normalized_preferred,
complete,
}
}
diff --git a/crates/core/src/live_locator/locator_field.rs b/crates/core/src/live_locator/locator_field.rs
index 09a1b6073..cee3259dd 100644
--- a/crates/core/src/live_locator/locator_field.rs
+++ b/crates/core/src/live_locator/locator_field.rs
@@ -16,6 +16,13 @@ impl<T> LocatorField<T> {
pub fn is_unknown(&self) -> bool {
matches!(self, Self::Unknown)
}
+
+ pub(crate) fn take_known(&mut self) -> Option<T> {
+ match std::mem::replace(self, Self::Unknown) {
+ Self::Known(value) => Some(value),
+ Self::Absent | Self::Unknown => None,
+ }
+ }
}
impl LocatorField<String> {
diff --git a/crates/core/src/live_locator/materialize.rs b/crates/core/src/live_locator/materialize.rs
index d39541bf6..f2f833bb7 100644
--- a/crates/core/src/live_locator/materialize.rs
+++ b/crates/core/src/live_locator/materialize.rs
@@ -15,10 +15,9 @@ pub(crate) fn materialize_refmap(
let nodes = &mut tree.nodes;
let mut refmap = RefMap::new();
let mut complete = true;
- let mut indices = selected
+ let indices = selected
.map(|indices| indices.to_vec())
.unwrap_or_else(|| (0..nodes.len()).collect());
- indices.sort_by_key(|index| nodes[*index].document_order);
for index in indices {
let node = &nodes[index];
let (addressable, known) = addressability(&node.evidence);
diff --git a/crates/core/src/live_locator/materialize_tests.rs b/crates/core/src/live_locator/materialize_tests.rs
index e9cc3b3c2..c77afc4f4 100644
--- a/crates/core/src/live_locator/materialize_tests.rs
+++ b/crates/core/src/live_locator/materialize_tests.rs
@@ -89,11 +89,11 @@ fn full_refmap_uses_same_arena_evidence_and_document_order() {
let resolution = evaluate_locator_tree(
tree(
vec![
+ node(0, root, vec![1, 2], &[]),
node(1, button, vec![], &[0]),
node(2, disclosure, vec![], &[1]),
- node(0, root, vec![0, 1], &[]),
],
- vec![2],
+ vec![0],
true,
),
&query,
@@ -208,8 +208,8 @@ fn scoped_refmap_extends_source_path_without_index_correlation() {
let root = evidence("group", Some("Scope"));
let button = evidence("button", Some("Save"));
let mut scoped = tree(
- vec![node(1, button, vec![], &[0]), node(0, root, vec![0], &[])],
- vec![1],
+ vec![node(0, root, vec![1], &[]), node(1, button, vec![], &[0])],
+ vec![0],
true,
);
scoped.source = ObservationSource::Element {
diff --git a/crates/core/src/live_locator/mod.rs b/crates/core/src/live_locator/mod.rs
index 79d7592e1..ecbc2d355 100644
--- a/crates/core/src/live_locator/mod.rs
+++ b/crates/core/src/live_locator/mod.rs
@@ -44,7 +44,6 @@ mod ref_evidence_requirements;
mod resolve;
mod select;
mod selection_completeness;
-mod tree_order;
mod validate;
pub use cardinality::{classify_query_result, require_unique};
diff --git a/crates/core/src/live_locator/observed_tree.rs b/crates/core/src/live_locator/observed_tree.rs
index 4604523f4..634996026 100644
--- a/crates/core/src/live_locator/observed_tree.rs
+++ b/crates/core/src/live_locator/observed_tree.rs
@@ -53,7 +53,7 @@ impl ObservedTree {
self.structurally_complete
}
- pub fn into_accessibility_tree(self) -> Result<AccessibilityNode, AdapterError> {
+ pub fn into_accessibility_tree(mut self) -> Result<AccessibilityNode, AdapterError> {
if !self.structurally_complete {
return Err(AdapterError::new(
ErrorCode::Timeout,
@@ -81,7 +81,7 @@ impl ObservedTree {
/// truncated container with `children_count`, so a partial tree stays
/// honest about its own boundaries.
pub fn into_accessibility_tree_partial(
- self,
+ mut self,
) -> Result<(AccessibilityNode, bool, usize), AdapterError> {
if self.roots.len() != 1 {
return Err(AdapterError::internal(
@@ -116,9 +116,17 @@ impl ObservedTree {
});
let mut child_indices = Vec::with_capacity(children.len());
let mut complete = completeness.subtree_complete;
+ let mut previous_native_index = None;
for (child_order, child) in children.into_iter().enumerate() {
+ let native_index = child.source_child_index.unwrap_or(child_order);
+ if previous_native_index.is_some_and(|previous| previous >= native_index) {
+ return Err(AdapterError::internal(
+ "locator tree children are not in native document order",
+ ));
+ }
+ previous_native_index = Some(native_index);
let mut child_path = path.clone();
- child_path.push(child.source_child_index.unwrap_or(child_order));
+ child_path.push(native_index);
let child_index = self.append(child, child_path)?;
complete &= self.nodes[child_index as usize]
.completeness
@@ -134,46 +142,56 @@ impl ObservedTree {
Ok(index)
}
- fn project(&self, index: usize) -> Result<AccessibilityNode, AdapterError> {
+ fn project(&mut self, index: usize) -> Result<AccessibilityNode, AdapterError> {
let node = self
.nodes
- .get(index)
+ .get_mut(index)
.ok_or_else(|| AdapterError::internal("observed child index is out of bounds"))?;
let role = node
.evidence
.role
- .known()
- .cloned()
+ .take_known()
.unwrap_or_else(|| "unknown".into());
- let children = node
- .children
- .iter()
- .map(|child| self.project(*child as usize))
- .collect::<Result<Vec<_>, _>>()?;
- Ok(AccessibilityNode {
- ref_id: node.ref_id.clone(),
+ let child_indices = std::mem::take(&mut node.children);
+ let mut projected = AccessibilityNode {
+ ref_id: node.ref_id.take(),
role,
identity: crate::NodeIdentity {
- name: node.evidence.name.meaningful_string(),
- value: node.evidence.value.meaningful_string(),
- description: node.evidence.description.meaningful_string(),
+ name: node
+ .evidence
+ .name
+ .take_known()
+ .filter(|value| !value.is_empty()),
+ value: node
+ .evidence
+ .value
+ .take_known()
+ .filter(|value| !value.is_empty()),
+ description: node
+ .evidence
+ .description
+ .take_known()
+ .filter(|value| !value.is_empty()),
native_id: node.evidence.identifiers.preferred_identifier().cloned(),
},
presentation: crate::NodePresentation {
hint: None,
- states: node.evidence.states.known().cloned().unwrap_or_default(),
+ states: node.evidence.states.take_known().unwrap_or_default(),
available_actions: node
.evidence
.ref_evidence
.available_actions
- .known()
- .cloned()
+ .take_known()
.unwrap_or_default(),
bounds: node.evidence.ref_evidence.bounds.known().copied(),
},
children_count: node.children_count,
subtree_truncated: !node.completeness.subtree_complete,
- children,
- })
+ children: Vec::with_capacity(child_indices.len()),
+ };
+ for child in child_indices {
+ projected.children.push(self.project(child as usize)?);
+ }
+ Ok(projected)
}
}
diff --git a/crates/core/src/live_locator/observed_tree_tests.rs b/crates/core/src/live_locator/observed_tree_tests.rs
index be11d762d..147e6c66b 100644
--- a/crates/core/src/live_locator/observed_tree_tests.rs
+++ b/crates/core/src/live_locator/observed_tree_tests.rs
@@ -95,9 +95,37 @@ fn incomplete_descendant_propagates_to_the_observation_root() {
assert!(tree.into_accessibility_tree().is_err());
}
+#[test]
+fn builder_rejects_nonincreasing_explicit_and_implicit_child_indices() {
+ for indices in [
+ [Some(1), Some(1)],
+ [Some(2), Some(1)],
+ [Some(2), None],
+ [None, Some(0)],
+ ] {
+ let children = indices
+ .into_iter()
+ .map(|index| {
+ let mut child = subtree("button", "Save", Vec::new());
+ child.source_child_index = index;
+ child
+ })
+ .collect();
+ let error = ObservedTree::from_roots(
+ vec![subtree("window", "Fixture", children)],
+ source(),
+ Default::default(),
+ true,
+ )
+ .unwrap_err();
+ assert_eq!(error.code, crate::ErrorCode::Internal);
+ assert!(error.message.contains("native document order"));
+ }
+}
+
#[test]
fn snapshot_projection_and_find_share_the_same_observation() {
- let tree = ObservedTree::from_roots(
+ let mut tree = ObservedTree::from_roots(
vec![subtree(
"window",
"Fixture",
@@ -108,7 +136,25 @@ fn snapshot_projection_and_find_share_the_same_observation() {
true,
)
.unwrap();
+ let button = &mut tree.nodes[1];
+ button.ref_id = Some("@e1".into());
+ button.evidence.value = super::LocatorField::Known("draft".into());
+ button.evidence.description = super::LocatorField::Known("Save draft".into());
+ button.evidence.states = super::LocatorField::Known(vec!["enabled".into()]);
+ button.evidence.ref_evidence.available_actions =
+ super::LocatorField::Known(vec!["Click".into()]);
let snapshot = tree.clone().into_accessibility_tree().unwrap();
+ let projected = &snapshot.children[0];
+ assert_eq!(projected.ref_id.as_deref(), Some("@e1"));
+ assert_eq!(projected.identity.value.as_deref(), Some("draft"));
+ assert_eq!(
+ projected.identity.description.as_deref(),
+ Some("Save draft")
+ );
+ assert_eq!(projected.presentation.states, ["enabled"]);
+ assert_eq!(projected.presentation.available_actions, ["Click"]);
+ assert_eq!(snapshot.identity.value, None);
+ assert_eq!(snapshot.identity.description, None);
let query = LocatorQuery {
identity: IdentityPredicate {
name: Some("save".into()),
diff --git a/crates/core/src/live_locator/ownership_tests.rs b/crates/core/src/live_locator/ownership_tests.rs
index e321b37a3..8f0375cc5 100644
--- a/crates/core/src/live_locator/ownership_tests.rs
+++ b/crates/core/src/live_locator/ownership_tests.rs
@@ -1,7 +1,7 @@
use super::{
LocatorMaterialization, LocatorResolveRequest, LocatorSelection, evaluate_locator_tree,
};
-use crate::{locator::LocatorQuery, refs::RefPath};
+use crate::locator::LocatorQuery;
use super::test_support::{evidence, node, tree};
@@ -42,22 +42,3 @@ fn count_returns_no_target_ownership() {
assert!(resolution.matches.is_empty());
}
-
-#[test]
-fn invalid_tree_fails_before_evaluation() {
- let mut invalid = tree(
- vec![node(0, evidence("button", Some("match")), vec![], &[])],
- vec![0],
- true,
- );
- invalid.nodes[0].path = RefPath::from_slice(&[1]);
- let error = evaluate_locator_tree(
- invalid,
- &LocatorQuery::default(),
- &request(LocatorSelection::Strict),
- )
- .err()
- .unwrap();
-
- assert_eq!(error.code, crate::ErrorCode::Internal);
-}
diff --git a/crates/core/src/live_locator/predicate.rs b/crates/core/src/live_locator/predicate.rs
index e2fa76334..c4f9bb5d7 100644
--- a/crates/core/src/live_locator/predicate.rs
+++ b/crates/core/src/live_locator/predicate.rs
@@ -50,6 +50,12 @@ pub(crate) fn self_verdict(
let (identifier, identifier_match) =
identifier_verdict(query.identity.native_id.as_deref(), evidence);
let verdict = role_verdict(query.identity.role.as_deref(), &evidence.role)
+ .and(identifier)
+ .and(states_verdict(query, evidence));
+ if verdict == MatchVerdict::NoMatch {
+ return verdict;
+ }
+ let verdict = verdict
.and(text_verdict(
query.identity.name.as_deref(),
&evidence.name,
@@ -60,13 +66,11 @@ pub(crate) fn self_verdict(
&evidence.description,
query.exact,
))
- .and(identifier)
.and(text_verdict(
query.identity.value.as_deref(),
&evidence.value,
query.exact,
- ))
- .and(states_verdict(query, evidence));
+ ));
if verdict == MatchVerdict::Match {
match identifier_match {
Some(IdentifierMatch::Preferred) => identifier_stats.preferred_matches += 1,
@@ -87,15 +91,10 @@ pub(crate) fn self_text_verdict(
};
let mut verdict = MatchVerdict::NoMatch;
for field in [&evidence.name, &evidence.description, &evidence.value] {
- verdict = verdict.or(match field {
- LocatorField::Known(actual) => bool_verdict(if exact {
- search_text::normalize(actual) == expected
- } else {
- search_text::contains(actual, expected)
- }),
- LocatorField::Absent => MatchVerdict::NoMatch,
- LocatorField::Unknown => MatchVerdict::Unknown,
- });
+ verdict = verdict.or(text_verdict(Some(expected), field, exact));
+ if verdict == MatchVerdict::Match {
+ return verdict;
+ }
}
verdict
}
@@ -104,7 +103,11 @@ fn role_verdict(expected: Option<&str>, actual: &LocatorField<String>) -> MatchV
let Some(expected) = expected else {
return MatchVerdict::Match;
};
- field_equality(actual, expected)
+ match actual {
+ LocatorField::Known(actual) => bool_verdict(actual == expected),
+ LocatorField::Absent => MatchVerdict::NoMatch,
+ LocatorField::Unknown => MatchVerdict::Unknown,
+ }
}
fn text_verdict(
@@ -179,14 +182,6 @@ fn states_verdict(query: &LocatorQuery, evidence: &LocatorEvidence) -> MatchVerd
}
}
-fn field_equality(actual: &LocatorField<String>, expected: &str) -> MatchVerdict {
- match actual {
- LocatorField::Known(actual) => bool_verdict(actual == expected),
- LocatorField::Absent => MatchVerdict::NoMatch,
- LocatorField::Unknown => MatchVerdict::Unknown,
- }
-}
-
fn bool_verdict(matched: bool) -> MatchVerdict {
if matched {
MatchVerdict::Match
diff --git a/crates/core/src/live_locator/resolve.rs b/crates/core/src/live_locator/resolve.rs
index 46c1666ae..d5de97f0e 100644
--- a/crates/core/src/live_locator/resolve.rs
+++ b/crates/core/src/live_locator/resolve.rs
@@ -102,7 +102,7 @@ fn unknown_incomplete_error(resolution: &LocatorResolution) -> AdapterError {
.with_disposition(crate::DeliverySemantics::not_delivered())
}
-fn has_deterministic_limit(stats: &LocatorStats) -> bool {
+pub(super) fn has_deterministic_limit(stats: &LocatorStats) -> bool {
let limits = &stats.traversal.limits;
limits.node_hits > 0
|| limits.edge_hits > 0
diff --git a/crates/core/src/live_locator/test_support.rs b/crates/core/src/live_locator/test_support.rs
index 13e2a3d7e..0755c284b 100644
--- a/crates/core/src/live_locator/test_support.rs
+++ b/crates/core/src/live_locator/test_support.rs
@@ -58,6 +58,10 @@ pub(crate) fn tree(
roots: Vec<u32>,
structurally_complete: bool,
) -> ObservedTree {
+ for (index, node) in nodes.iter().enumerate() {
+ assert_eq!(node.document_order as usize, index);
+ assert!(node.children.iter().all(|child| *child as usize > index));
+ }
ObservedTree {
nodes,
roots,
diff --git a/crates/core/src/live_locator/tree_order.rs b/crates/core/src/live_locator/tree_order.rs
deleted file mode 100644
index fe9f59510..000000000
--- a/crates/core/src/live_locator/tree_order.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-use super::ObservedTree;
-use crate::AdapterError;
-use std::collections::HashSet;
-
-pub(crate) fn validated_postorder(
- tree: &ObservedTree,
-) -> Result<(Vec<usize>, Vec<Option<usize>>), AdapterError> {
- let mut state = (
- vec![0_u8; tree.nodes.len()],
- vec![None; tree.nodes.len()],
- Vec::with_capacity(tree.nodes.len()),
- );
- for root in &tree.roots {
- visit(*root as usize, None, tree, &mut state)?;
- }
- if state.2.len() != tree.nodes.len() {
- return Err(AdapterError::internal(
- "locator tree contains unreachable nodes",
- ));
- }
- let mut document_orders = HashSet::new();
- for node in &tree.nodes {
- if !document_orders.insert(node.document_order) {
- return Err(AdapterError::internal(
- "locator tree has duplicate document_order values",
- ));
- }
- }
- Ok((state.2, state.1))
-}
-
-fn visit(
- index: usize,
- parent: Option<usize>,
- tree: &ObservedTree,
- state: &mut (Vec<u8>, Vec<Option<usize>>, Vec<usize>),
-) -> Result<(), AdapterError> {
- let mark = state
- .0
- .get(index)
- .copied()
- .ok_or_else(|| AdapterError::internal("locator tree child index is out of bounds"))?;
- if mark == 1 {
- return Err(AdapterError::internal("locator tree contains a cycle"));
- }
- if mark == 2 {
- return Err(AdapterError::internal(
- "locator tree node has multiple parents",
- ));
- }
- let node = tree
- .nodes
- .get(index)
- .ok_or_else(|| AdapterError::internal("locator tree node index is out of bounds"))?;
- let path_matches_edge = match parent {
- Some(parent) => tree.nodes.get(parent).is_some_and(|parent| {
- node.path.len() == parent.path.len() + 1
- && node.path.starts_with(parent.path.as_slice())
- }),
- None => node.path.is_empty(),
- };
- if !path_matches_edge {
- return Err(AdapterError::internal(
- "locator tree node path does not match its edges",
- ));
- }
- state.0[index] = 1;
- state.1[index] = parent;
- let mut previous_native_index = None;
- for child in node.children.iter().copied() {
- let native_index = tree
- .nodes
- .get(child as usize)
- .and_then(|child| child.path.last().copied())
- .ok_or_else(|| AdapterError::internal("locator tree child path is empty"))?;
- if previous_native_index.is_some_and(|previous| previous >= native_index) {
- return Err(AdapterError::internal(
- "locator tree children are not in native document order",
- ));
- }
- previous_native_index = Some(native_index);
- visit(child as usize, Some(index), tree, state)?;
- }
- state.0[index] = 2;
- state.2.push(index);
- Ok(())
-}
diff --git a/crates/core/src/locator.rs b/crates/core/src/locator.rs
index 1a587a53a..63993b310 100644
--- a/crates/core/src/locator.rs
+++ b/crates/core/src/locator.rs
@@ -130,11 +130,7 @@ fn text_field_matches(expected: Option<&str>, actual: Option<&str>, exact: bool)
let Some(actual) = actual else {
return false;
};
- if exact {
- search_text::normalize(actual) == expected
- } else {
- search_text::contains(actual, expected)
- }
+ text_matches(actual, expected, exact)
}
fn native_id_matches(expected: Option<&str>, actual: Option<&str>) -> bool {
@@ -155,22 +151,7 @@ fn has_text_matches(expected: Option<&str>, ctx: &NodeMatchContext<'_>, exact: b
|| ctx
.children
.iter()
- .any(|child| subtree_text_matches(child, expected, exact))
-}
-
-fn subtree_text_matches(node: &AccessibilityNode, expected: &str, exact: bool) -> bool {
- [
- node.identity.name.as_deref(),
- node.identity.description.as_deref(),
- node.identity.value.as_deref(),
- ]
- .into_iter()
- .flatten()
- .any(|text| text_matches(text, expected, exact))
- || node
- .children
- .iter()
- .any(|child| subtree_text_matches(child, expected, exact))
+ .any(|child| has_text_matches(Some(expected), &node_context(child), exact))
}
fn text_matches(actual: &str, expected: &str, exact: bool) -> bool {
diff --git a/crates/core/src/ref_action/presentation.rs b/crates/core/src/ref_action/presentation.rs
index ce3ab7acf..f1c690818 100644
--- a/crates/core/src/ref_action/presentation.rs
+++ b/crates/core/src/ref_action/presentation.rs
@@ -1,30 +1,16 @@
use super::{ActionabilityPreflight, ResolvedRefAction};
use crate::cursor_overlay::CursorPhase;
-use crate::{Action, CommandContext, DeliveryDisposition, DeliverySemantics, PlatformAdapter};
-
-const DISPATCH_RESERVE_MS: u64 = 100;
+use crate::{Action, CommandContext, PlatformAdapter};
pub(super) fn before_dispatch(
target: &ResolvedRefAction<'_>,
preflight: &ActionabilityPreflight,
lease: &crate::InteractionLease,
) {
- if lease.deadline().remaining_ms()
- <= crate::CURSOR_ARRIVAL_TIMEOUT_MS.saturating_add(DISPATCH_RESERVE_MS)
- {
- return;
- }
- let Some(destination) = preflight.presentation_point.clone() else {
+ let Some(destination) = destination(preflight) else {
return;
};
- crate::cursor_overlay::submit(
- target.adapter,
- target.context,
- destination,
- None,
- false,
- CursorPhase::Travel,
- );
+ crate::cursor_overlay::submit_travel(target.adapter, target.context, destination, lease);
}
pub(super) fn after_dispatch(
@@ -38,10 +24,10 @@ pub(super) fn after_dispatch(
Ok(result) => result.disposition(),
Err(error) => error.disposition,
};
- if !confirms_dispatch(disposition) {
+ if !crate::cursor_overlay::confirms_delivery(disposition) {
return;
}
- let Some(destination) = preflight.presentation_point.clone() else {
+ let Some(destination) = destination(preflight) else {
return;
};
crate::cursor_overlay::submit(
@@ -54,13 +40,11 @@ pub(super) fn after_dispatch(
);
}
-fn confirms_dispatch(disposition: DeliverySemantics) -> bool {
- matches!(
- disposition.delivery(),
- DeliveryDisposition::DeliveryUncertain
- | DeliveryDisposition::DeliveredUnverified
- | DeliveryDisposition::DeliveredVerified
- )
+fn destination(preflight: &ActionabilityPreflight) -> Option<crate::Point> {
+ match preflight.pointer_delivery {
+ crate::actionability::PointerDelivery::Physical => preflight.verified_point.clone(),
+ _ => preflight.presentation_point.clone(),
+ }
}
fn is_click(action: &Action) -> bool {
diff --git a/crates/core/src/ref_action_cursor_overlay_tests.rs b/crates/core/src/ref_action_cursor_overlay_tests.rs
index 3a10ba069..437234ce7 100644
--- a/crates/core/src/ref_action_cursor_overlay_tests.rs
+++ b/crates/core/src/ref_action_cursor_overlay_tests.rs
@@ -48,9 +48,15 @@ impl ActionOps for CursorAdapter {
fn execute_action(
&self,
_handle: &NativeHandle,
- _request: ActionRequest,
+ request: ActionRequest,
_lease: &crate::InteractionLease,
) -> Result<ActionResult, AdapterError> {
+ if request.policy.is_headed() {
+ assert_eq!(
+ request.verified_point(),
+ Some(&crate::Point { x: 11.0, y: 11.0 })
+ );
+ }
self.events.lock().unwrap().push(CursorEvent::Dispatch);
Ok(ActionResult::delivered_unverified("click"))
}
@@ -180,11 +186,17 @@ fn short_action_budget_skips_optional_travel_before_dispatch() {
}
#[test]
-fn disabled_and_headed_contexts_do_not_present() {
+fn disabled_overlay_does_not_present() {
let adapter = CursorAdapter::new(false);
execute_entry(&adapter, &entry(), ActionRequest::headless(Action::Click))
.expect("click succeeds");
+ assert!(adapter.presented.lock().unwrap().is_empty());
+}
+
+#[test]
+fn headed_click_retains_travel_and_effect_around_physical_dispatch() {
+ let adapter = CursorAdapter::new(false);
let headed = enabled_context().with_headed(true);
execute_entry_with_context(
&adapter,
@@ -194,7 +206,54 @@ fn disabled_and_headed_contexts_do_not_present() {
)
.expect("click succeeds");
+ assert_eq!(
+ *adapter.events.lock().unwrap(),
+ [
+ CursorEvent::Travel,
+ CursorEvent::Dispatch,
+ CursorEvent::Effect
+ ]
+ );
+ for control in adapter.presented.lock().unwrap().iter() {
+ assert_eq!(
+ control.instruction().unwrap().destination(),
+ &crate::Point { x: 11.0, y: 11.0 }
+ );
+ }
+}
+
+#[test]
+fn physical_effect_uses_verified_input_point_and_requires_delivery() {
+ let adapter = CursorAdapter::new(false);
+ let context = enabled_context().with_headed(true);
+ let preflight = ActionabilityPreflight {
+ verified_point: Some(crate::Point { x: 4.0, y: 5.0 }),
+ presentation_point: Some(crate::Point { x: 11.0, y: 11.0 }),
+ presentation_bounds: entry().geometry.bounds,
+ pointer_delivery: actionability::PointerDelivery::Physical,
+ };
+ presentation::after_dispatch(
+ &adapter,
+ &context,
+ &preflight,
+ &Action::Click,
+ &Err(AdapterError::stale_ref("blocked")
+ .with_disposition(crate::DeliverySemantics::NotDelivered)),
+ );
assert!(adapter.presented.lock().unwrap().is_empty());
+ presentation::after_dispatch(
+ &adapter,
+ &context,
+ &preflight,
+ &Action::Click,
+ &Ok(ActionResult::delivered_unverified("click")),
+ );
+ let presented = adapter.presented.lock().unwrap();
+ assert_eq!(presented.len(), 1);
+ assert_eq!(
+ presented[0].instruction().unwrap().destination(),
+ &crate::Point { x: 4.0, y: 5.0 }
+ );
}
#[test]
@@ -232,3 +291,30 @@ fn a_value_write_outlines_the_element_without_a_click_ripple() {
assert!(effect.target().is_some(), "but it must outline the element");
assert_eq!(effect.phase(), crate::CursorPhase::Effect);
}
+
+#[test]
+fn headed_and_headless_contexts_present_the_same_cursor() {
+ let adapter = CursorAdapter::new(false);
+ let headless = enabled_context();
+ let headed = headless.clone().with_headed(true);
+
+ execute_entry_with_context(
+ &adapter,
+ &entry(),
+ ActionRequest::headless(Action::Click),
+ &headless,
+ )
+ .expect("headless click succeeds");
+ execute_entry_with_context(
+ &adapter,
+ &entry(),
+ ActionRequest::headed(Action::Click),
+ &headed,
+ )
+ .expect("headed click succeeds");
+
+ let presented = adapter.presented.lock().unwrap();
+ assert_eq!(presented.len(), 4);
+ assert_eq!(presented[0].instruction(), presented[2].instruction());
+ assert_eq!(presented[1].instruction(), presented[3].instruction());
+}
diff --git a/crates/core/src/ref_action_wait_process_state_tests.rs b/crates/core/src/ref_action_wait_process_state_tests.rs
index 2fb838dbe..4ddaf8ec8 100644
--- a/crates/core/src/ref_action_wait_process_state_tests.rs
+++ b/crates/core/src/ref_action_wait_process_state_tests.rs
@@ -205,74 +205,35 @@ fn recycled_pid_never_upgrades_stale_ref_to_app_unresponsive() {
assert_eq!(adapter.inventory_calls.load(Ordering::SeqCst), 1);
}
-struct ExitedProcessAdapter;
-
-impl ObservationOps for ExitedProcessAdapter {
- fn resolve_element_strict(
- &self,
- _entry: &RefEntry,
- _deadline: crate::Deadline,
- ) -> Result<NativeHandle, AdapterError> {
- Err(AdapterError::stale_ref("@e1"))
- }
-}
-
-impl ActionOps for ExitedProcessAdapter {
- fn execute_action(
- &self,
- _handle: &NativeHandle,
- _request: ActionRequest,
- _lease: &crate::InteractionLease,
- ) -> Result<crate::action_result::ActionResult, AdapterError> {
- Ok(crate::action_result::ActionResult::delivered_unverified(
- "click",
- ))
- }
-}
-
-impl InputOps for ExitedProcessAdapter {}
-
-impl SystemOps for ExitedProcessAdapter {
- crate::adapter::guarded_interaction_lease!();
-
- fn process_state(
- &self,
- _process: crate::ProcessIdentity,
- _deadline: crate::Deadline,
- ) -> Result<crate::process_state::ProcessState, AdapterError> {
- Ok(crate::process_state::ProcessState::Exited { code: None })
- }
-}
-
#[test]
-fn terminal_stale_ref_against_exited_process_carries_process_state_detail() {
- let err = execute_with_auto_wait(
- RefActionWaitCtx {
- adapter: &ExitedProcessAdapter,
- entry: &entry(),
- ref_id: "@e1",
- context: &CommandContext::default(),
- },
- ActionRequest::headless(Action::Click),
- crate::ref_action::dispatch_resolved,
- )
- .unwrap_err();
+fn unresponsive_enrichment_preserves_delivery_evidence() {
+ use crate::DeliverySemantics;
- assert_eq!(
- err.code,
- ErrorCode::StaleRef,
- "an Exited (not Unresponsive) classification must not replace the original error code"
- );
- assert_eq!(
- err.details.as_ref().and_then(|d| d.get("process_state")),
- Some(&serde_json::json!("exited")),
- "STALE_REF against a dead pid must carry details.process_state = \"exited\""
- );
+ let adapter = UnresponsiveProcessAdapter {
+ probe_calls: AtomicU32::new(0),
+ inventory_calls: AtomicU32::new(0),
+ };
+ for disposition in [
+ DeliverySemantics::Unknown,
+ DeliverySemantics::NotDelivered,
+ DeliverySemantics::DeliveryUncertain,
+ DeliverySemantics::DeliveredUnverified,
+ DeliverySemantics::DeliveredVerified,
+ ] {
+ let error = enrich_with_process_state(
+ &adapter,
+ &entry(),
+ AdapterError::stale_ref("post-action read").with_disposition(disposition),
+ Deadline::standard().unwrap(),
+ );
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(error.disposition, disposition);
+ }
}
-struct CrashedProcessAdapter;
+struct TerminatedProcessAdapter(crate::process_state::ProcessState);
-impl ObservationOps for CrashedProcessAdapter {
+impl ObservationOps for TerminatedProcessAdapter {
fn resolve_element_strict(
&self,
_entry: &RefEntry,
@@ -282,22 +243,10 @@ impl ObservationOps for CrashedProcessAdapter {
}
}
-impl ActionOps for CrashedProcessAdapter {
- fn execute_action(
- &self,
- _handle: &NativeHandle,
- _request: ActionRequest,
- _lease: &crate::InteractionLease,
- ) -> Result<crate::action_result::ActionResult, AdapterError> {
- Ok(crate::action_result::ActionResult::delivered_unverified(
- "click",
- ))
- }
-}
-
-impl InputOps for CrashedProcessAdapter {}
+impl ActionOps for TerminatedProcessAdapter {}
+impl InputOps for TerminatedProcessAdapter {}
-impl SystemOps for CrashedProcessAdapter {
+impl SystemOps for TerminatedProcessAdapter {
crate::adapter::guarded_interaction_lease!();
fn process_state(
@@ -305,32 +254,38 @@ impl SystemOps for CrashedProcessAdapter {
_process: crate::ProcessIdentity,
_deadline: crate::Deadline,
) -> Result<crate::process_state::ProcessState, AdapterError> {
- Ok(crate::process_state::ProcessState::Crashed { signal_or_code: 11 })
+ Ok(self.0)
}
}
#[test]
-fn terminal_stale_ref_against_crashed_process_carries_process_state_detail() {
- let err = execute_with_auto_wait(
- RefActionWaitCtx {
- adapter: &CrashedProcessAdapter,
- entry: &entry(),
- ref_id: "@e1",
- context: &CommandContext::default(),
- },
- ActionRequest::headless(Action::Click),
- crate::ref_action::dispatch_resolved,
- )
- .unwrap_err();
-
- assert_eq!(
- err.code,
- ErrorCode::StaleRef,
- "a Crashed (not Unresponsive) classification must not replace the original error code"
- );
- assert_eq!(
- err.details.as_ref().and_then(|d| d.get("process_state")),
- Some(&serde_json::json!("crashed")),
- "STALE_REF against a crashed pid must carry details.process_state = \"crashed\""
- );
+fn terminal_stale_ref_preserves_exited_and_crashed_process_details() {
+ for (state, label) in [
+ (
+ crate::process_state::ProcessState::Exited { code: None },
+ "exited",
+ ),
+ (
+ crate::process_state::ProcessState::Crashed { signal_or_code: 11 },
+ "crashed",
+ ),
+ ] {
+ let err = execute_with_auto_wait(
+ RefActionWaitCtx {
+ adapter: &TerminatedProcessAdapter(state),
+ entry: &entry(),
+ ref_id: "@e1",
+ context: &CommandContext::default(),
+ },
+ ActionRequest::headless(Action::Click),
+ crate::ref_action::dispatch_resolved,
+ )
+ .unwrap_err();
+
+ assert_eq!(err.code, ErrorCode::StaleRef);
+ assert_eq!(
+ err.details.as_ref().and_then(|d| d.get("process_state")),
+ Some(&serde_json::json!(label))
+ );
+ }
}
diff --git a/crates/core/src/ref_action_wait_support.rs b/crates/core/src/ref_action_wait_support.rs
index 4deeb5f85..0b36940ae 100644
--- a/crates/core/src/ref_action_wait_support.rs
+++ b/crates/core/src/ref_action_wait_support.rs
@@ -43,7 +43,9 @@ pub(crate) fn enrich_with_process_state(
};
details.insert("kind".into(), json!("app_unresponsive"));
details.insert("retryable".into(), json!(false));
- return unresponsive.with_details(details.into());
+ return unresponsive
+ .with_details(details.into())
+ .with_disposition(err.disposition);
}
attach_process_state_detail(err, state)
}
diff --git a/crates/core/src/search_text.rs b/crates/core/src/search_text.rs
index 48d74f0c7..2909c0569 100644
--- a/crates/core/src/search_text.rs
+++ b/crates/core/src/search_text.rs
@@ -13,7 +13,11 @@ pub(crate) fn normalize(value: &str) -> String {
normalized.push(' ');
pending_space = false;
}
- normalized.extend(character.to_lowercase());
+ if character.is_ascii() {
+ normalized.push(character.to_ascii_lowercase());
+ } else {
+ normalized.extend(character.to_lowercase());
+ }
}
normalized
}
diff --git a/crates/core/src/search_text_tests.rs b/crates/core/src/search_text_tests.rs
index 05186aed9..840b1719e 100644
--- a/crates/core/src/search_text_tests.rs
+++ b/crates/core/src/search_text_tests.rs
@@ -28,6 +28,10 @@ fn contains_uses_ascii_fast_path_case_insensitively() {
#[test]
fn contains_handles_non_ascii_text() {
assert!(contains("Résumé", &normalize("rés")));
+ assert_eq!(
+ normalize(" SAVE\tAs\n \u{200e}İ\u{a0}Σ "),
+ "save as i\u{307} σ"
+ );
}
#[test]
diff --git a/crates/core/src/session/cursor_profile_tests.rs b/crates/core/src/session/cursor_profile_tests.rs
new file mode 100644
index 000000000..02df49f58
--- /dev/null
+++ b/crates/core/src/session/cursor_profile_tests.rs
@@ -0,0 +1,111 @@
+use super::*;
+use crate::{context::CommandContext, refs_test_support::HomeGuard};
+
+#[test]
+fn named_profiles_inherit_session_mode_and_share_snapshots() {
+ let _guard = HomeGuard::new();
+ let session = start_session(Default::default()).unwrap();
+ let master = CursorOverlayConfig::enabled(None, 6)
+ .unwrap()
+ .with_multi_agent(true);
+ set_cursor_overlay(&session.id, master.clone()).unwrap();
+ let profile = CursorOverlayConfig::enabled(Some("Agent A".into()), 6).unwrap();
+ save_cursor_overlay_profile(&session.id, "a", profile.clone()).unwrap();
+ let base = CommandContext::new(Some(session.id.clone()), None, false).unwrap();
+ let a = base.clone().with_agent_id(Some("a".into())).unwrap();
+ let b = base.with_agent_id(Some("b".into())).unwrap();
+ assert_eq!(a.session_id(), b.session_id());
+ assert_eq!(a.cursor_overlay(), &profile.with_multi_agent(true));
+ assert_eq!(b.cursor_overlay(), &master);
+ assert_eq!(a.for_batch_item(None).unwrap().agent_id(), Some("a"));
+ let other = start_session(Default::default()).unwrap();
+ set_cursor_overlay(&other.id, master.clone()).unwrap();
+ let other_profile = CursorOverlayConfig::enabled(Some("Other task".into()), 6).unwrap();
+ save_cursor_overlay_profile(&other.id, "a", other_profile.clone()).unwrap();
+ let switched = a.for_batch_item(Some(other.id.clone())).unwrap();
+ assert_eq!(switched.agent_id(), Some("a"));
+ assert_eq!(switched.session_id(), Some(other.id.as_str()));
+ assert_eq!(
+ switched.cursor_overlay(),
+ &other_profile.with_multi_agent(true)
+ );
+ assert_eq!(
+ read_manifest(&session.id).unwrap().unwrap().cursor_overlay,
+ master
+ );
+ set_cursor_overlay(&session.id, CursorOverlayConfig::default()).unwrap();
+ assert!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("a"))
+ .unwrap()
+ .is_disabled()
+ );
+ assert!(save_cursor_overlay_profile(&session.id, "a", master).is_err());
+}
+
+#[test]
+fn profiles_reject_bad_identity_but_fall_back_on_corrupt_files() {
+ let _guard = HomeGuard::new();
+ let session = start_session(Default::default()).unwrap();
+ let master = CursorOverlayConfig::enabled(None, 6).unwrap();
+ set_cursor_overlay(&session.id, master.clone()).unwrap();
+ for id in ["", "../a", "a/b", "a.b", &"a".repeat(65)] {
+ assert!(cursor_overlay_for_session_agent(Some(&session.id), Some(id)).is_err());
+ }
+ let path = agent_profile_path(&session.id, "a").unwrap();
+ write_private_file(&path, b"invalid json").unwrap();
+ assert_eq!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("a")).unwrap(),
+ master
+ );
+ end_session(&session.id).unwrap();
+ assert!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("a"))
+ .unwrap()
+ .is_disabled()
+ );
+}
+
+#[test]
+fn corrupt_profile_bytes_fall_back_to_session_config() {
+ let _guard = HomeGuard::new();
+ let session = start_session(Default::default()).unwrap();
+ let master = CursorOverlayConfig::enabled(None, 6).unwrap();
+ set_cursor_overlay(&session.id, master.clone()).unwrap();
+ let path = agent_profile_path(&session.id, "a").unwrap();
+ write_private_file(&path, b"not json at all").unwrap();
+ assert_eq!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("a")).unwrap(),
+ master
+ );
+ write_private_file(&path, br#"{"enabled":true,"max_words":0}"#).unwrap();
+ assert_eq!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("a")).unwrap(),
+ master
+ );
+}
+
+#[test]
+fn missing_profile_falls_back_to_session_config() {
+ let _guard = HomeGuard::new();
+ let session = start_session(Default::default()).unwrap();
+ let master = CursorOverlayConfig::enabled(None, 6).unwrap();
+ set_cursor_overlay(&session.id, master.clone()).unwrap();
+ assert_eq!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("ghost")).unwrap(),
+ master
+ );
+}
+
+#[test]
+fn valid_profile_is_used_over_session_config() {
+ let _guard = HomeGuard::new();
+ let session = start_session(Default::default()).unwrap();
+ let master = CursorOverlayConfig::enabled(None, 6).unwrap();
+ set_cursor_overlay(&session.id, master.clone()).unwrap();
+ let profile = CursorOverlayConfig::enabled(Some("Agent A".into()), 6).unwrap();
+ save_cursor_overlay_profile(&session.id, "a", profile.clone()).unwrap();
+ assert_eq!(
+ cursor_overlay_for_session_agent(Some(&session.id), Some("a")).unwrap(),
+ profile.with_multi_agent(false)
+ );
+}
diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs
index 60b24acaf..36416316f 100644
--- a/crates/core/src/session/mod.rs
+++ b/crates/core/src/session/mod.rs
@@ -141,6 +141,81 @@ pub fn cursor_overlay_for_session(
}
}
+pub fn cursor_overlay_for_session_agent(
+ session_id: Option<&str>,
+ agent_id: Option<&str>,
+) -> Result<CursorOverlayConfig, AppError> {
+ let Some(session_id) = session_id else {
+ return Ok(CursorOverlayConfig::default());
+ };
+ let config = cursor_overlay_for_session(Some(session_id))?;
+ if config.is_disabled() {
+ return Ok(config);
+ }
+ let Some(agent_id) = agent_id else {
+ return Ok(config);
+ };
+ let path = agent_profile_path(session_id, agent_id)?;
+ match crate::private_file::read_private_bounded(&path, MAX_SESSION_MANIFEST_BYTES) {
+ Ok(bytes) => {
+ let parsed: Result<CursorOverlayConfig, AppError> = serde_json::from_slice::<
+ CursorOverlayConfig,
+ >(&bytes)
+ .map_err(|error| AppError::invalid_input(format!("Invalid cursor profile: {error}")))
+ .and_then(|profile| profile.validated().map_err(Into::into));
+ match parsed.map(|profile| profile.with_multi_agent(config.is_multi_agent())) {
+ Ok(profile) => Ok(profile),
+ Err(error) => {
+ tracing::warn!(
+ code = error.code(),
+ session_id = session_id,
+ agent_id = agent_id,
+ "ignoring invalid cursor profile"
+ );
+ Ok(config)
+ }
+ }
+ }
+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(config),
+ Err(error) => Err(error.into()),
+ }
+}
+
+pub fn save_cursor_overlay_profile(
+ session_id: &str,
+ agent_id: &str,
+ config: CursorOverlayConfig,
+) -> Result<(), AppError> {
+ validate_agent_id(agent_id)?;
+ let manifest = read_manifest(session_id)?
+ .ok_or_else(|| AppError::invalid_input("Session has no manifest"))?;
+ if manifest.ended_at.is_some() || manifest.cursor_overlay.is_disabled() {
+ return Err(AppError::invalid_input(
+ "Cursor overlay is not enabled for this session",
+ ));
+ }
+ let json = serde_json::to_vec(&config.validated()?.with_multi_agent(false))?;
+ write_private_file(&agent_profile_path(session_id, agent_id)?, &json)
+}
+
+fn agent_profile_path(session_id: &str, agent_id: &str) -> Result<PathBuf, AppError> {
+ validate_session_id(session_id)?;
+ validate_agent_id(agent_id)?;
+ Ok(session_dir(session_id)?
+ .join("cursor-overlays")
+ .join(format!("{agent_id}.json")))
+}
+
+pub fn validate_agent_id(id: &str) -> Result<(), AppError> {
+ if validate_session_id(id).is_ok() {
+ return Ok(());
+ }
+ Err(AppError::invalid_input_with_suggestion(
+ "Agent id must be 1-64 chars using letters, numbers, '-' or '_'",
+ "Use a stable filesystem-safe id such as agent-a.",
+ ))
+}
+
pub fn trace_enabled_for_session(session_id: &str) -> Result<bool, AppError> {
Ok(read_manifest(session_id)?.is_some_and(|manifest| manifest.trace_enabled()))
}
@@ -302,3 +377,6 @@ mod tests;
#[cfg(test)]
#[path = "session_gc_tests.rs"]
mod gc_tests;
+
+#[cfg(test)]
+mod cursor_profile_tests;
diff --git a/crates/macos/src/actions/chain_defs.rs b/crates/macos/src/actions/chain_defs.rs
index 4e1a7b2fb..3256ac03d 100644
--- a/crates/macos/src/actions/chain_defs.rs
+++ b/crates/macos/src/actions/chain_defs.rs
@@ -9,7 +9,7 @@ mod imp {
use crate::tree::AXElement;
use agent_desktop_core::{ActionStep, Deadline, MouseButton, StepMechanism};
- pub(crate) static CLICK_CHAIN: ChainDef = ChainDef {
+ static CLICK_CHAIN: ChainDef = ChainDef {
steps: &[
ChainStep::CGClick {
button: MouseButton::Left,
@@ -31,6 +31,20 @@ mod imp {
continue_after_unverified_delivery: false,
};
+ static MENUBAR_CLICK_CHAIN: ChainDef = ChainDef {
+ steps: &[ChainStep::Action("AXPress")],
+ suggestion: "Refresh the menu-bar snapshot and target an item that supports AXPress.",
+ continue_after_unverified_delivery: false,
+ };
+
+ pub(crate) fn click_chain(native_role: Option<&str>) -> &'static ChainDef {
+ if native_role == Some("AXMenuBarItem") {
+ &MENUBAR_CLICK_CHAIN
+ } else {
+ &CLICK_CHAIN
+ }
+ }
+
/// Continues past an unverified delivery because an `AXShowMenu` that
/// reports success without opening a menu must not consume the fallbacks
/// behind it. Each step re-checks for an open menu first, so continuing
@@ -199,6 +213,6 @@ mod imp {}
#[cfg(target_os = "macos")]
pub(crate) use imp::{
- CLEAR_CHAIN, CLICK_CHAIN, COLLAPSE_CHAIN, EXPAND_CHAIN, FOCUS_CHAIN, RIGHT_CLICK_CHAIN,
- SCROLL_TO_CHAIN, SEMANTIC_CLICK_CHAIN, SET_VALUE_CHAIN, double_click, triple_click,
+ CLEAR_CHAIN, COLLAPSE_CHAIN, EXPAND_CHAIN, FOCUS_CHAIN, RIGHT_CLICK_CHAIN, SCROLL_TO_CHAIN,
+ SEMANTIC_CLICK_CHAIN, SET_VALUE_CHAIN, click_chain, double_click, triple_click,
};
diff --git a/crates/macos/src/actions/chain_tests.rs b/crates/macos/src/actions/chain_tests.rs
index 705f66d3e..3326ee0bd 100644
--- a/crates/macos/src/actions/chain_tests.rs
+++ b/crates/macos/src/actions/chain_tests.rs
@@ -35,7 +35,7 @@ fn right_click_prefers_physical_input_before_semantic_fallbacks() {
#[test]
fn click_and_clear_prefer_physical_delivery_when_policy_allows_it() {
assert!(matches!(
- crate::actions::chain_defs::CLICK_CHAIN.steps.first(),
+ crate::actions::chain_defs::click_chain(None).steps.first(),
Some(ChainStep::CGClick {
button: MouseButton::Left,
count: 1
@@ -241,3 +241,63 @@ fn exhaustion_without_any_delivery_reports_not_delivered() {
agent_desktop_core::DeliverySemantics::not_delivered()
);
}
+
+#[test]
+fn headed_menubar_click_uses_only_semantic_press_and_keeps_other_clicks_physical() {
+ let menu = crate::actions::chain_defs::click_chain(Some("AXMenuBarItem"));
+ assert!(matches!(menu.steps, [ChainStep::Action("AXPress")]));
+ assert!(!menu.continue_after_unverified_delivery);
+ let mut steps = Vec::new();
+ assert!(record_step_outcome(
+ &mut steps,
+ &menu.steps[0],
+ DeliveryOutcome::DeliveredUnverified,
+ false
+ ));
+ assert_eq!(steps[0].mechanism(), Some(StepMechanism::SemanticApi));
+ assert_eq!(steps[0].verified(), Some(false));
+ let mut unsupported = Vec::new();
+ assert!(!record_step_outcome(
+ &mut unsupported,
+ &menu.steps[0],
+ DeliveryOutcome::NotDelivered,
+ false,
+ ));
+ assert_eq!(
+ exhaustion_disposition(&unsupported),
+ agent_desktop_core::DeliverySemantics::not_delivered()
+ );
+ for role in [
+ None,
+ Some("AXButton"),
+ Some("AXMenuItem"),
+ Some("AXMenuBar"),
+ ] {
+ assert!(matches!(
+ crate::actions::chain_defs::click_chain(role).steps.first(),
+ Some(ChainStep::CGClick { .. })
+ ));
+ }
+}
+
+#[test]
+fn click_role_probe_failure_falls_back_to_default_chain() {
+ let fallback = crate::actions::chain_defs::click_chain(None);
+ assert!(matches!(
+ fallback.steps.first(),
+ Some(ChainStep::CGClick {
+ button: MouseButton::Left,
+ count: 1
+ })
+ ));
+ for unknown in [Some("AXUnknown"), Some(""), Some("AXButton")] {
+ assert!(std::ptr::eq(
+ fallback,
+ crate::actions::chain_defs::click_chain(unknown)
+ ));
+ }
+ assert!(!std::ptr::eq(
+ fallback,
+ crate::actions::chain_defs::click_chain(Some("AXMenuBarItem"))
+ ));
+}
diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rs
index 58d835b5a..9bc938650 100644
--- a/crates/macos/src/actions/dispatch.rs
+++ b/crates/macos/src/actions/dispatch.rs
@@ -30,9 +30,14 @@ mod imp {
tracing::debug!("action: perform {label}");
match action {
Action::Click => {
+ let role = if request.policy.is_headed() {
+ probe_click_role(el, deadline)?
+ } else {
+ None
+ };
steps.extend(run_chain(
el,
- &chain_defs::CLICK_CHAIN,
+ chain_defs::click_chain(role.as_deref()),
None,
request,
deadline,
@@ -221,6 +226,17 @@ mod imp {
)
}
+ fn probe_click_role(
+ element: &AXElement,
+ deadline: Deadline,
+ ) -> Result<Option<String>, AdapterError> {
+ let operation_deadline = crate::tree::locator_deadline::from_operation(deadline)?;
+ match crate::tree::resolve_ax_read::read_string(element, "AXRole", operation_deadline) {
+ Err(error) if error.code == ErrorCode::AppUnresponsive => Ok(None),
+ result => result,
+ }
+ }
+
fn after_delivery(error: AdapterError) -> AdapterError {
error.with_disposition(agent_desktop_core::DeliverySemantics::delivered_unverified())
}
diff --git a/crates/macos/src/input/clipboard_file_urls.rs b/crates/macos/src/input/clipboard_file_urls.rs
index c9f81b015..5f03dcb39 100644
--- a/crates/macos/src/input/clipboard_file_urls.rs
+++ b/crates/macos/src/input/clipboard_file_urls.rs
@@ -148,7 +148,10 @@ unsafe fn read_file_urls_inner(pb: Id, deadline: Deadline) -> Result<Vec<String>
}
pub(crate) fn file_url_to_path(url_string: &str) -> Option<String> {
- if !url_string.starts_with("file:///") || url_string.contains('\0') {
+ if !url_string.starts_with("file:///")
+ || url_string.contains('\0')
+ || url_string.contains("%00")
+ {
return None;
}
let value = CFString::new(url_string);
diff --git a/crates/macos/src/input/mouse_drag.rs b/crates/macos/src/input/mouse_drag.rs
index 8c7d29305..72c158a15 100644
--- a/crates/macos/src/input/mouse_drag.rs
+++ b/crates/macos/src/input/mouse_drag.rs
@@ -1,4 +1,4 @@
-use agent_desktop_core::{AdapterError, Deadline, DragParams, ErrorCode};
+use agent_desktop_core::{AdapterError, CursorMotion, Deadline, DragParams, ErrorCode};
use core_graphics::event::{CGEvent, CGEventFlags, CGEventTapLocation, CGEventType, CGMouseButton};
use core_graphics::event_source::CGEventSource;
use core_graphics::geometry::CGPoint;
@@ -30,6 +30,7 @@ fn drag_sequence(params: DragParams, deadline: Deadline) -> Result<(), AdapterEr
let from = CGPoint::new(params.from.x, params.from.y);
let to = CGPoint::new(params.to.x, params.to.y);
let duration_ms = params.duration_ms.unwrap_or(DEFAULT_DURATION_MS);
+ let motion = CursorMotion::new(params.from.clone(), params.to.clone());
let steps = duration_ms.div_ceil(DWELL_TICK_MS).clamp(1, MAX_STEPS);
let step_delay = Duration::from_secs_f64(duration_ms as f64 / steps as f64 / 1_000.0);
let pre_delivery = crate::actions::DeliveryTracker::default();
@@ -59,11 +60,7 @@ fn drag_sequence(params: DragParams, deadline: Deadline) -> Result<(), AdapterEr
)?;
for index in 1..=steps {
- let progress = index as f64 / steps as f64;
- let point = CGPoint::new(
- params.from.x + (params.to.x - params.from.x) * progress,
- params.from.y + (params.to.y - params.from.y) * progress,
- );
+ let point = drag_point(&motion, index, steps);
crate::input::mouse::post_event_with_source(
&source,
(
@@ -90,6 +87,11 @@ fn drag_sequence(params: DragParams, deadline: Deadline) -> Result<(), AdapterEr
outcome.map_err(|error| release.enrich_error(error))
}
+fn drag_point(motion: &CursorMotion, index: u64, steps: u64) -> CGPoint {
+ let point = motion.sample(motion.duration_ms() * index / steps);
+ CGPoint::new(point.x, point.y)
+}
+
struct DragReleaseGuard {
abort_drag: CGEvent,
abort_up: CGEvent,
@@ -248,6 +250,17 @@ mod tests {
use super::*;
use agent_desktop_core::Point;
+ #[test]
+ fn drag_reuses_cursor_motion_and_lands_exactly() {
+ let motion = CursorMotion::new(Point { x: 10.0, y: 20.0 }, Point { x: 400.0, y: 200.0 });
+ let midpoint = motion.sample(motion.duration_ms() / 2);
+ let halfway = drag_point(&motion, 5, 10);
+ let end = drag_point(&motion, 10, 10);
+ assert_eq!((halfway.x, halfway.y), (midpoint.x, midpoint.y));
+ assert_eq!((end.x, end.y), (400.0, 200.0));
+ assert_ne!((halfway.x, halfway.y), (205.0, 110.0));
+ }
+
#[test]
fn drag_limits_reject_unbounded_work() {
let base = DragParams {
diff --git a/crates/macos/src/system/cursor_overlay/bridge.rs b/crates/macos/src/system/cursor_overlay/bridge.rs
index 48cfb4cdc..ae5df09e4 100644
--- a/crates/macos/src/system/cursor_overlay/bridge.rs
+++ b/crates/macos/src/system/cursor_overlay/bridge.rs
@@ -41,6 +41,9 @@ unsafe extern "C" {
frame_count: usize,
config: *const NativeRenderConfig,
) -> bool;
+ fn agent_desktop_cursor_overlay_drag_begin(x: f64, y: f64, trail: bool);
+ fn agent_desktop_cursor_overlay_drag_end(x: f64, y: f64, completed: bool);
+ fn agent_desktop_cursor_overlay_drag_active() -> bool;
fn agent_desktop_cursor_overlay_style(style: *const NativeCursorStyle);
fn agent_desktop_cursor_overlay_idle();
fn agent_desktop_cursor_overlay_hide();
@@ -49,6 +52,18 @@ unsafe extern "C" {
fn agent_desktop_cursor_overlay_stop();
}
+pub(super) fn begin_drag(from: &Point, trail: bool) {
+ unsafe { agent_desktop_cursor_overlay_drag_begin(from.x, from.y, trail) }
+}
+
+pub(super) fn end_drag(to: &Point, completed: bool) {
+ unsafe { agent_desktop_cursor_overlay_drag_end(to.x, to.y, completed) }
+}
+
+pub(super) fn drag_active() -> bool {
+ unsafe { agent_desktop_cursor_overlay_drag_active() }
+}
+
pub(super) fn initial_point() -> Result<Point, AdapterError> {
let mut output = [0.0; 2];
if !unsafe { agent_desktop_cursor_overlay_initial_point(output.as_mut_ptr()) } {
diff --git a/crates/macos/src/system/cursor_overlay/child.rs b/crates/macos/src/system/cursor_overlay/child.rs
index 1a8612d83..fb1c52e52 100644
--- a/crates/macos/src/system/cursor_overlay/child.rs
+++ b/crates/macos/src/system/cursor_overlay/child.rs
@@ -4,7 +4,7 @@ use agent_desktop_core::{
};
use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
-use std::os::unix::net::UnixListener;
+use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Duration;
@@ -35,6 +35,9 @@ pub(crate) fn entry_from_env() -> Option<Result<(), AdapterError>> {
fn run() -> Result<(), AdapterError> {
let initial = read_control(std::io::stdin())?;
+ if !session_active(initial.session_id(), initial.agent_id()) {
+ return Ok(());
+ }
let socket = socket_path(&initial)?;
prepare_socket(&socket)?;
let mut state = OverlayState::default();
@@ -54,13 +57,27 @@ fn run() -> Result<(), AdapterError> {
.with_platform_detail(error.to_string())
})?;
let mut quiet_since = std::time::Instant::now();
+ let mut checked_session = quiet_since;
loop {
+ if checked_session.elapsed() >= Duration::from_secs(1) {
+ if !session_active(initial.session_id(), initial.agent_id()) {
+ return cleanup(socket);
+ }
+ checked_session = std::time::Instant::now();
+ }
match listener.accept() {
Ok((mut stream, _)) => {
+ if prepare_stream(&stream).is_err() {
+ continue;
+ }
let Ok(control) = read_control(&mut stream) else {
continue;
};
- if control.session_id() != initial.session_id() {
+ if control.session_id() != initial.session_id()
+ || (control.agent_id() != initial.agent_id()
+ && !(control.agent_id().is_none()
+ && (control.is_transient() || control.is_disable())))
+ {
continue;
}
if control.is_disable() {
@@ -85,6 +102,7 @@ fn run() -> Result<(), AdapterError> {
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
bridge::idle();
if !state.resting
+ && !bridge::drag_active()
&& quiet_since.elapsed().as_millis() >= u128::from(CURSOR_IDLE_REST_MS)
{
bridge::rest();
@@ -103,6 +121,12 @@ fn run() -> Result<(), AdapterError> {
}
}
+fn prepare_stream(stream: &UnixStream) -> std::io::Result<()> {
+ stream.set_nonblocking(false)?;
+ stream.set_read_timeout(Some(Duration::from_secs(1)))?;
+ stream.set_write_timeout(Some(Duration::from_secs(1)))
+}
+
fn handle(control: &CursorOverlayControl, state: &mut OverlayState) -> Result<bool, AdapterError> {
control.validate()?;
if control.is_disable() {
@@ -129,7 +153,16 @@ fn handle(control: &CursorOverlayControl, state: &mut OverlayState) -> Result<bo
&owned
};
render(instruction, state)?;
- state.at = Some(instruction.destination().clone());
+ state.at = Some(
+ if instruction.phase() == agent_desktop_core::CursorPhase::Drag {
+ instruction
+ .drag_from()
+ .unwrap_or(instruction.destination())
+ .clone()
+ } else {
+ instruction.destination().clone()
+ },
+ );
Ok(true)
}
@@ -137,6 +170,23 @@ fn render(
instruction: &CursorOverlayInstruction,
state: &OverlayState,
) -> Result<(), AdapterError> {
+ if instruction.phase() == agent_desktop_core::CursorPhase::Drag {
+ let from = instruction.drag_from().unwrap_or(instruction.destination());
+ let (screen, fps, reduce_motion) = bridge::screen_at(from)?;
+ let bubble = place_label(from, BUBBLE_SIZE, &screen);
+ bridge::run(
+ &[CursorPose::still(from.clone())],
+ fps,
+ instruction,
+ reduce_motion,
+ &bubble,
+ )?;
+ bridge::begin_drag(from, state.style.ripple() && !reduce_motion);
+ return Ok(());
+ }
+ if instruction.phase() == agent_desktop_core::CursorPhase::Effect {
+ bridge::end_drag(instruction.destination(), instruction.drag_from().is_some());
+ }
let (screen, fps, reduce_motion) = bridge::screen_at(instruction.destination())?;
let bubble = place_label(instruction.destination(), BUBBLE_SIZE, &screen);
let shown = if state.style.highlight() {
@@ -209,7 +259,7 @@ fn read_control(reader: impl Read) -> Result<CursorOverlayControl, AdapterError>
}
fn socket_path(control: &CursorOverlayControl) -> Result<PathBuf, AdapterError> {
- let expected = super::endpoint::path(control.session_id())?;
+ let expected = super::endpoint::path(control.session_id(), control.agent_id())?;
let supplied = std::env::var_os(SOCKET_ENV)
.map(PathBuf::from)
.ok_or_else(|| AdapterError::internal("Cursor overlay child socket is missing"))?;
@@ -222,6 +272,17 @@ fn socket_path(control: &CursorOverlayControl) -> Result<PathBuf, AdapterError>
Ok(expected)
}
+pub(super) fn session_active(session_id: &str, agent_id: Option<&str>) -> bool {
+ agent_desktop_core::session::read_manifest(session_id)
+ .ok()
+ .flatten()
+ .is_some_and(|manifest| {
+ manifest.ended_at.is_none()
+ && manifest.cursor_overlay.is_enabled()
+ && !(manifest.cursor_overlay.is_multi_agent() && agent_id.is_none())
+ })
+}
+
fn prepare_socket(path: &Path) -> Result<(), AdapterError> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
@@ -246,101 +307,5 @@ fn cleanup(path: PathBuf) -> Result<(), AdapterError> {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- fn state(at: Option<Point>) -> OverlayState {
- OverlayState {
- at,
- ..OverlayState::default()
- }
- }
-
- fn screen() -> agent_desktop_core::Rect {
- agent_desktop_core::Rect {
- x: 0.0,
- y: 0.0,
- width: 1920.0,
- height: 1080.0,
- }
- }
-
- fn instruction(destination: Point, click: bool) -> CursorOverlayInstruction {
- let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
- CursorOverlayInstruction::new(destination, &config, click).expect("valid instruction")
- }
-
- #[test]
- fn sampled_motion_ends_at_the_requested_destination() {
- let destination = Point { x: 900.0, y: 500.0 };
- let frames = motion_frames(
- &state(None),
- &instruction(destination.clone(), false),
- &screen(),
- 120,
- );
-
- assert_eq!(frames.last().map(|pose| &pose.point), Some(&destination));
- let biggest_step = frames
- .windows(2)
- .map(|pair| {
- (pair[1].point.x - pair[0].point.x).hypot(pair[1].point.y - pair[0].point.y)
- })
- .fold(0.0_f64, f64::max);
- assert!(frames.len() >= 20, "the path is sampled per frame");
- assert!(
- biggest_step < 40.0,
- "no visible jump between frames: {biggest_step}"
- );
- }
-
- #[test]
- fn subsequent_motion_starts_from_the_previous_destination() {
- let start = Point { x: 200.0, y: 300.0 };
- let destination = Point { x: 900.0, y: 500.0 };
- let frames = motion_frames(
- &state(Some(start.clone())),
- &instruction(destination.clone(), false),
- &screen(),
- 120,
- );
-
- assert_eq!(frames.first().map(|pose| &pose.point), Some(&start));
- assert_eq!(frames.last().map(|pose| &pose.point), Some(&destination));
- }
-
- #[test]
- fn a_click_instruction_adds_ripple_frames_at_the_destination() {
- let destination = Point { x: 900.0, y: 500.0 };
- let moved = motion_frames(
- &state(None),
- &instruction(destination.clone(), false),
- &screen(),
- 120,
- );
- let clicked = motion_frames(
- &state(None),
- &instruction(destination.clone(), true),
- &screen(),
- 120,
- );
-
- assert!(clicked.len() > moved.len());
- assert!(clicked.iter().any(|pose| pose.ripple > 0.0));
- assert_eq!(clicked.last().map(|pose| &pose.point), Some(&destination));
- }
-
- #[test]
- fn click_effect_returns_immediately_to_the_control_loop() {
- let destination = Point { x: 900.0, y: 500.0 };
- let effect = instruction(destination.clone(), true)
- .with_phase(agent_desktop_core::CursorPhase::Effect);
-
- let frames = motion_frames(&state(Some(destination.clone())), &effect, &screen(), 120);
-
- assert_eq!(frames.len(), 2);
- assert_eq!(frames[0], CursorPose::still(destination.clone()));
- assert_eq!(frames[1].point, destination);
- assert_eq!(frames[1].ripple, 1.0);
- }
-}
+#[path = "child_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/cursor_overlay/child_tests.rs b/crates/macos/src/system/cursor_overlay/child_tests.rs
new file mode 100644
index 000000000..9471de203
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/child_tests.rs
@@ -0,0 +1,122 @@
+use super::*;
+
+#[test]
+fn accepted_stream_waits_for_a_delayed_control() {
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let path =
+ std::path::Path::new("/tmp").join(format!("cd-{}-{unique:x}.sock", std::process::id()));
+ let result = std::panic::catch_unwind(|| {
+ let listener = UnixListener::bind(&path).unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let mut client = UnixStream::connect(&path).unwrap();
+ let (stream, _) = listener.accept().unwrap();
+ prepare_stream(&stream).unwrap();
+ let sender = thread::spawn(move || {
+ thread::sleep(Duration::from_millis(20));
+ let control = CursorOverlayControl::hide("run-delayed".into());
+ client
+ .write_all(&serde_json::to_vec(&control).unwrap())
+ .unwrap();
+ });
+ assert_eq!(read_control(stream).unwrap().session_id(), "run-delayed");
+ sender.join().unwrap();
+ });
+ let _ = std::fs::remove_file(path);
+ result.unwrap();
+}
+
+fn state(at: Option<Point>) -> OverlayState {
+ OverlayState {
+ at,
+ ..OverlayState::default()
+ }
+}
+
+fn screen() -> agent_desktop_core::Rect {
+ agent_desktop_core::Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 1920.0,
+ height: 1080.0,
+ }
+}
+
+fn instruction(destination: Point, click: bool) -> CursorOverlayInstruction {
+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ CursorOverlayInstruction::new(destination, &config, click).expect("valid instruction")
+}
+
+#[test]
+fn sampled_motion_ends_at_the_requested_destination() {
+ let destination = Point { x: 900.0, y: 500.0 };
+ let frames = motion_frames(
+ &state(None),
+ &instruction(destination.clone(), false),
+ &screen(),
+ 120,
+ );
+
+ assert_eq!(frames.last().map(|pose| &pose.point), Some(&destination));
+ let biggest_step = frames
+ .windows(2)
+ .map(|pair| (pair[1].point.x - pair[0].point.x).hypot(pair[1].point.y - pair[0].point.y))
+ .fold(0.0_f64, f64::max);
+ assert!(frames.len() >= 20, "the path is sampled per frame");
+ assert!(
+ biggest_step < 40.0,
+ "no visible jump between frames: {biggest_step}"
+ );
+}
+
+#[test]
+fn subsequent_motion_starts_from_the_previous_destination() {
+ let start = Point { x: 200.0, y: 300.0 };
+ let destination = Point { x: 900.0, y: 500.0 };
+ let frames = motion_frames(
+ &state(Some(start.clone())),
+ &instruction(destination.clone(), false),
+ &screen(),
+ 120,
+ );
+
+ assert_eq!(frames.first().map(|pose| &pose.point), Some(&start));
+ assert_eq!(frames.last().map(|pose| &pose.point), Some(&destination));
+}
+
+#[test]
+fn a_click_instruction_adds_ripple_frames_at_the_destination() {
+ let destination = Point { x: 900.0, y: 500.0 };
+ let moved = motion_frames(
+ &state(None),
+ &instruction(destination.clone(), false),
+ &screen(),
+ 120,
+ );
+ let clicked = motion_frames(
+ &state(None),
+ &instruction(destination.clone(), true),
+ &screen(),
+ 120,
+ );
+
+ assert!(clicked.len() > moved.len());
+ assert!(clicked.iter().any(|pose| pose.ripple > 0.0));
+ assert_eq!(clicked.last().map(|pose| &pose.point), Some(&destination));
+}
+
+#[test]
+fn click_effect_returns_immediately_to_the_control_loop() {
+ let destination = Point { x: 900.0, y: 500.0 };
+ let effect =
+ instruction(destination.clone(), true).with_phase(agent_desktop_core::CursorPhase::Effect);
+
+ let frames = motion_frames(&state(Some(destination.clone())), &effect, &screen(), 120);
+
+ assert_eq!(frames.len(), 2);
+ assert_eq!(frames[0], CursorPose::still(destination.clone()));
+ assert_eq!(frames[1].point, destination);
+ assert_eq!(frames[1].ripple, 1.0);
+}
diff --git a/crates/macos/src/system/cursor_overlay/endpoint.rs b/crates/macos/src/system/cursor_overlay/endpoint.rs
index 3ad4f7c31..184b596e9 100644
--- a/crates/macos/src/system/cursor_overlay/endpoint.rs
+++ b/crates/macos/src/system/cursor_overlay/endpoint.rs
@@ -1,19 +1,32 @@
use agent_desktop_core::{AdapterError, ErrorCode, session};
use std::os::unix::ffi::OsStrExt;
+use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt};
use std::path::{Path, PathBuf};
pub(super) const PROTOCOL_VERSION: &str = "v2";
-pub(super) fn path(session_id: &str) -> Result<PathBuf, AdapterError> {
+pub(super) fn path(session_id: &str, agent_id: Option<&str>) -> Result<PathBuf, AdapterError> {
let root = session::agent_desktop_dir()
.map_err(|error| AdapterError::new(ErrorCode::InvalidArgs, error.to_string()))?;
- Ok(path_for_root(&root, session_id, Some(PROTOCOL_VERSION)))
+ let path = path_for_root(&root, session_id, agent_id);
+ ensure_socket_parent(&path)?;
+ validate_socket_path(&path)?;
+ Ok(path)
}
pub(super) fn legacy_path(session_id: &str) -> Result<PathBuf, AdapterError> {
let root = session::agent_desktop_dir()
.map_err(|error| AdapterError::new(ErrorCode::InvalidArgs, error.to_string()))?;
- Ok(path_for_root(&root, session_id, None))
+ let path = socket_for_name(
+ &root,
+ format!(
+ ".cursor-overlay-{:016x}.sock",
+ endpoint_hash(&root, session_id, None)
+ ),
+ );
+ ensure_socket_parent(&path)?;
+ validate_socket_path(&path)?;
+ Ok(path)
}
pub(super) fn lock_path() -> Result<PathBuf, AdapterError> {
@@ -22,17 +35,195 @@ pub(super) fn lock_path() -> Result<PathBuf, AdapterError> {
Ok(root.join(".cursor-overlay-start.lock"))
}
-fn path_for_root(root: &Path, session_id: &str, protocol: Option<&str>) -> PathBuf {
- let name = format!(
- ".cursor-overlay-{:016x}.sock",
- endpoint_hash(root, session_id, protocol)
- );
+fn path_for_root(root: &Path, session_id: &str, agent_id: Option<&str>) -> PathBuf {
+ let name = match agent_id {
+ Some(agent_id) => format!(
+ ".cursor-overlay-{:016x}-{:016x}.sock",
+ endpoint_hash(root, session_id, Some(PROTOCOL_VERSION)),
+ endpoint_hash(root, agent_id, Some("agent")),
+ ),
+ None => format!(
+ ".cursor-overlay-{:016x}.sock",
+ endpoint_hash(root, session_id, Some(PROTOCOL_VERSION))
+ ),
+ };
+ socket_for_name(root, name)
+}
+
+fn socket_for_name(root: &Path, name: String) -> PathBuf {
let path = root.join(&name);
if path.as_os_str().as_bytes().len() < 100 {
path
} else {
- PathBuf::from("/tmp").join(name)
+ private_fallback_root().join(name)
+ }
+}
+
+fn private_fallback_root() -> PathBuf {
+ PathBuf::from("/tmp").join(format!("agent-desktop-{}", unsafe { libc::geteuid() }))
+}
+
+fn ensure_socket_parent(path: &Path) -> Result<(), AdapterError> {
+ let Some(parent) = path.parent() else {
+ return Ok(());
+ };
+ if parent != private_fallback_root() {
+ return Ok(());
+ }
+ ensure_private_directory(parent)
+}
+
+fn ensure_private_directory(parent: &Path) -> Result<(), AdapterError> {
+ let mut builder = std::fs::DirBuilder::new();
+ builder.mode(0o700);
+ match builder.create(parent) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(error) => {
+ return Err(AdapterError::internal(
+ "Could not create the private cursor overlay socket directory",
+ )
+ .with_platform_detail(error.to_string()));
+ }
+ }
+ if !validate_private_directory(parent)? {
+ return Err(AdapterError::internal(
+ "Cursor overlay socket directory is missing",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_private_directory(parent: &Path) -> Result<bool, AdapterError> {
+ let metadata = match std::fs::symlink_metadata(parent) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(error) => {
+ return Err(AdapterError::internal(
+ "Could not verify the cursor overlay socket directory",
+ )
+ .with_platform_detail(error.to_string()));
+ }
+ };
+ if !metadata.file_type().is_dir()
+ || metadata.uid() != unsafe { libc::geteuid() }
+ || metadata.mode() & 0o077 != 0
+ {
+ return Err(AdapterError::internal(
+ "Cursor overlay socket directory is not private to the current user",
+ ));
+ }
+ Ok(true)
+}
+
+fn validate_socket_path(path: &Path) -> Result<(), AdapterError> {
+ match std::fs::symlink_metadata(path) {
+ Ok(_) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => {
+ return Err(
+ AdapterError::internal("Could not verify the cursor overlay socket")
+ .with_platform_detail(error.to_string()),
+ );
+ }
+ }
+ if !is_private_socket(path) {
+ return Err(AdapterError::internal(
+ "Cursor overlay socket is not owned by the current user",
+ ));
}
+ Ok(())
+}
+
+fn is_private_socket(path: &Path) -> bool {
+ std::fs::symlink_metadata(path).is_ok_and(|metadata| {
+ !metadata.file_type().is_symlink()
+ && metadata.file_type().is_socket()
+ && metadata.uid() == unsafe { libc::geteuid() }
+ && metadata.mode() & 0o077 == 0
+ })
+}
+
+pub(super) fn discover(
+ session_id: &str,
+) -> Result<(Vec<PathBuf>, Option<AdapterError>), AdapterError> {
+ let root = session::agent_desktop_dir()
+ .map_err(|error| AdapterError::new(ErrorCode::InvalidArgs, error.to_string()))?;
+ let prefix = format!(
+ ".cursor-overlay-{:016x}-",
+ endpoint_hash(&root, session_id, Some(PROTOCOL_VERSION))
+ );
+ let fallback = private_fallback_root();
+ let expected = path_for_root(&root, session_id, None);
+ ensure_socket_parent(&expected)?;
+ let mut paths = [expected, legacy_path(session_id)?]
+ .into_iter()
+ .filter(|path| is_private_socket(path))
+ .collect::<Vec<_>>();
+ let needs_fallback =
+ path_for_root(&root, session_id, Some("agent")).parent() == Some(fallback.as_path());
+ let directories = if needs_fallback && validate_private_directory(&fallback)? {
+ vec![root.clone(), fallback]
+ } else {
+ vec![root.clone()]
+ };
+ let (mut scanned, listing_error) = collect_session_sockets(&directories, &prefix);
+ paths.append(&mut scanned);
+ paths.sort();
+ paths.dedup();
+ let listing_error = listing_error.map(|detail| {
+ AdapterError::internal(
+ "Cursor overlay socket directory could not be fully listed; teardown was not confirmed",
+ )
+ .with_platform_detail(detail)
+ });
+ Ok((paths, listing_error))
+}
+
+fn collect_session_sockets(
+ directories: &[PathBuf],
+ prefix: &str,
+) -> (Vec<PathBuf>, Option<String>) {
+ let mut paths = Vec::new();
+ let mut listing_error: Option<String> = None;
+ for directory in directories {
+ let entries = match std::fs::read_dir(directory) {
+ Ok(entries) => entries,
+ Err(error) => {
+ tracing::warn!(path = %directory.display(), %error, "cursor overlay sockets could not be listed");
+ if listing_error.is_none() {
+ listing_error = Some(error.to_string());
+ }
+ continue;
+ }
+ };
+ for entry in entries {
+ let entry = match entry {
+ Ok(entry) => entry,
+ Err(error) => {
+ tracing::warn!(path = %directory.display(), %error, "cursor overlay socket entry could not be read");
+ if listing_error.is_none() {
+ listing_error = Some(error.to_string());
+ }
+ continue;
+ }
+ };
+ let name = entry.file_name();
+ let name = name.to_string_lossy();
+ let suffix = name
+ .strip_prefix(prefix)
+ .and_then(|value| value.strip_suffix(".sock"));
+ if suffix.is_some_and(|value| {
+ value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
+ }) && is_private_socket(&entry.path())
+ {
+ paths.push(entry.path());
+ }
+ }
+ }
+ paths.sort();
+ paths.dedup();
+ (paths, listing_error)
}
fn endpoint_hash(root: &Path, session_id: &str, protocol: Option<&str>) -> u64 {
@@ -53,25 +244,125 @@ fn endpoint_hash(root: &Path, session_id: &str, protocol: Option<&str>) -> u64 {
#[cfg(test)]
mod tests {
use super::*;
+ use std::os::unix::fs::PermissionsExt;
#[test]
fn long_state_root_uses_a_short_deterministic_socket_path() {
let root = Path::new("/private/tmp").join("deep".repeat(40));
- let first = path_for_root(&root, "run-1", Some(PROTOCOL_VERSION));
- let second = path_for_root(&root, "run-1", Some(PROTOCOL_VERSION));
+ let first = path_for_root(&root, "run-1", None);
+ let second = path_for_root(&root, "run-1", None);
assert_eq!(first, second);
- assert_eq!(first.parent(), Some(Path::new("/tmp")));
+ assert_eq!(first.parent(), Some(private_fallback_root().as_path()));
assert!(first.as_os_str().as_bytes().len() < 100);
}
+ #[test]
+ fn private_directory_is_owner_matched_and_mode_restricted() {
+ let directory = std::env::temp_dir().join(format!(
+ "agent-desktop-endpoint-test-{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir(&directory);
+ std::fs::create_dir(&directory).expect("create test directory");
+ std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o755))
+ .expect("make test directory permissive");
+ assert!(ensure_private_directory(&directory).is_err());
+ std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700))
+ .expect("protect test directory");
+
+ ensure_private_directory(&directory).expect("restrict test directory");
+ let metadata = std::fs::symlink_metadata(&directory).expect("read test directory");
+ assert!(metadata.file_type().is_dir());
+ assert_eq!(metadata.uid(), unsafe { libc::geteuid() });
+ assert_eq!(metadata.mode() & 0o777, 0o700);
+ std::fs::remove_dir(&directory).expect("remove test directory");
+ }
+
#[test]
fn protocol_generation_uses_a_distinct_socket() {
let root = Path::new("/private/tmp/state");
assert_ne!(
path_for_root(root, "run-1", None),
- path_for_root(root, "run-1", Some(PROTOCOL_VERSION))
+ path_for_root(root, "run-1", Some("agent-a"))
);
}
+
+ #[test]
+ fn named_endpoints_are_distinct_and_session_prefixed() {
+ let root = Path::new("/private/tmp/state");
+ let first = path_for_root(root, "run-1", Some("agent-a"));
+ let second = path_for_root(root, "run-1", Some("agent-b"));
+ assert_ne!(first, second);
+ assert!(first.file_name().unwrap().to_string_lossy().contains('-'));
+ }
+
+ #[test]
+ fn v2_is_a_valid_agent_id_without_colliding_with_default() {
+ let root = Path::new("/private/tmp/state");
+ assert_ne!(
+ path_for_root(root, "run-1", None),
+ path_for_root(root, "run-1", Some("v2"))
+ );
+ }
+
+ fn bind_private_socket(path: &Path) -> std::os::unix::net::UnixListener {
+ let listener = std::os::unix::net::UnixListener::bind(path).expect("bind test socket");
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
+ .expect("protect test socket");
+ listener
+ }
+
+ #[test]
+ fn socket_validation_uses_the_shared_ownership_predicate() {
+ let directory = std::env::temp_dir().join(format!("ae-p{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&directory);
+ std::fs::create_dir(&directory).expect("create predicate directory");
+ let missing = directory.join("missing.sock");
+ let regular = directory.join("regular.sock");
+ std::fs::write(&regular, "probe").expect("write probe file");
+ let link = directory.join("link.sock");
+ std::os::unix::fs::symlink(&regular, &link).expect("link probe file");
+ let socket = directory.join("live.sock");
+ let listener = bind_private_socket(&socket);
+ assert!(!is_private_socket(&missing));
+ assert!(validate_socket_path(&missing).is_ok());
+ for path in [&regular, &link, &directory] {
+ assert!(!is_private_socket(path));
+ assert!(validate_socket_path(path).is_err());
+ }
+ assert!(is_private_socket(&socket));
+ assert!(validate_socket_path(&socket).is_ok());
+ drop(listener);
+ std::fs::remove_dir_all(&directory).expect("remove predicate directory");
+ }
+
+ #[test]
+ fn partial_listing_keeps_sockets_but_reports_unconfirmed_teardown() {
+ if unsafe { libc::geteuid() } == 0 {
+ return;
+ }
+ let directory = std::env::temp_dir().join(format!("ae-s{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&directory);
+ let listed = directory.join("l");
+ let blocked = directory.join("b");
+ std::fs::create_dir_all(&listed).expect("create listed directory");
+ std::fs::create_dir_all(&blocked).expect("create blocked directory");
+ let prefix = ".co-0123abcd-";
+ let socket = listed.join(format!("{prefix}0011223344556677.sock"));
+ let listener = bind_private_socket(&socket);
+ let decoy = listed.join(format!("{prefix}aabbccddeeff0011.sock"));
+ std::fs::write(&decoy, "probe").expect("write decoy file");
+ std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o000))
+ .expect("block directory listing");
+ let (paths, error) = collect_session_sockets(&[listed, blocked.clone()], prefix);
+ std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o700))
+ .expect("restore blocked directory");
+ assert!(!paths.contains(&decoy));
+ assert_eq!(paths, vec![socket]);
+ assert!(error.is_some());
+ drop(listener);
+ std::fs::remove_dir_all(&directory).expect("remove scan directory");
+ }
}
diff --git a/crates/macos/src/system/cursor_overlay/spawn.rs b/crates/macos/src/system/cursor_overlay/spawn.rs
index c19585de6..9d5c354fd 100644
--- a/crates/macos/src/system/cursor_overlay/spawn.rs
+++ b/crates/macos/src/system/cursor_overlay/spawn.rs
@@ -1,9 +1,7 @@
use agent_desktop_core::{
AdapterError, CURSOR_ARRIVAL_TIMEOUT_MS, CursorOverlayControl, ErrorCode,
};
-use std::fs::OpenOptions;
use std::io::{Read, Write};
-use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::net::UnixStream;
use std::os::unix::process::CommandExt;
use std::path::Path;
@@ -17,37 +15,84 @@ const MAX_INSTRUCTION_BYTES: usize = 4 * 1024;
pub(crate) fn update(control: &CursorOverlayControl) -> Result<(), AdapterError> {
control.validate()?;
- let socket = super::endpoint::path(control.session_id())?;
- if send(&socket, control).is_ok() {
+ if control.is_disable() || (control.is_transient() && control.agent_id().is_none()) {
+ return broadcast(control);
+ }
+ if !control.is_transient()
+ && !super::child::session_active(control.session_id(), control.agent_id())
+ {
+ return Ok(());
+ }
+ let budget = if matches!(control, CursorOverlayControl::Present { .. }) {
+ CURSOR_ARRIVAL_TIMEOUT_MS
+ } else {
+ 4_000
+ };
+ let deadline = Instant::now() + agent_desktop_core::Deadline::after(budget)?.remaining();
+ let socket = super::endpoint::path(control.session_id(), control.agent_id())?;
+ if send_until(&socket, control, deadline)? {
return Ok(());
}
- retire_legacy(control);
- if control.is_disable() || (control.is_transient() && !control.is_travel()) {
+ if control.agent_id().is_none() {
+ retire_legacy(control, deadline);
+ }
+ if control.is_transient() {
return Ok(());
}
let lock_path = super::endpoint::lock_path()?;
- let lock = OpenOptions::new()
- .create(true)
- .read(true)
- .truncate(false)
- .write(true)
- .mode(0o600)
- .open(lock_path)
- .map_err(|error| {
- AdapterError::internal("Could not open the cursor overlay startup lock")
- .with_platform_detail(error.to_string())
- })?;
- lock.lock().map_err(|error| {
- AdapterError::internal("Could not acquire the cursor overlay startup lock")
- .with_platform_detail(error.to_string())
- })?;
- if send(&socket, control).is_ok() {
+ let _lock = startup_lock(&lock_path, deadline)?;
+ if send_until(&socket, control, deadline)? {
+ return Ok(());
+ }
+ if !super::child::session_active(control.session_id(), control.agent_id()) {
return Ok(());
}
- spawn(&socket, control)
+ spawn(&socket, control, deadline)
+}
+
+fn broadcast(control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ let lock_path = super::endpoint::lock_path()?;
+ let deadline = Instant::now() + Duration::from_secs(4);
+ let _lock = startup_lock(&lock_path, deadline)?;
+ let (paths, mut first_error) = super::endpoint::discover(control.session_id())?;
+ for socket in paths {
+ if Instant::now() >= deadline {
+ return Err(AdapterError::internal(
+ "Timed out stopping macOS cursor overlays",
+ ));
+ }
+ if let Err(error) = send_until(&socket, control, deadline) {
+ first_error.get_or_insert(error);
+ }
+ }
+ first_error.map_or(Ok(()), Err)
+}
+
+fn startup_lock(
+ path: &Path,
+ deadline: Instant,
+) -> Result<agent_desktop_core::FileLock, AdapterError> {
+ agent_desktop_core::FileLock::acquire(
+ path,
+ agent_desktop_core::Deadline::detached_after(
+ deadline
+ .saturating_duration_since(Instant::now())
+ .as_millis() as u64,
+ )?,
+ "cursor overlay startup lock",
+ )
}
-fn spawn(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+fn spawn(
+ socket: &Path,
+ control: &CursorOverlayControl,
+ deadline: Instant,
+) -> Result<(), AdapterError> {
+ if Instant::now() >= deadline {
+ return Err(AdapterError::internal(
+ "Cursor overlay startup deadline elapsed",
+ ));
+ }
let executable = std::env::current_exe().map_err(|error| {
AdapterError::internal("Could not locate the cursor overlay executable")
.with_platform_detail(error.to_string())
@@ -77,39 +122,90 @@ fn spawn(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErr
AdapterError::internal("Could not start the macOS cursor overlay")
.with_platform_detail(error.to_string())
})?;
- let mut stdin = child.stdin.take().ok_or_else(|| {
- AdapterError::internal("Cursor overlay child did not expose its input pipe")
- })?;
- stdin.write_all(&payload).map_err(|error| {
- AdapterError::internal("Could not send the cursor overlay control")
- .with_platform_detail(error.to_string())
- })?;
+ let Some(mut stdin) = child.stdin.take() else {
+ let exited = terminate_child(&mut child);
+ return Err(AdapterError::internal(if exited {
+ "Cursor overlay child did not expose its input pipe"
+ } else {
+ "Cursor overlay child could not be reaped after startup failure"
+ }));
+ };
+ if let Err(error) = stdin.write_all(&payload) {
+ if !terminate_child(&mut child) {
+ return Err(AdapterError::internal(
+ "Cursor overlay child did not exit after startup failure",
+ ));
+ }
+ return Err(
+ AdapterError::internal("Could not send the cursor overlay control")
+ .with_platform_detail(error.to_string()),
+ );
+ }
drop(stdin);
- let deadline = Instant::now() + Duration::from_millis(CURSOR_ARRIVAL_TIMEOUT_MS);
while Instant::now() < deadline {
if UnixStream::connect(socket).is_ok() {
return Ok(());
}
thread::sleep(Duration::from_millis(10));
}
+ if !terminate_child(&mut child) {
+ return Err(AdapterError::internal(
+ "Cursor overlay child did not exit after startup failure",
+ ));
+ }
Err(AdapterError::internal(
"macOS cursor overlay did not become ready",
))
}
-fn retire_legacy(control: &CursorOverlayControl) {
+fn terminate_child(child: &mut std::process::Child) -> bool {
+ let _ = child.kill();
+ let deadline = Instant::now() + Duration::from_secs(2);
+ super::super::process::poll_reap(child, deadline)
+}
+
+fn retire_legacy(control: &CursorOverlayControl, deadline: Instant) {
let Ok(socket) = super::endpoint::legacy_path(control.session_id()) else {
return;
};
let disable = CursorOverlayControl::disable(control.session_id().to_owned());
- let _ = send(&socket, &disable);
+ let _ = send_until(&socket, &disable, deadline);
}
-fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterError> {
- let mut stream = UnixStream::connect(socket).map_err(|error| {
- AdapterError::internal("Could not connect to the macOS cursor overlay")
- .with_platform_detail(error.to_string())
- })?;
+fn send_until(
+ socket: &Path,
+ control: &CursorOverlayControl,
+ deadline: Instant,
+) -> Result<bool, AdapterError> {
+ let mut stream = match UnixStream::connect(socket) {
+ Ok(stream) => stream,
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
+ ) =>
+ {
+ return Ok(false);
+ }
+ Err(error) => {
+ return Err(
+ AdapterError::internal("Could not connect to the macOS cursor overlay")
+ .with_platform_detail(error.to_string()),
+ );
+ }
+ };
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return Err(AdapterError::internal(
+ "Cursor overlay control deadline elapsed",
+ ));
+ }
+ stream
+ .set_write_timeout(Some(remaining.min(Duration::from_secs(1))))
+ .map_err(|error| {
+ AdapterError::internal("Could not bound the cursor overlay control write")
+ .with_platform_detail(error.to_string())
+ })?;
let payload = serde_json::to_vec(control).map_err(|error| {
AdapterError::internal("Could not encode macOS cursor overlay control")
.with_platform_detail(error.to_string())
@@ -126,7 +222,7 @@ fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErro
})?;
let travels = control.is_travel();
if !travels && !control.is_hide() && !control.is_disable() {
- return Ok(());
+ return Ok(true);
}
stream
.shutdown(std::net::Shutdown::Write)
@@ -134,10 +230,15 @@ fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErro
AdapterError::internal("Could not finish the cursor overlay control")
.with_platform_detail(error.to_string())
})?;
- let budget = if travels {
- Duration::from_millis(CURSOR_ARRIVAL_TIMEOUT_MS)
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ let budget = if remaining.is_zero() {
+ return Err(AdapterError::internal(
+ "Timed out stopping macOS cursor overlays",
+ ));
+ } else if travels {
+ remaining.min(Duration::from_millis(CURSOR_ARRIVAL_TIMEOUT_MS))
} else {
- Duration::from_secs(4)
+ remaining
};
stream.set_read_timeout(Some(budget)).map_err(|error| {
AdapterError::internal("Could not bound the cursor overlay acknowledgement")
@@ -145,10 +246,22 @@ fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErro
})?;
let mut acknowledgement = [0_u8; 1];
match stream.read_exact(&mut acknowledgement) {
- Ok(()) => Ok(()),
- Err(error) if travels => {
- tracing::debug!(%error, "cursor overlay arrival was not acknowledged in time");
- Ok(())
+ Ok(()) => Ok(true),
+ Err(error)
+ if control.instruction().is_some_and(|instruction| {
+ instruction.phase() == agent_desktop_core::CursorPhase::Travel
+ }) =>
+ {
+ tracing::warn!(
+ session = control.session_id(),
+ agent = control.agent_id(),
+ %error,
+ "cursor overlay travel was not acknowledged; continuing without cursor confirmation"
+ );
+ Err(
+ AdapterError::internal("macOS cursor overlay did not confirm cursor arrival")
+ .with_platform_detail(error.to_string()),
+ )
}
Err(error) => Err(AdapterError::internal(
"macOS cursor overlay did not acknowledge the control",
@@ -156,3 +269,7 @@ fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErro
.with_platform_detail(error.to_string())),
}
}
+
+#[cfg(test)]
+#[path = "spawn_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/cursor_overlay/spawn_tests.rs b/crates/macos/src/system/cursor_overlay/spawn_tests.rs
new file mode 100644
index 000000000..6df490ab1
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/spawn_tests.rs
@@ -0,0 +1,47 @@
+use super::*;
+use std::os::unix::net::UnixListener;
+
+#[test]
+fn travel_acknowledgement_obeys_remaining_budget() {
+ check_acknowledgement(agent_desktop_core::CursorPhase::Travel, false);
+}
+
+#[test]
+fn drag_requires_acknowledgement_before_tracking_is_considered_ready() {
+ check_acknowledgement(agent_desktop_core::CursorPhase::Drag, false);
+}
+
+fn check_acknowledgement(phase: agent_desktop_core::CursorPhase, accepted: bool) {
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let path = std::path::PathBuf::from(format!("/tmp/ca-{}-{unique:x}.sock", std::process::id()));
+ let result = std::panic::catch_unwind(|| {
+ let listener = UnixListener::bind(&path).unwrap();
+ let receiver = thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ let mut payload = Vec::new();
+ stream.read_to_end(&mut payload).unwrap();
+ thread::sleep(Duration::from_millis(700));
+ });
+ let instruction = agent_desktop_core::CursorOverlayInstruction::new(
+ agent_desktop_core::Point { x: 10.0, y: 20.0 },
+ &agent_desktop_core::CursorOverlayConfig::enabled(None, 8).unwrap(),
+ false,
+ )
+ .unwrap()
+ .with_phase(phase);
+ let control = CursorOverlayControl::present("run-budget".into(), instruction);
+ let started = Instant::now();
+ assert_eq!(
+ send_until(&path, &control, started + Duration::from_millis(30)).is_ok(),
+ accepted
+ );
+ let elapsed = started.elapsed();
+ receiver.join().unwrap();
+ assert!(elapsed < Duration::from_millis(500), "{elapsed:?}");
+ });
+ let _ = std::fs::remove_file(path);
+ result.unwrap();
+}
diff --git a/crates/macos/src/system/cursor_overlay_bridge.m b/crates/macos/src/system/cursor_overlay_bridge.m
index d60f5ea44..8884e4e54 100644
--- a/crates/macos/src/system/cursor_overlay_bridge.m
+++ b/crates/macos/src/system/cursor_overlay_bridge.m
@@ -36,6 +36,70 @@ static __strong CALayer *ADPointer = nil;
static __strong NSWindow *ADRipple = nil;
static __strong NSWindow *ADBubbleWindow = nil;
static __strong NSTextField *ADBubbleText = nil;
+static bool ADDragArmed = false;
+static bool ADDragStarted = false;
+static bool ADDragTrail = false;
+static CGPoint ADDragLast = {0.0, 0.0};
+static CFTimeInterval ADDragArmDeadline = 0.0;
+static CFTimeInterval ADDragDeadline = 0.0;
+
+static void ADMoveCursor(const AgentDesktopCursorFrame *frame, double mainHeight);
+
+static void ADDragCancel(void) {
+ ADDragArmed = false;
+ ADDragStarted = false;
+ ADTrailStop();
+}
+
+static void ADDragPoll(void) {
+ if (!ADDragArmed) {
+ return;
+ }
+ CFTimeInterval now = CACurrentMediaTime();
+ bool down = CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState,
+ kCGMouseButtonLeft);
+ if (now >= ADDragDeadline || (!ADDragStarted && now >= ADDragArmDeadline)) {
+ ADDragCancel();
+ return;
+ }
+ if (!down) {
+ if (ADDragStarted) {
+ if (ADDragTrail) {
+ ADTrailFinish(0.9);
+ }
+ ADDragArmed = false;
+ ADDragStarted = false;
+ }
+ return;
+ }
+ CGEventRef event = CGEventCreate(NULL);
+ if (event == NULL) {
+ return;
+ }
+ CGPoint point = CGEventGetLocation(event);
+ CFRelease(event);
+ if (ADDragStarted && CGPointEqualToPoint(point, ADDragLast)) {
+ return;
+ }
+ double mainHeight = CGDisplayBounds(CGMainDisplayID()).size.height;
+ if (!ADDragStarted) {
+ ADDragStarted = true;
+ ADDragLast = point;
+ if (ADDragTrail) {
+ ADTrailBegin(NSMakePoint(point.x, mainHeight - point.y));
+ }
+ } else if (ADBubbleWindow.isVisible) {
+ NSPoint origin = ADBubbleWindow.frame.origin;
+ [ADBubbleWindow setFrameOrigin:NSMakePoint(origin.x + point.x - ADDragLast.x,
+ origin.y - point.y + ADDragLast.y)];
+ }
+ AgentDesktopCursorFrame frame = {.x = point.x, .y = point.y, .ripple = 0.0};
+ ADMoveCursor(&frame, mainHeight);
+ if (ADDragTrail) {
+ ADTrailAppend(NSMakePoint(point.x, mainHeight - point.y));
+ }
+ ADDragLast = point;
+}
static CAShapeLayer *ADDartLayer(void) {
static const CGPoint dart[] = {
@@ -106,15 +170,18 @@ static NSWindow *ADBubble(void) {
void agent_desktop_cursor_overlay_idle(void) {
@autoreleasepool {
+ ADDragPoll();
ADPump(NSApplication.sharedApplication);
}
}
void agent_desktop_cursor_overlay_stop(void) {
+ ADDragCancel();
[ADCursorWindow orderOut:nil];
[ADBubbleWindow orderOut:nil];
[ADRipple orderOut:nil];
ADHighlightStop();
+ ADTrailStop();
ADCursorWindow = nil;
ADPointer = nil;
ADRipple = nil;
@@ -135,14 +202,67 @@ void agent_desktop_cursor_overlay_rest(void) {
[ADBubbleWindow orderOut:nil];
ADCursorWindow.alphaValue = 1.0;
ADBubbleWindow.alphaValue = 1.0;
+ ADTrailStop();
}
}
void agent_desktop_cursor_overlay_hide(void) {
+ ADDragCancel();
[ADCursorWindow orderOut:nil];
[ADBubbleWindow orderOut:nil];
[ADRipple orderOut:nil];
ADHighlightStop();
+ ADTrailStop();
+}
+
+void agent_desktop_cursor_overlay_drag_begin(double fromX, double fromY, bool trail) {
+ @try {
+ @autoreleasepool {
+ (void)fromX;
+ (void)fromY;
+ ADDragCancel();
+ ADDragArmed = true;
+ ADDragTrail = trail;
+ CFTimeInterval now = CACurrentMediaTime();
+ ADDragArmDeadline = now + 1.0;
+ ADDragDeadline = now + 95.0;
+ }
+ } @catch (NSException *exception) {
+ (void)exception;
+ ADDragCancel();
+ }
+}
+
+void agent_desktop_cursor_overlay_drag_end(double toX, double toY, bool completed) {
+ @try {
+ @autoreleasepool {
+ if (!ADDragArmed) {
+ return;
+ }
+ if (!completed) {
+ ADDragCancel();
+ return;
+ }
+ double mainHeight = CGDisplayBounds(CGMainDisplayID()).size.height;
+ AgentDesktopCursorFrame frame = {.x = toX, .y = toY, .ripple = 0.0};
+ ADMoveCursor(&frame, mainHeight);
+ if (ADDragTrail) {
+ ADTrailAppend(NSMakePoint(toX, mainHeight - toY));
+ ADTrailFinish(0.9);
+ }
+ ADDragArmed = false;
+ ADDragStarted = false;
+ }
+ } @catch (NSException *exception) {
+ (void)exception;
+ if (ADDragArmed) {
+ ADDragCancel();
+ }
+ }
+}
+
+bool agent_desktop_cursor_overlay_drag_active(void) {
+ return ADDragArmed;
}
void agent_desktop_cursor_overlay_show(void) {
diff --git a/crates/macos/src/system/cursor_overlay_chrome.h b/crates/macos/src/system/cursor_overlay_chrome.h
index 27205c9a8..2591f7dbb 100644
--- a/crates/macos/src/system/cursor_overlay_chrome.h
+++ b/crates/macos/src/system/cursor_overlay_chrome.h
@@ -1,3 +1,5 @@
+#pragma once
+
#import <AppKit/AppKit.h>
#import <QuartzCore/QuartzCore.h>
@@ -20,4 +22,8 @@ NSWindow *ADRippleWindow(void);
void ADRipplePlay(NSWindow *window);
void ADHighlightShow(NSRect frame, double seconds);
void ADHighlightStop(void);
+void ADTrailBegin(NSPoint point);
+void ADTrailAppend(NSPoint point);
+void ADTrailFinish(double seconds);
+void ADTrailStop(void);
void ADShowBubble(NSTextField *text, NSRect frame, bool changed);
diff --git a/crates/macos/src/system/cursor_overlay_chrome_bridge.m b/crates/macos/src/system/cursor_overlay_chrome_bridge.m
index 7f4d789df..130bae7e2 100644
--- a/crates/macos/src/system/cursor_overlay_chrome_bridge.m
+++ b/crates/macos/src/system/cursor_overlay_chrome_bridge.m
@@ -13,6 +13,45 @@ static AgentDesktopCursorStyle ADCurrentStyle = {
static __strong NSWindow *ADHighlightWindow = nil;
static __strong CALayer *ADHighlightBorder = nil;
+static __strong NSWindow *ADTrailWindow = nil;
+static __strong CAShapeLayer *ADTrailLayer = nil;
+static CGMutablePathRef ADTrailPath = NULL;
+static NSRect ADTrailDesktop = {{0.0, 0.0}, {0.0, 0.0}};
+static NSPoint ADTrailLast = {0.0, 0.0};
+static NSUInteger ADTrailPointCount = 0;
+
+static void ADTrailRender(void) {
+ CGRect bounds = CGPathGetBoundingBox(ADTrailPath);
+ NSRect frame = NSIntersectionRect(NSInsetRect(bounds, -10.0, -10.0),
+ NSInsetRect(ADTrailDesktop, -10.0, -10.0));
+ if (NSIsEmptyRect(frame)) {
+ return;
+ }
+ if (ADTrailWindow == nil) {
+ ADTrailWindow = ADWindow(frame);
+ ADTrailWindow.level = ADEffectLevel;
+ ADTrailLayer = [CAShapeLayer layer];
+ ADTrailLayer.fillColor = ADColor(ADCurrentStyle.accent, 0.9);
+ ADTrailLayer.strokeColor = ADColor(ADCurrentStyle.accent, 0.9);
+ ADTrailLayer.lineWidth = 4.0;
+ ADTrailLayer.lineCap = kCALineCapRound;
+ ADTrailLayer.lineJoin = kCALineJoinRound;
+ ADTrailLayer.shadowColor = ADColor(ADCurrentStyle.accent, 1.0);
+ ADTrailLayer.shadowOpacity = 0.45;
+ ADTrailLayer.shadowRadius = 6.0;
+ ADFreezeLayer(ADTrailLayer);
+ [ADTrailWindow.contentView.layer addSublayer:ADTrailLayer];
+ } else {
+ [ADTrailWindow setFrame:frame display:NO];
+ }
+ ADTrailLayer.frame = ADTrailWindow.contentView.bounds;
+ CGAffineTransform translation = CGAffineTransformMakeTranslation(-frame.origin.x,
+ -frame.origin.y);
+ CGPathRef localPath = CGPathCreateCopyByTransformingPath(ADTrailPath, &translation);
+ ADTrailLayer.path = localPath;
+ CGPathRelease(localPath);
+ [ADTrailWindow orderFrontRegardless];
+}
CGColorRef ADColor(const double *rgb, CGFloat alpha) {
return [NSColor colorWithSRGBRed:rgb[0] green:rgb[1] blue:rgb[2] alpha:alpha].CGColor;
@@ -182,6 +221,72 @@ void ADHighlightStop(void) {
ADHighlightBorder = nil;
}
+static void ADTrailBeginInFrame(NSPoint point, NSRect desktop) {
+ ADTrailStop();
+ ADTrailDesktop = desktop;
+ if (NSEqualRects(ADTrailDesktop, NSZeroRect)) {
+ return;
+ }
+ ADTrailPath = CGPathCreateMutable();
+ ADTrailLast = point;
+ ADTrailPointCount = 1;
+ CGPathAddEllipseInRect(ADTrailPath, NULL, CGRectMake(point.x - 4.0, point.y - 4.0, 8.0, 8.0));
+ ADTrailRender();
+}
+
+void ADTrailBegin(NSPoint point) {
+ NSRect desktop = NSZeroRect;
+ for (NSScreen *screen in NSScreen.screens) {
+ desktop = NSEqualRects(desktop, NSZeroRect) ? screen.frame
+ : NSUnionRect(desktop, screen.frame);
+ }
+ ADTrailBeginInFrame(point, desktop);
+}
+
+void ADTrailAppend(NSPoint point) {
+ if (ADTrailPath == NULL || hypot(point.x - ADTrailLast.x, point.y - ADTrailLast.y) < 2.0) {
+ return;
+ }
+ if (ADTrailPointCount >= 4096) {
+ ADTrailLast = point;
+ return;
+ }
+ CGPathMoveToPoint(ADTrailPath, NULL, ADTrailLast.x, ADTrailLast.y);
+ CGPathAddLineToPoint(ADTrailPath, NULL, point.x, point.y);
+ ADTrailLast = point;
+ ADTrailPointCount += 1;
+ ADTrailRender();
+}
+
+void ADTrailFinish(double seconds) {
+ if (ADTrailLayer == nil) {
+ return;
+ }
+ CGPathAddEllipseInRect(ADTrailPath,
+ NULL,
+ CGRectMake(ADTrailLast.x - 4.0, ADTrailLast.y - 4.0, 8.0, 8.0));
+ ADTrailRender();
+ [ADTrailLayer removeAllAnimations];
+ [ADTrailLayer addAnimation:ADHold(@"opacity",
+ @[ @1.0, @1.0, @0.0 ],
+ @[ @0.0, @0.55, @1.0 ],
+ seconds)
+ forKey:@"agent-drag-trail-fade"];
+}
+
+void ADTrailStop(void) {
+ [ADTrailLayer removeAllAnimations];
+ [ADTrailWindow orderOut:nil];
+ ADTrailLayer = nil;
+ ADTrailWindow = nil;
+ if (ADTrailPath != NULL) {
+ CGPathRelease(ADTrailPath);
+ ADTrailPath = NULL;
+ }
+ ADTrailDesktop = NSZeroRect;
+ ADTrailPointCount = 0;
+}
+
void ADShowBubble(NSTextField *text, NSRect frame, bool changed) {
NSWindow *bubble = text.window;
CALayer *surface = bubble.contentView.layer;
diff --git a/crates/macos/src/system/process.rs b/crates/macos/src/system/process.rs
index 8c6a71d26..6ee15a3c2 100644
--- a/crates/macos/src/system/process.rs
+++ b/crates/macos/src/system/process.rs
@@ -207,7 +207,7 @@ fn signal_group(process_group: i32, signal: i32) -> std::io::Result<bool> {
}
}
-fn poll_reap(child: &mut Child, deadline: Instant) -> bool {
+pub(super) fn poll_reap(child: &mut Child, deadline: Instant) -> bool {
loop {
match child.try_wait() {
Ok(Some(_)) => return true,
diff --git a/crates/macos/src/system/screenshot.rs b/crates/macos/src/system/screenshot.rs
index 8d35eed4d..b9a84bb64 100644
--- a/crates/macos/src/system/screenshot.rs
+++ b/crates/macos/src/system/screenshot.rs
@@ -101,7 +101,7 @@ mod imp {
)
.with_suggestion("Refresh the target with 'list-windows', then retry"));
}
- let verified = crate::system::window_resolve::resolve_window_strict(
+ let verified = crate::system::window_resolve::resolve_capture_window(
window,
deadline_instant(deadline)?,
)?;
@@ -109,7 +109,7 @@ mod imp {
let scale = crate::system::display::scale_for_bounds(verified.bounds, deadline)?;
ensure_budget(deadline)?;
let captured = capture(scale, deadline, |path| Ok(window_args(window_id, path)))?;
- crate::system::window_resolve::resolve_window_strict(
+ crate::system::window_resolve::resolve_capture_window(
&verified,
deadline_instant(deadline)?,
)?;
diff --git a/crates/macos/src/system/window_resolve.rs b/crates/macos/src/system/window_resolve.rs
index 90c608c96..c34156e07 100644
--- a/crates/macos/src/system/window_resolve.rs
+++ b/crates/macos/src/system/window_resolve.rs
@@ -34,6 +34,14 @@ pub(crate) fn window_element_for_info_with_deadline(
resolve_window_element_strict(win, deadline)
}
+pub(crate) fn resolve_capture_window(
+ win: &WindowInfo,
+ deadline: std::time::Instant,
+) -> Result<WindowInfo, AdapterError> {
+ let (_, record) = locate_verified_record_until(win, deadline)?;
+ window_info_from_record(win, &record)
+}
+
pub(crate) fn resolve_window_strict(
win: &WindowInfo,
deadline: std::time::Instant,
diff --git a/crates/macos/src/system/window_resolve_tests.rs b/crates/macos/src/system/window_resolve_tests.rs
index a399391bc..0d714df81 100644
--- a/crates/macos/src/system/window_resolve_tests.rs
+++ b/crates/macos/src/system/window_resolve_tests.rs
@@ -94,6 +94,15 @@ fn resolved_window_preserves_verified_core_graphics_bounds() {
assert_eq!(resolved.bounds, Some(live.bounds));
}
+#[test]
+fn capture_verification_rejects_expired_deadline_before_native_reads() {
+ let requested = win("w-100", 10, "Untitled");
+ let error = resolve_capture_window(&requested, std::time::Instant::now())
+ .expect_err("expired capture verification");
+
+ assert_eq!(error.code, ErrorCode::Timeout);
+}
+
#[test]
fn source_identity_survives_window_move_and_resize() {
let pid = current_pid();
diff --git a/crates/macos/src/tree/action_list.rs b/crates/macos/src/tree/action_list.rs
index 81c2d9e87..cbe538ac7 100644
--- a/crates/macos/src/tree/action_list.rs
+++ b/crates/macos/src/tree/action_list.rs
@@ -42,7 +42,7 @@ pub(crate) fn read_platform_available_actions(
usage: &mut crate::tree::observation_usage::ObservationUsage,
) -> AvailableActionsRead {
let mut read = AvailableActionsRead::default();
- if crate::tree::locator_deadline::prepare(el, deadline).is_err() {
+ if crate::tree::locator_deadline::remaining(deadline).is_err() {
read.complete = false;
read.deadline_exhausted = true;
return read;
@@ -116,7 +116,7 @@ fn read_settable(
deadline: std::time::Instant,
read: &mut AvailableActionsRead,
) -> Option<bool> {
- if crate::tree::locator_deadline::prepare(element, deadline).is_err() {
+ if crate::tree::locator_deadline::remaining(deadline).is_err() {
read.complete = false;
read.deadline_exhausted = true;
return None;
diff --git a/crates/macos/src/tree/element_dedupe.rs b/crates/macos/src/tree/element_dedupe.rs
index 434e7801b..24c96e241 100644
--- a/crates/macos/src/tree/element_dedupe.rs
+++ b/crates/macos/src/tree/element_dedupe.rs
@@ -1,31 +1,14 @@
use super::{AXElement, same_element};
-#[derive(Default)]
-pub(crate) struct ElementDedupe;
-
-impl ElementDedupe {
- pub(crate) fn push(&mut self, elements: &mut Vec<AXElement>, element: AXElement) -> bool {
- if elements
- .iter()
- .any(|existing| equivalent(existing, &element))
- {
- return false;
- }
- elements.push(element);
- true
- }
-
- pub(crate) fn push_clone(
- &mut self,
- elements: &mut Vec<AXElement>,
- element: &AXElement,
- ) -> bool {
- self.push(elements, element.clone())
+pub(crate) fn push_unique(elements: &mut Vec<AXElement>, element: AXElement) -> bool {
+ if elements
+ .iter()
+ .any(|existing| !existing.0.is_null() && same_element(existing, &element))
+ {
+ return false;
}
-}
-
-fn equivalent(existing: &AXElement, element: &AXElement) -> bool {
- existing.0 as usize != 0 && same_element(existing, element)
+ elements.push(element);
+ true
}
#[cfg(test)]
@@ -34,24 +17,22 @@ mod tests {
#[test]
fn null_elements_do_not_collapse_without_semantic_identity() {
- let mut dedupe = ElementDedupe;
let mut elements = Vec::new();
- assert!(dedupe.push(&mut elements, null_element()));
- assert!(dedupe.push(&mut elements, null_element()));
+ assert!(push_unique(&mut elements, null_element()));
+ assert!(push_unique(&mut elements, null_element()));
assert_eq!(elements.len(), 2);
}
#[cfg(target_os = "macos")]
#[test]
fn same_ax_element_collapses_to_one_candidate() {
- let mut dedupe = ElementDedupe;
let mut elements = Vec::new();
let element = current_process_element();
let same = element.clone();
- assert!(dedupe.push(&mut elements, element));
- assert!(!dedupe.push(&mut elements, same));
+ assert!(push_unique(&mut elements, element));
+ assert!(!push_unique(&mut elements, same));
assert_eq!(elements.len(), 1);
}
diff --git a/crates/macos/src/tree/node_attribute_fetch.rs b/crates/macos/src/tree/node_attribute_fetch.rs
index e4999e93a..531db293a 100644
--- a/crates/macos/src/tree/node_attribute_fetch.rs
+++ b/crates/macos/src/tree/node_attribute_fetch.rs
@@ -33,10 +33,8 @@ mod imp {
usage: &mut crate::tree::observation_usage::ObservationUsage,
) -> NodeAttributeRead {
let mask = crate::tree::node_attribute_names::safe_attribute_mask(requirements);
- let requested =
- crate::tree::node_attribute_names::requested_indices(mask).collect::<Vec<_>>();
- let mut requested_count = requested.len() as u64;
- if crate::tree::locator_deadline::prepare(element, deadline).is_err() {
+ let mut requested_count = u64::from(mask.count_ones());
+ if crate::tree::locator_deadline::remaining(deadline).is_err() {
return failed_node_attribute_read(
accessibility_sys::kAXErrorCannotComplete,
requested_count,
@@ -63,6 +61,9 @@ mod imp {
let Some(attributes) = created_cf_array(batch_result) else {
return failed_node_attribute_read(kAXErrorFailure, requested_count, false, 1);
};
+ if attributes.len() as u64 != requested_count {
+ return failed_node_attribute_read(kAXErrorFailure, requested_count, false, 1);
+ }
let mut batch_reads = 1;
let fallback_reads = 0;
@@ -74,7 +75,9 @@ mod imp {
let mut subrole = None;
let mut status = NodeAttributeStatus::default();
let mut deadline_exhausted = false;
- for (index, item) in requested.into_iter().zip(attributes.into_iter()) {
+ for (index, item) in
+ crate::tree::node_attribute_names::requested_indices(mask).zip(attributes.into_iter())
+ {
if node_attribute_decode::is_null(&item) {
continue;
}
@@ -130,8 +133,7 @@ mod imp {
_ => {}
}
}
- let get = |index: usize| texts.get(index).and_then(Clone::clone);
- let role = get(ROLE);
+ let role = texts[ROLE].take();
if status.field_unknown(SUBROLE) {
subrole = None;
}
@@ -146,7 +148,7 @@ mod imp {
) {
batch_reads += 1;
requested_count += 1;
- if crate::tree::locator_deadline::prepare(element, deadline).is_err() {
+ if crate::tree::locator_deadline::remaining(deadline).is_err() {
deadline_exhausted = true;
status.record_slot_error(VALUE, accessibility_sys::kAXErrorCannotComplete);
} else {
@@ -190,8 +192,7 @@ mod imp {
} else if requirements.value && (!role_complete || !subrole_complete) {
status.record_slot_error(VALUE, accessibility_sys::kAXErrorCannotComplete);
}
- let get = |index: usize| texts.get(index).and_then(Clone::clone);
- let value = get(VALUE);
+ let value = texts[VALUE].take();
let readonly = if requirements.states {
crate::tree::readonly::read_readonly(element, role.as_deref(), deadline)
} else {
@@ -206,15 +207,21 @@ mod imp {
status.record_readonly_error(error);
}
deadline_exhausted |= readonly.deadline_exhausted;
- let identifier_field = |index| {
+ let mut identifier_field = |index: usize| {
if status.field_unknown(index) {
agent_desktop_core::LocatorField::Unknown
} else {
- get(index)
+ texts[index]
+ .take()
.map(agent_desktop_core::LocatorField::Known)
.unwrap_or(agent_desktop_core::LocatorField::Absent)
}
};
+ let identifiers = NodeIdentifiers::from_fields(
+ identifier_field(AX_IDENTIFIER),
+ identifier_field(AX_DOM_IDENTIFIER),
+ );
+ let mut get = |index: usize| texts[index].take();
NodeAttributeRead {
attrs: NodeAttrs {
name_evidence: agent_desktop_core::NameEvidence {
@@ -255,10 +262,7 @@ mod imp {
.and_then(|(position, size)| rect_from_parts(position, size)),
has_scrollbars,
},
- identifiers: NodeIdentifiers::from_fields(
- identifier_field(AX_IDENTIFIER),
- identifier_field(AX_DOM_IDENTIFIER),
- ),
+ identifiers,
metrics: crate::tree::node_attribute_metrics::NodeAttributeMetrics {
batch_reads,
requested_count,
@@ -300,8 +304,6 @@ mod imp {
deadline: std::time::Instant,
usage: &mut crate::tree::observation_usage::ObservationUsage,
) -> Result<Option<crate::tree::bounded_string::BoundedString>, i32> {
- crate::tree::locator_deadline::prepare(element, deadline)
- .map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
let title = crate::tree::attributes::copy_string_attr_bounded_result(
element,
kAXTitleAttribute,
@@ -311,13 +313,16 @@ mod imp {
if let Some(title) = title.filter(|value| !value.value.trim().is_empty()) {
return Ok(Some(title));
}
- let role = read_unbounded_identity(element, kAXRoleAttribute, deadline)?;
- let subrole = read_unbounded_identity(element, kAXSubroleAttribute, deadline)?;
+ let role =
+ crate::tree::attributes::copy_string_attr_result(element, kAXRoleAttribute, deadline)?;
+ let subrole = crate::tree::attributes::copy_string_attr_result(
+ element,
+ kAXSubroleAttribute,
+ deadline,
+ )?;
let safe_static_text = role.as_deref() == Some("AXStaticText")
&& subrole.as_deref() != Some("AXSecureTextField");
if safe_static_text {
- crate::tree::locator_deadline::prepare(element, deadline)
- .map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
if let Some(value) =
crate::tree::attributes::copy_value_typed_bounded_result(element, deadline, usage)?
.filter(|value| !value.value.trim().is_empty())
@@ -325,8 +330,6 @@ mod imp {
return Ok(Some(value));
}
}
- crate::tree::locator_deadline::prepare(element, deadline)
- .map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
crate::tree::attributes::copy_string_attr_bounded_result(
element,
kAXDescriptionAttribute,
@@ -334,16 +337,6 @@ mod imp {
usage,
)
}
-
- fn read_unbounded_identity(
- element: &AXElement,
- attribute: &str,
- deadline: std::time::Instant,
- ) -> Result<Option<String>, i32> {
- crate::tree::locator_deadline::prepare(element, deadline)
- .map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
- crate::tree::attributes::copy_string_attr_result(element, attribute, deadline)
- }
}
#[cfg(not(target_os = "macos"))]
diff --git a/crates/macos/src/tree/query/child_read.rs b/crates/macos/src/tree/query/child_read.rs
index bb6cde235..fb5bed197 100644
--- a/crates/macos/src/tree/query/child_read.rs
+++ b/crates/macos/src/tree/query/child_read.rs
@@ -52,6 +52,30 @@ impl ChildRead {
}
}
+ fn indexed(
+ mut elements: Vec<AXElement>,
+ initial_count: usize,
+ index: usize,
+ final_count: Result<usize, i32>,
+ mut status: ChildReadStatus,
+ ) -> Self {
+ let Ok(final_count) = final_count else {
+ return Self::failed(status);
+ };
+ status.count_changed |= initial_count != final_count;
+ let expected = usize::from(index < initial_count);
+ let complete = !status.count_changed && elements.len() == expected;
+ elements.truncate(expected);
+ Self {
+ elements,
+ total_count: final_count,
+ complete,
+ source_availability: ChildSourceAvailability::Available,
+ prefix_certain: complete,
+ status,
+ }
+ }
+
pub(crate) fn truncated(&self) -> bool {
self.elements.len() < self.total_count
}
@@ -103,7 +127,7 @@ mod imp {
let count_deadline =
super::super::child_read_budget::count_deadline(max_elements, deadline);
let mut status = ChildReadStatus::default();
- if prepare(element, deadline, &mut status).is_err() {
+ if check_deadline(deadline, &mut status).is_err() {
return ChildRead::failed(status);
}
status.attempts += 1;
@@ -136,7 +160,7 @@ mod imp {
count
}
};
- if count_changed(count, final_count) {
+ if count != final_count {
status.count_changed = true;
complete = false;
elements.truncate(final_count);
@@ -158,7 +182,7 @@ mod imp {
deadline: std::time::Instant,
) -> ChildRead {
let mut status = ChildReadStatus::default();
- if prepare(element, deadline, &mut status).is_err() {
+ if check_deadline(deadline, &mut status).is_err() {
return ChildRead::failed(status);
}
status.attempts += 1;
@@ -170,7 +194,7 @@ mod imp {
return ChildRead::failed(status);
}
};
- let mut elements = if index < initial_count {
+ let elements = if index < initial_count {
status.attempts += 1;
match copy_page(element, attribute, index, 1, deadline) {
Ok(elements) => elements,
@@ -191,56 +215,41 @@ mod imp {
if index < initial_count && elements.is_empty() {
status.cursor_stalled = true;
}
- let final_count = match stable_count(element, attribute, deadline, &mut status) {
- Ok(count) => count,
- Err(error) => {
- telemetry::record(
- &mut status,
- attribute,
- "stable_count",
- error,
- Some(initial_count),
- );
- initial_count
- }
- };
- if count_changed(initial_count, final_count) {
- status.count_changed = true;
- }
- let expected = usize::from(index < initial_count);
- let complete = status.health.deadline_exhausted == 0
- && status.health.cannot_complete == 0
- && !status.invalid_element
- && !status.api_disabled
- && !status.count_changed
- && elements.len() == expected;
- elements.truncate(expected);
- ChildRead {
- elements,
- total_count: final_count,
- complete,
- source_availability: ChildSourceAvailability::Available,
- prefix_certain: complete,
- status,
+ let final_count = stable_count(element, attribute, deadline, &mut status);
+ if let Err(error) = final_count {
+ telemetry::record(
+ &mut status,
+ attribute,
+ "stable_count",
+ error,
+ Some(initial_count),
+ );
}
+ ChildRead::indexed(elements, initial_count, index, final_count, status)
}
/// A responder can serve the values of an attribute while failing to answer
/// its count inside the count budget — Xcode does this for `AXWindows`. The
/// count is only an optimisation, so a short read still proves the elements
/// it returned; only a full page leaves the tail unknown.
- fn read_without_count(
+ pub(super) fn read_without_count(
element: &AXElement,
attribute: &str,
max_elements: usize,
deadline: std::time::Instant,
mut status: ChildReadStatus,
) -> ChildRead {
- let Ok(elements) = read_prefix(element, attribute, max_elements, deadline, &mut status)
- else {
+ if max_elements == 0 {
return ChildRead::failed(status);
+ }
+ let elements = match read_prefix(element, attribute, max_elements, deadline, &mut status) {
+ Ok(elements) => elements,
+ Err(error) => {
+ telemetry::record(&mut status, attribute, "prefix", error, None);
+ return ChildRead::failed(status);
+ }
};
- let saturated = max_elements > 0 && elements.len() == max_elements;
+ let saturated = elements.len() == max_elements;
ChildRead {
total_count: elements.len() + usize::from(saturated),
elements,
@@ -272,7 +281,7 @@ mod imp {
status: &mut ChildReadStatus,
) -> Result<Vec<AXElement>, i32> {
let result = read_paged_prefix(requested, CHILD_PAGE_SIZE, |index, page_len| {
- prepare(element, deadline, status)
+ check_deadline(deadline, status)
.map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
status.attempts += 1;
copy_page(element, attribute, index, page_len, deadline)
@@ -287,8 +296,7 @@ mod imp {
deadline: std::time::Instant,
status: &mut ChildReadStatus,
) -> Result<usize, i32> {
- prepare(element, deadline, status)
- .map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
+ check_deadline(deadline, status).map_err(|_| accessibility_sys::kAXErrorCannotComplete)?;
status.attempts += 1;
child_count(element, attribute, deadline)
}
@@ -333,30 +341,20 @@ mod imp {
Ok(elements)
}
- fn prepare(
- element: &AXElement,
+ fn check_deadline(
deadline: std::time::Instant,
status: &mut ChildReadStatus,
) -> Result<(), ()> {
- crate::tree::locator_deadline::prepare(element, deadline)
+ crate::tree::locator_deadline::remaining(deadline)
.map(|_| ())
.map_err(|_| {
status.health.deadline_exhausted = 1;
})
}
- #[cfg(test)]
- pub(super) fn record_error(status: &mut ChildReadStatus, error: i32) {
- telemetry::record_status(status, error);
- }
-
pub(super) fn is_absent_error(error: i32) -> bool {
error == kAXErrorAttributeUnsupported || error == kAXErrorNoValue
}
-
- pub(super) fn count_changed(initial: usize, final_count: usize) -> bool {
- initial != final_count
- }
}
#[cfg(not(target_os = "macos"))]
diff --git a/crates/macos/src/tree/query/child_read_tests.rs b/crates/macos/src/tree/query/child_read_tests.rs
index b544ecde4..2b0613b90 100644
--- a/crates/macos/src/tree/query/child_read_tests.rs
+++ b/crates/macos/src/tree/query/child_read_tests.rs
@@ -1,9 +1,40 @@
-use super::imp::{count_changed, is_absent_error, record_error};
+use super::super::child_read_telemetry::record_status as record_error;
+use super::imp::{is_absent_error, read_without_count};
use super::*;
use accessibility_sys::{
kAXErrorAttributeUnsupported, kAXErrorCannotComplete, kAXErrorFailure, kAXErrorNoValue,
};
+#[test]
+fn child_reads_distinguish_expired_deadlines_from_invalid_elements() {
+ let element = AXElement(std::ptr::null_mut());
+ let expired = read_attribute_children(&element, "AXChildren", 1, std::time::Instant::now());
+
+ assert!(!expired.complete);
+ assert_eq!(expired.status.health.deadline_exhausted, 1);
+ assert_eq!(expired.status.attempts, 0);
+ assert!(!expired.status.invalid_element);
+
+ for max_elements in [0, 1] {
+ let invalid = read_attribute_children(
+ &element,
+ "AXChildren",
+ max_elements,
+ std::time::Instant::now() + std::time::Duration::from_secs(1),
+ );
+
+ assert!(!invalid.complete);
+ assert!(!invalid.prefix_certain);
+ assert_eq!(
+ invalid.source_availability,
+ ChildSourceAvailability::Unknown
+ );
+ assert!(invalid.status.invalid_element);
+ assert_eq!(invalid.status.health.deadline_exhausted, 0);
+ assert_eq!(invalid.status.attempts, 1 + max_elements as u64);
+ }
+}
+
#[test]
fn unsupported_and_missing_child_attributes_are_authoritatively_absent() {
assert!(is_absent_error(kAXErrorAttributeUnsupported));
@@ -27,10 +58,38 @@ fn bounded_child_read_distinguishes_truncation_from_native_failure() {
}
#[test]
-fn child_count_change_is_not_a_complete_observation() {
- assert!(count_changed(4, 3));
- assert!(count_changed(3, 4));
- assert!(!count_changed(4, 4));
+fn indexed_child_requires_a_successful_unchanged_final_count() {
+ for final_count in [
+ Ok(1),
+ Ok(0),
+ Ok(2),
+ Err(kAXErrorFailure),
+ Err(kAXErrorNoValue),
+ Err(kAXErrorAttributeUnsupported),
+ Err(kAXErrorCannotComplete),
+ Err(i32::MIN),
+ ] {
+ let mut status = ChildReadStatus {
+ attempts: 3,
+ ..Default::default()
+ };
+ if let Err(error) = final_count {
+ record_error(&mut status, error);
+ }
+ let read = ChildRead::indexed(
+ vec![AXElement(std::ptr::null_mut())],
+ 1,
+ 0,
+ final_count,
+ status,
+ );
+ assert_eq!(read.complete, final_count == Ok(1));
+ assert_eq!(read.prefix_certain, read.complete);
+ assert_eq!(read.status.attempts, 3);
+ if final_count == Err(kAXErrorFailure) {
+ assert_eq!(read.status.health.native_read_failures, 1);
+ }
+ }
}
#[test]
@@ -51,14 +110,13 @@ fn cursor_stall_is_preserved_when_statuses_merge() {
#[test]
fn indexed_child_read_is_not_rejected_for_unread_siblings() {
- let read = ChildRead {
- elements: vec![AXElement(std::ptr::null_mut())],
- total_count: 10_000,
- complete: true,
- source_availability: ChildSourceAvailability::Available,
- prefix_certain: true,
- status: ChildReadStatus::default(),
- };
+ let read = ChildRead::indexed(
+ vec![AXElement(std::ptr::null_mut())],
+ 10_000,
+ 3,
+ Ok(10_000),
+ ChildReadStatus::default(),
+ );
assert!(read.complete);
assert!(read.truncated());
@@ -142,3 +200,25 @@ fn ax_failure_remains_a_native_read_failure() {
assert_eq!(status.health.native_read_failures, 1);
assert_eq!(status.health.cannot_complete, 0);
}
+
+#[test]
+fn count_fallback_preserves_a_terminal_prefix_failure() {
+ let mut status = ChildReadStatus {
+ attempts: 1,
+ ..Default::default()
+ };
+ record_error(&mut status, kAXErrorCannotComplete);
+ let read = read_without_count(
+ &AXElement(std::ptr::null_mut()),
+ "AXChildren",
+ 1,
+ std::time::Instant::now() + std::time::Duration::from_secs(1),
+ status,
+ );
+
+ assert!(read.status.invalid_element);
+ assert_eq!(read.status.health.cannot_complete, 1);
+ assert_eq!(read.status.attempts, 2);
+ assert!(!read.complete);
+ assert!(!read.prefix_certain);
+}
diff --git a/crates/macos/src/tree/query/node_evidence.rs b/crates/macos/src/tree/query/node_evidence.rs
index fdeae169f..104a1e2ef 100644
--- a/crates/macos/src/tree/query/node_evidence.rs
+++ b/crates/macos/src/tree/query/node_evidence.rs
@@ -1,6 +1,5 @@
use agent_desktop_core::{
- EvidenceRequirements, IdentifierEvidence, LocatorEvidence, LocatorField, LocatorRefEvidence,
- LocatorStats,
+ IdentifierEvidence, LocatorEvidence, LocatorField, LocatorRefEvidence, LocatorStats,
};
fn is_wrapper_candidate(
@@ -118,21 +117,6 @@ pub(crate) fn identifiers(
IdentifierEvidence::typed(values, preferred, complete)
}
-pub(crate) fn required_complete(
- evidence: &LocatorEvidence,
- requirements: EvidenceRequirements,
-) -> bool {
- (!requirements.role || !evidence.role.is_unknown())
- && (!requirements.name || !evidence.name.is_unknown())
- && (!requirements.description || !evidence.description.is_unknown())
- && (!requirements.value || !evidence.value.is_unknown())
- && (!requirements.identifiers || evidence.identifiers.is_complete())
- && (!requirements.states || !evidence.states.is_unknown())
- && (!requirements.ref_evidence.bounds || !evidence.ref_evidence.bounds.is_unknown())
- && (!requirements.ref_evidence.actions
- || !evidence.ref_evidence.available_actions.is_unknown())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/macos/src/tree/query/node_read.rs b/crates/macos/src/tree/query/node_read.rs
index 98f058b64..bcdc50440 100644
--- a/crates/macos/src/tree/query/node_read.rs
+++ b/crates/macos/src/tree/query/node_read.rs
@@ -5,7 +5,7 @@ use serde_json::json;
use crate::tree::query::evidence_fields::{description_field, name_field};
use crate::tree::query::node_evidence::{
- identifiers as identifier_evidence, is_transparent_wrapper, option_field, required_complete,
+ identifiers as identifier_evidence, is_transparent_wrapper, option_field,
unknown as unknown_evidence, update_identifier_stats,
};
use crate::tree::query::node_read_context::NodeReadContext;
@@ -17,7 +17,6 @@ pub(crate) struct NodeRead {
pub(crate) web_wrapper: bool,
pub(crate) invalid_element: bool,
pub(crate) child_read: ChildRead,
- pub(crate) evidence_complete: bool,
}
pub(crate) fn read_node(
@@ -32,7 +31,7 @@ pub(crate) fn read_node(
deadline,
child_plan,
} = context;
- crate::tree::locator_deadline::prepare(element, deadline)?;
+ crate::tree::locator_deadline::remaining(deadline)?;
let read = crate::tree::element::fetch_node_attrs_with_status_for(
element,
requirements,
@@ -55,7 +54,6 @@ pub(crate) fn read_node(
web_wrapper: false,
invalid_element: true,
child_read: ChildRead::empty(false),
- evidence_complete: false,
});
}
let attrs = read.attrs;
@@ -68,16 +66,15 @@ pub(crate) fn read_node(
let secure = attrs.role.as_deref() == Some("AXSecureTextField")
|| attrs.subrole.as_deref() == Some("AXSecureTextField");
let value = (!secure).then(|| attrs.value.clone()).flatten();
- let actions = if let Some(actions) =
- read_native_actions_if(requirements.ref_evidence.actions, || {
- crate::tree::action_list::read_platform_available_actions(
- element,
- &role,
- attrs.has_scrollbars,
- deadline,
- usage,
- )
- }) {
+ let actions = if let Some(actions) = requirements.ref_evidence.actions.then(|| {
+ crate::tree::action_list::read_platform_available_actions(
+ element,
+ &role,
+ attrs.has_scrollbars,
+ deadline,
+ usage,
+ )
+ }) {
stats.reads.counts.action_reads += 1;
stats.reads.health.cannot_complete += u64::from(actions.cannot_complete);
stats.reads.health.deadline_exhausted += u64::from(actions.deadline_exhausted);
@@ -92,7 +89,6 @@ pub(crate) fn read_node(
web_wrapper: false,
invalid_element: true,
child_read: ChildRead::empty(false),
- evidence_complete: false,
});
}
if actions.complete && !actions.deadline_exhausted && !read.status.scrollbars_unknown() {
@@ -133,7 +129,6 @@ pub(crate) fn read_node(
web_wrapper: false,
invalid_element: true,
child_read: ChildRead::empty(false),
- evidence_complete: false,
});
}
let (name_evidence, child_label_complete) = if requirements.name || requirements.description {
@@ -216,23 +211,15 @@ pub(crate) fn read_node(
available_actions: actions,
},
};
- let evidence_complete = required_complete(&evidence, requirements)
- && !read.metrics.deadline_exhausted
- && child_read.status.health.deadline_exhausted == 0;
Ok(NodeRead {
attrs,
evidence,
web_wrapper,
invalid_element: false,
child_read,
- evidence_complete,
})
}
-fn read_native_actions_if<T>(include_actions: bool, reader: impl FnOnce() -> T) -> Option<T> {
- include_actions.then(reader)
-}
-
fn permission_error(phase: &str) -> AdapterError {
AdapterError::new(
ErrorCode::PermDenied,
@@ -300,14 +287,4 @@ mod tests {
LocatorField::Known("Save".into())
);
}
-
- #[test]
- fn omitted_ref_evidence_performs_zero_native_action_reads() {
- let calls = std::cell::Cell::new(0);
-
- let read = read_native_actions_if(false, || calls.set(calls.get() + 1));
-
- assert!(read.is_none());
- assert_eq!(calls.get(), 0);
- }
}
diff --git a/crates/macos/src/tree/query/traversal.rs b/crates/macos/src/tree/query/traversal.rs
index 0d0a67460..b8fa9cfce 100644
--- a/crates/macos/src/tree/query/traversal.rs
+++ b/crates/macos/src/tree/query/traversal.rs
@@ -156,7 +156,6 @@ impl LocatorTraversal {
};
self.arena.ancestors.remove(&pointer);
self.arena.drop_handles(1);
- let subtree_complete = structural_completeness(subtree_complete, read.evidence_complete);
if !subtree_complete {
self.arena.mark_incomplete();
}
@@ -245,10 +244,6 @@ fn retained_edge_certainty(prefix_certain: &mut bool, retained: bool) -> bool {
edge_certain
}
-fn structural_completeness(topology_complete: bool, _evidence_complete: bool) -> bool {
- topology_complete
-}
-
#[cfg(test)]
mod tests {
use super::retained_edge_certainty;
@@ -267,10 +262,4 @@ mod tests {
assert!(retained_edge_certainty(&mut prefix_certain, false));
assert!(!retained_edge_certainty(&mut prefix_certain, true));
}
-
- #[test]
- fn unknown_semantic_evidence_does_not_poison_complete_topology() {
- assert!(super::structural_completeness(true, false));
- assert!(!super::structural_completeness(false, true));
- }
}
diff --git a/crates/macos/src/tree/readonly.rs b/crates/macos/src/tree/readonly.rs
index 0882aea08..6159b183a 100644
--- a/crates/macos/src/tree/readonly.rs
+++ b/crates/macos/src/tree/readonly.rs
@@ -19,7 +19,7 @@ pub(crate) fn read_readonly(
deadline_exhausted: false,
};
}
- if super::locator_deadline::prepare(element, deadline).is_err() {
+ if super::locator_deadline::remaining(deadline).is_err() {
return ReadonlyRead {
value: None,
error: None,
diff --git a/crates/macos/src/tree/resolve_roots.rs b/crates/macos/src/tree/resolve_roots.rs
index c6dcf83bc..76ab8d108 100644
--- a/crates/macos/src/tree/resolve_roots.rs
+++ b/crates/macos/src/tree/resolve_roots.rs
@@ -2,7 +2,7 @@ use agent_desktop_core::{AdapterError, RefEntry, SnapshotSurface};
use super::AXElement;
use super::element::element_for_pid;
-use super::element_dedupe::ElementDedupe;
+use super::element_dedupe::push_unique;
use super::resolve_read_context::ResolveReadContext;
#[cfg(target_os = "macos")]
@@ -33,30 +33,25 @@ pub(super) fn candidate_roots(
}
let mut roots = Vec::new();
- let mut dedupe = ElementDedupe;
let windows = read_root_array(&application, "AXWindows", context)?;
if windows.as_ref().is_some_and(|windows| !windows.is_empty()) {
- add_array(&mut roots, &mut dedupe, windows);
+ add_array(&mut roots, windows);
} else {
add_optional_element(
&mut roots,
- &mut dedupe,
super::resolve_ax_read::read_element(&application, "AXFocusedWindow", deadline)?,
);
add_optional_element(
&mut roots,
- &mut dedupe,
super::resolve_ax_read::read_element(&application, "AXMainWindow", deadline)?,
);
}
add_array(
&mut roots,
- &mut dedupe,
read_root_array(&application, "AXMenus", context)?,
);
add_array(
&mut roots,
- &mut dedupe,
read_root_array(&application, "AXChildren", context)?,
);
crate::tree::locator_deadline::remaining(deadline)?;
@@ -303,24 +298,16 @@ fn verify_source_application(
}
#[cfg(target_os = "macos")]
-fn add_optional_element(
- roots: &mut Vec<AXElement>,
- dedupe: &mut ElementDedupe,
- element: Option<AXElement>,
-) {
+fn add_optional_element(roots: &mut Vec<AXElement>, element: Option<AXElement>) {
if let Some(element) = element {
- dedupe.push(roots, element);
+ push_unique(roots, element);
}
}
#[cfg(target_os = "macos")]
-fn add_array(
- roots: &mut Vec<AXElement>,
- dedupe: &mut ElementDedupe,
- elements: Option<Vec<AXElement>>,
-) {
+fn add_array(roots: &mut Vec<AXElement>, elements: Option<Vec<AXElement>>) {
for element in elements.unwrap_or_default() {
- dedupe.push(roots, element);
+ push_unique(roots, element);
}
}
diff --git a/crates/macos/src/tree/resolve_search.rs b/crates/macos/src/tree/resolve_search.rs
index b29ee275d..893be96d0 100644
--- a/crates/macos/src/tree/resolve_search.rs
+++ b/crates/macos/src/tree/resolve_search.rs
@@ -5,7 +5,7 @@ use agent_desktop_core::{
use rustc_hash::FxHashSet;
use super::AXElement;
-use super::element_dedupe::ElementDedupe;
+use super::element_dedupe::push_unique;
use super::resolve_classify::classify_candidates;
pub(super) use super::resolve_errors::incomplete_traversal as incomplete_traversal_error;
use super::resolve_errors::{
@@ -23,7 +23,6 @@ pub(super) fn find_entry_by_path(
) -> Result<NativeHandle, AdapterError> {
crate::tree::locator_deadline::remaining(read_context.deadline)?;
let mut matches = Vec::new();
- let mut dedupe = ElementDedupe;
let mut incomplete = None;
for root in roots {
crate::tree::locator_deadline::remaining(read_context.deadline)?;
@@ -33,7 +32,7 @@ pub(super) fn find_entry_by_path(
let identity = candidate_identity(&candidate, entry, read_context)?;
match identity {
IdentityMatch::Match => {
- dedupe.push(&mut matches, candidate);
+ push_unique(&mut matches, candidate);
}
IdentityMatch::Unknown => {
incomplete.get_or_insert_with(|| identity_unknown_error(entry));
@@ -135,7 +134,6 @@ pub(super) fn find_entry_in_roots(
read_context: &mut ResolveReadContext,
) -> Result<NativeHandle, AdapterError> {
let mut matches = Vec::new();
- let mut seen_matches = ElementDedupe;
let mut incomplete = None;
let mut identifier_role_reuse = false;
for root in roots {
@@ -147,7 +145,6 @@ pub(super) fn find_entry_in_roots(
entry,
max_depth: resolve_depth,
ancestors: &mut ancestors,
- seen_matches: &mut seen_matches,
matches: &mut matches,
incomplete: &mut incomplete,
identifier_role_reuse: &mut identifier_role_reuse,
@@ -182,7 +179,6 @@ struct CollectContext<'a> {
entry: &'a RefEntry,
max_depth: u8,
ancestors: &'a mut FxHashSet<usize>,
- seen_matches: &'a mut ElementDedupe,
matches: &'a mut Vec<AXElement>,
incomplete: &'a mut Option<AdapterError>,
identifier_role_reuse: &'a mut bool,
@@ -227,11 +223,11 @@ fn collect_elements_recursive(
if role == &context.entry.identity.role {
match match_native_or_text_identity(context.entry, &read.evidence) {
IdentityMatch::Match => {
- context.seen_matches.push_clone(context.matches, element);
+ push_unique(context.matches, element.clone());
}
IdentityMatch::Unknown => {
if provisional_geometry_candidate(context.entry) {
- context.seen_matches.push_clone(context.matches, element);
+ push_unique(context.matches, element.clone());
} else {
mark_incomplete(context, identity_unknown_error(context.entry));
}
diff --git a/docs/plans/2026-09-05-001-feat-multi-agent-cursors-plan.md b/docs/plans/2026-09-05-001-feat-multi-agent-cursors-plan.md
new file mode 100644
index 000000000..5688ec122
--- /dev/null
+++ b/docs/plans/2026-09-05-001-feat-multi-agent-cursors-plan.md
@@ -0,0 +1,191 @@
+---
+title: Multi-agent cursors - Plan
+type: feat
+date: 2026-09-05
+artifact_contract: ce-unified-plan/v1
+artifact_readiness: implementation-ready
+product_contract_source: ce-plan-bootstrap
+execution: code
+---
+
+# Multi-agent cursors - Plan
+
+## Goal Capsule
+
+Give each named agent its own macOS cursor while agents share one session and its snapshots.
+Preserve the shipped cursor renderer and keep the change limited to identity, configuration, and lifecycle routing.
+The user authorizes implementation, inexpensive sub-agents, review, and the LFG shipping tail through an open PR; merging is excluded.
+Work from the committed baseline in an isolated worktree because the original checkout contains unrelated edits.
+Stop for an invalidated product constraint or unverifiable safety-critical behavior; ordinary implementation details remain executor decisions.
+
+---
+
+## Product Contract
+
+### Summary and problem
+
+The existing overlay has one persistent native child and one animation state per session.
+Multiple agents therefore address the same cursor.
+Named participants need independent visible cursors without changing shared observation or input coordination.
+
+### Requirements
+
+- R1. Three distinct agent names in an enabled session produce three independently positioned cursors after their first presentation.
+- R2. Agent identity persists across CLI invocations through global `--agent-id` or `AGENT_DESKTOP_AGENT_ID`, with the explicit flag taking precedence.
+- R3. Session cursor enablement automatically applies to named agents without registration; explicit multi-agent sessions require an agent ID for desktop actions, while ordinary sessions retain the default cursor.
+- R4. Existing cursor styling and label options can configure a named agent without changing its peers or the session defaults.
+- R5. Motion, fade, rest, description bubble, ripple, highlight, arrival acknowledgement, and reduced-motion behavior reuse the existing renderer.
+- R6. Session-wide disable and session end stop every cursor in that session, including agents that never saved a custom profile.
+- R7. Agent selection does not alter session IDs, snapshot/ref lookup, tracing schemas, interaction locks, delivery semantics, or the public C ABI.
+- R8. Only macOS renders the additional cursors; other platform behavior remains unchanged.
+
+### Scope and flows
+
+A coordinator starts a session with `session start --cursor --multi-agent` and supplies the same session ID plus distinct agent names to its workers.
+Each worker inherits the session style automatically; `cursor-overlay enable` with its agent name is optional and only saves a custom style.
+The first verified action destination creates that agent's renderer lazily; later invocations reconnect to it.
+Repeated use of the same name intentionally addresses the same cursor.
+Multi-agent setup creates no default cursor.
+Ordinary single-agent sessions keep the current greeting and unnamed cursor behavior.
+
+Outside scope: launching agents, task scheduling, changing shared input serialization, new animation/design work, screenshot policy changes, and new platform implementations.
+
+---
+
+## Planning Contract
+
+### Key technical decisions
+
+- KTD1. Reuse the existing native drawing and animation code unchanged (session-settled: user-directed — chosen over redesigning animations: the user requires preservation of the current visuals). Covers R5.
+- KTD2. Use one existing renderer process per session/agent pair. Native bridge globals and the synchronous animation loop in `crates/macos/src/system/cursor_overlay/child.rs` make process isolation much smaller than multiplexing AppKit state. Covers R1, R5.
+- KTD3. Keep a validated optional agent ID in command context, independent of session scope. Preserve it when batch items change sessions and reload the destination session's profile. Missing identity selects the existing default route. Covers R2, R7.
+- KTD4. Store optional complete `CursorOverlayConfig` profiles in `sessions/<session>/cursor-overlays/<agent>.json` using existing bounded private-file helpers. Session enablement remains the master gate. Missing profiles inherit session defaults; malformed profiles fail closed with a clear error. Named configuration requires an active cursor-enabled session. Covers R3, R4.
+- KTD5. `cursor-overlay disable` remains session-wide even when an agent selector is inherited. Hide/Show with an agent ID target only that agent for explicit visibility controls; controls without an ID retain session-wide scope. Enable/Present/Hide/Show carry optional agent identity; legacy JSON remains valid. Covers R6, R7.
+- KTD6. Discover live named sockets by a session-specific filename prefix, not profile files or a participant registry. Reuse the startup lock to serialize spawn against session-wide lifecycle controls. Before spawning, recheck session enablement so stale contexts cannot resurrect disabled cursors. Use a four-second aggregate lifecycle deadline and bounded socket reads/writes; report timeout rather than silently claiming teardown. On startup failure terminate and confirm child exit before releasing the startup lock; refuse replacement when exit cannot be confirmed. Covers R6.
+- KTD7. Named children periodically check their session manifest and stop after disable, end, or manifest removal, including GC and core callers that bypass CLI teardown. Check at a coarse interval, not per animation frame. Keep native rendering math and timing unchanged. Covers R6.
+- KTD8. Add an optional `multi_agent` boolean to the existing session cursor configuration, set by `session start --cursor --multi-agent` or unqualified `cursor-overlay enable --multi-agent`. This mode suppresses bootstrap/default rendering and rejects desktop action commands without `--agent-id` before dispatch; administrative commands remain usable without an ID. Named profiles cannot alter this master setting. Ordinary sessions retain default-route behavior. Covers R1, R3.
+
+### High-level design
+
+```mermaid
+flowchart TB
+ A[CLI agent name] --> C[Command context]
+ S[Shared session and optional agent profile] --> C
+ C --> R[Existing strict ref action and input lease]
+ R --> T[Overlay control with session and agent]
+ T --> P[Socket for that session and agent]
+ P --> N[Unchanged native renderer process]
+ S --> O[Shared snapshots and refs]
+```
+
+```mermaid
+stateDiagram-v2
+ [*] --> Absent
+ Absent --> Visible: enabled session and first presentation
+ Visible --> Resting: existing idle timeout
+ Resting --> Visible: next presentation
+ Visible --> Hidden: session hide
+ Hidden --> Visible: session show
+ Visible --> Stopped: disable or session ends
+ Resting --> Stopped: disable or session ends
+ Hidden --> Stopped: disable or session ends
+ Stopped --> [*]
+```
+
+### Assumptions and risks
+
+The caller assigns distinct stable names; the tool cannot infer logical agent identity from short-lived process IDs.
+One process per agent has linear memory cost; measure a three-agent run before accepting this approach.
+Native children must not hold session liveness leases indefinitely, which would prevent session GC.
+Named-socket discovery must cover long state-root paths and must not match another session.
+Concurrent configuration writes use separate agent files; this work does not redesign existing session-manifest write concurrency.
+External research is unnecessary for the chosen approach because it reuses existing renderer, private-file, and socket code without new APIs or dependencies.
+
+---
+
+## Implementation Units
+
+### U1. Agent identity and configuration
+
+**Goal:** Route context and configuration by agent while preserving shared sessions.
+**Requirements:** R2-R4, R7-R8; KTD3-KTD5.
+**Dependencies:** None.
+**Files:** `src/cli/root.rs`, `src/main.rs`, `src/cli_args/session.rs`, `src/cli_args/cursor_overlay_enable.rs`, `src/dispatch/session.rs`, `src/dispatch/mod.rs`, `src/dispatch/cursor_overlay.rs`, `crates/core/src/context.rs`, `crates/core/src/context/options.rs`, `crates/core/src/session/mod.rs`, a focused session cursor-profile module, `crates/core/src/cursor_overlay/config.rs`, `crates/core/src/cursor_overlay/control.rs`, `crates/core/src/cursor_overlay/submit.rs`, `src/cli/contract_tests.rs`, `crates/core/src/context_scope_tests.rs`, `crates/core/src/cursor_overlay/tests.rs`, and focused profile tests.
+**Approach:** Reuse existing ID validation and bounded private-file persistence. Add optional identity to Enable/Present/Hide/Show and route configuration through command context. Split by responsibility only where the 400-line limit requires it.
+**Test scenarios:**
+1. Three names resolve the same session namespace but yield distinct identity-bearing presentation controls.
+2. Explicit agent overrides environment; absent identity preserves legacy controls; empty, oversized, and path-like names fail validation.
+3. A saved custom profile affects only that agent; missing profiles inherit defaults; disabled or ended sessions suppress all profiles.
+4. Multi-agent setup creates no renderer; desktop UI actions without an ID fail before dispatch; lifecycle commands still work without an ID.
+5. Batch session switching retains identity and loads the destination profile; malformed profile data cannot silently activate an overlay.
+**Verification:** Focused core and CLI tests protect these contracts without changing C headers or action semantics.
+
+### U2. Independent macOS renderer lifecycles
+
+**Goal:** Give each agent independent state with session-wide teardown.
+**Requirements:** R1, R5-R8; KTD1-KTD2, KTD5-KTD8.
+**Dependencies:** U1.
+**Files:** `crates/macos/src/system/cursor_overlay/endpoint.rs`, `spawn.rs`, `child.rs`, and focused routing/lifecycle tests in that directory.
+**Approach:** Extend endpoint routing and discovery; reuse the child renderer and startup lock. Validate session and agent on received controls. Preserve old default endpoint compatibility; honor the explicit mode in KTD8 rather than retiring another caller heuristically.
+**Test scenarios:**
+1. Same session/different agents and same agent/different sessions produce distinct sockets, including long state-root fallback.
+2. Concurrent first presentations for one agent create only one renderer; three agents preserve independent destinations and styles.
+3. Session disable/end closes every discovered socket, while another session remains alive; a stale context cannot spawn after disable.
+4. Missing/custom profiles do not affect socket cleanup; malformed or stalled clients have bounded reads and cannot freeze cleanup forever.
+5. Failed startup confirms child exit before replacement; a child that never bound a socket cannot escape cleanup.
+6. Existing motion endpoint, ripple, reduced-motion, and native styling checks remain valid without renderer edits.
+**Verification:** Deterministic transport tests plus a live three-cursor probe establish isolation, visual preservation, and process/socket teardown.
+
+### U3. Usage documentation and integration proof
+
+**Goal:** Make the feature usable by independent agent processes and verify regressions.
+**Requirements:** R1-R8.
+**Dependencies:** U1, U2.
+**Files:** `CONCEPTS.md`, `skills/agent-desktop/references/commands-system.md`, existing CLI help if needed, and a focused native integration probe under `tests/e2e/` or `scripts/` following current conventions.
+**Approach:** Document coordinator setup, per-agent identity/style, shared qualified refs, and session-wide shutdown. Preserve current screenshot policy.
+**Test scenarios:**
+1. Three separate CLI workers share one session, present three styled cursors, then end the session with no surviving renderer.
+2. Unnamed single-agent usage remains valid; headed and headless actions both present the selected agent’s overlay; session disable covers every cursor.
+3. Record three-agent process memory and baseline latency compared with the merge base.
+**Verification:** Run repository gates and review the performance report; state any unavailable live verification explicitly.
+
+---
+
+## Verification Contract
+
+Run focused tests during each unit, then `cargo fmt --all -- --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test --workspace`, and core dependency isolation.
+Run the existing FFI header/contract checks if shared exported Rust changes affect their generation; the committed C ABI must remain identical.
+Run `bash scripts/perf-baseline-compare.sh` and inspect its `report.html`; investigate material latency regressions before shipping.
+Use isolated state roots for native probes and remove only this run's renderer state through supported teardown.
+Record evidence separately for logical routing, live simultaneous cursors, visual behavior, and cleanup.
+
+---
+
+## Definition of Done
+
+U1-U3 meet their scenarios, all required local checks pass, and three named agents have independently verified cursors in one shared session.
+The Objective-C renderer, Rust motion functions, and animation constants remain unchanged; child lifecycle/routing edits are allowed.
+Unrelated original-checkout edits remain untouched.
+No new dependency, registry, scheduler, public C ABI change, or abandoned implementation remains.
+The reviewed change is committed as Lahfir, pushed once local gates pass, and opened as a PR with exact-head CI and review feedback checked; it is not merged.
+
+
+## Implementation verification
+
+Implemented U1–U3 with the existing renderer and motion code unchanged. The CLI and bundled skill document session setup, stable agent IDs, optional profiles, qualified shared refs, and session-wide shutdown. Clipboard and administrative commands remain exempt from the UI-action identity gate.
+
+The local review fixes make named style configuration profile-only, surface uncertain teardown after state persistence, and put long-path sockets in a private per-user directory. Local independent reviewers and a validator completed; the external adversarial review returned no usable result because authentication failed.
+
+Workspace tests, clippy, formatting, Rust file limits, and core dependency isolation passed. The checked-in fixture probe verifies three cursors, profile-free lazy creation, repeated-ID reuse, shared refs, cross-session isolation with the same agent ID, and process/socket cleanup. The full native E2E runner skipped because the desktop was not exclusive.
+
+The 10-round performance comparison against `8e390a4d` measured click p50 -3%, dense snapshot p50 +1%, and get +11 ms in the sample. Three existing renderer processes used approximately 94 MiB RSS in total. No no-agent context I/O or renderer dependencies were added.
+
+### Headed parity follow-up
+
+The user requires the same per-agent presentation in headed mode. Remove automatic headed suppression, present eligible physical pointer commands using the existing renderer, and retain the interaction lease for OS input. Verify named headed ref and raw-coordinate clicks create/reuse their cursors, preserve headless behavior, and update the installed skills and piano prompt.
+
+Verified headed parity: full workspace tests and clippy pass; isolated live headed probe creates three ref-agent cursors plus a raw-click-only cursor and independently observes five clicks. Matching headless probe observes four clicks with three cursors. Both prove cleanup and cross-session isolation. Raw drag presentation covers its endpoints, retaining native physical drag delivery. Presentation remains ordered under the interaction lease, with a shared 900 ms Present budget; failure cleanup retains bounded child reaping.
+
+### Live drag trail
+
+User-directed extension: a bounded, acknowledged drag-start instruction arms the acting agent’s macOS renderer before mouse-down. Its existing idle loop follows the physical pointer and draws the observed path while held; release fades the trail and an explicit completion or cancellation ends tracking. The physical drag reuses CursorMotion, scaled to the requested duration. Global interaction leasing keeps other agents from interleaving physical drags. Existing ripple and Reduce Motion preferences apply; no event tap, per-step IPC, new setting, or public C ABI change.
diff --git a/scripts/check_rust_comments.py b/scripts/check_rust_comments.py
index 82bad585b..060985ec1 100644
--- a/scripts/check_rust_comments.py
+++ b/scripts/check_rust_comments.py
@@ -65,17 +65,9 @@ def forbidden_comments(source):
line = 1
code_on_line = False
while cursor < len(source):
- raw_end = raw_string_end(source, cursor)
- if raw_end is not None:
- segment = source[cursor:raw_end]
- line += segment.count("\n")
- if "\n" in segment:
- code_on_line = bool(segment.rsplit("\n", 1)[-1].strip())
- else:
- code_on_line = True
- cursor = raw_end
- continue
- string_end = quoted_string_end(source, cursor)
+ string_end = raw_string_end(source, cursor)
+ if string_end is None:
+ string_end = quoted_string_end(source, cursor)
if string_end is not None:
segment = source[cursor:string_end]
line += segment.count("\n")
diff --git a/scripts/cursor-multi-agent-probe.py b/scripts/cursor-multi-agent-probe.py
new file mode 100644
index 000000000..ddc18e773
--- /dev/null
+++ b/scripts/cursor-multi-agent-probe.py
@@ -0,0 +1,173 @@
+#!/usr/bin/env python3
+"""Verify three macOS CLI cursors using only the supplied fixture application."""
+import argparse
+import json
+import os
+from pathlib import Path
+import socket
+import subprocess
+import tempfile
+import time
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--bin", required=True, type=Path)
+ parser.add_argument("--fixture", required=True, type=Path)
+ parser.add_argument("--out", required=True, type=Path)
+ parser.add_argument("--headed", action="store_true", help="Exercise physical clicks with agent cursors")
+ args = parser.parse_args()
+ args.out.mkdir(parents=True, exist_ok=True)
+ state_directory = tempfile.TemporaryDirectory(prefix="adc-", dir="/tmp")
+ state = Path(state_directory.name)
+ env = dict(os.environ, AGENT_DESKTOP_HOME=str(state))
+ env.pop("AGENT_DESKTOP_SESSION", None)
+ env.pop("AGENT_DESKTOP_AGENT_ID", None)
+ action_flags = ["--headed"] if args.headed else []
+ lease_fd = env.get("AGENT_DESKTOP_INTERACTION_LEASE_FD")
+ cli_pass_fds = (int(lease_fd),) if lease_fd is not None else ()
+
+ def cli(*command):
+ result = subprocess.run([str(args.bin.resolve()), *command], env=env,
+ capture_output=True, text=True, timeout=15,
+ pass_fds=cli_pass_fds)
+ value = json.loads(result.stdout)
+ assert result.returncode == 0 and value["ok"], value
+ return value["data"]
+
+ fixture = subprocess.Popen([str(args.fixture.resolve())], stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL)
+ session_id = None
+ other_session = None
+ pids = set()
+ try:
+ time.sleep(2)
+ session_id = cli("session", "start", "--cursor", "--multi-agent")["session_id"]
+ env["AGENT_DESKTOP_SESSION"] = session_id
+ assert not list(state.glob("*.sock")), "setup created an unwanted default cursor"
+ snapshot = cli("snapshot", "--app", "AgentDeskFixture", "-i", "--include-bounds")
+ (args.out / "snapshot.json").write_text(json.dumps(snapshot, indent=2))
+
+ def walk(node):
+ if isinstance(node, dict):
+ yield node
+ for value in node.values():
+ yield from walk(value)
+ elif isinstance(node, list):
+ for value in node:
+ yield from walk(value)
+
+ target = next(node["ref_id"] for node in walk(snapshot)
+ if node.get("name") == "primary-button" and node.get("ref_id"))
+ for command in [["click", target], ["batch", json.dumps([
+ {"command": "click", "args": {"ref_id": target}}])]]:
+ result = subprocess.run([str(args.bin.resolve()), *command], env=env,
+ capture_output=True, text=True, timeout=15,
+ pass_fds=cli_pass_fds)
+ error = json.loads(result.stdout)
+ assert error["error"]["code"] == "INVALID_ARGS", error
+ assert "agent-id" in error["error"]["message"], error
+ assert not list(state.glob("*.sock"))
+ sockets = {}
+ previous = set()
+ colors = ["#FF3B7B", "#49C98A", "#FFE080"]
+ for index, color in enumerate(colors):
+ agent = f"worker-{index}"
+ if index < 2:
+ cli("--agent-id", agent, "cursor-overlay", "enable", "--label", agent,
+ "--fill", color, "--accent", color)
+ assert set(state.glob("*.sock")) == previous, "profile created a cursor"
+ cli(*action_flags, "--agent-id", agent, "click", target)
+ paths = set(state.glob("*.sock"))
+ assert len(paths) == index + 1, paths
+ sockets[agent] = (paths - previous).pop()
+ previous = paths
+ before = set(state.glob("*.sock"))
+ cli(*action_flags, "--agent-id", "worker-0", "click", target)
+ assert set(state.glob("*.sock")) == before, "repeat identity created another cursor"
+ if args.headed:
+ target_bounds = cli("get", target, "--property", "bounds")["value"]
+ xy = f"{target_bounds['x'] + target_bounds['width'] / 2},{target_bounds['y'] + target_bounds['height'] / 2}"
+ cli("--headed", "--agent-id", "raw-pointer", "mouse-click", "--xy", xy)
+ raw_socket, = set(state.glob("*.sock")) - before
+ before.add(raw_socket)
+ observed = cli("snapshot", "--app", "AgentDeskFixture")
+ (args.out / "observed.json").write_text(json.dumps(observed, indent=2))
+ click_status = next(node.get("value") for node in walk(observed)
+ if node.get("description") == "click-status")
+ expected_clicks = 5 if args.headed else 4
+ assert click_status == f"click-{expected_clicks}", click_status
+ displays = cli("list-displays")
+ bounds = displays[0]["bounds"]
+ for index, path in enumerate(sorted(before)):
+ pid_output = subprocess.check_output(["lsof", "-t", str(path)], text=True)
+ pids.update(int(pid) for pid in pid_output.split())
+ assert len(pids) == (4 if args.headed else 3), pids
+ memory = subprocess.check_output(["ps", "-o", "pid=,rss=", "-p",
+ ",".join(map(str, sorted(pids)))], text=True)
+ for index, color in enumerate(colors):
+ agent = f"worker-{index}"
+ control = {"action": "present", "session_id": session_id, "agent_id": agent,
+ "style": {"fill": color, "accent": color}, "instruction": {
+ "destination": {"x": bounds["x"] + 200 + index * 260,
+ "y": bounds["y"] + 250},
+ "label": agent, "click": False, "phase": "travel"}}
+ with socket.socket(socket.AF_UNIX) as stream:
+ stream.settimeout(2)
+ stream.connect(str(sockets[agent]))
+ stream.sendall(json.dumps(control).encode())
+ stream.shutdown(socket.SHUT_WR)
+ assert stream.recv(1) == b"\x01"
+ subprocess.run(["screencapture", "-x", str(args.out / "three-cursors.png")], check=True)
+ report = {"session_id": session_id, "cursor_count": len(before), "headed": args.headed,
+ "renderer_pids": sorted(pids), "rss_kib": memory,
+ "shared_ref": target, "state_root": str(state),
+ "profile_free_agent": "worker-2", "verified_click_count": expected_clicks}
+ other_session = cli("session", "start", "--cursor", "--multi-agent")["session_id"]
+ other_snapshot = cli("--session", other_session, "snapshot", "--app", "AgentDeskFixture", "-i")
+ other_target = next(node["ref_id"] for node in walk(other_snapshot)
+ if node.get("name") == "primary-button" and node.get("ref_id"))
+ cli(*action_flags, "--session", other_session, "--agent-id", "worker-0", "click", other_target)
+ other_socket, = set(state.glob("*.sock")) - before
+ other_pid = int(subprocess.check_output(["lsof", "-t", str(other_socket)], text=True).strip())
+ cli("session", "end")
+ def alive(pid):
+ try:
+ os.kill(pid, 0)
+ return True
+ except ProcessLookupError:
+ return False
+
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and (any(path.exists() for path in before) or any(map(alive, pids))):
+ time.sleep(0.05)
+ assert set(state.glob("*.sock")) == {other_socket}, "session end crossed session boundaries"
+ assert not any(map(alive, pids)), "renderer survived session end"
+ cli("--session", other_session, "--agent-id", "worker-0", "cursor-overlay", "disable")
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and (other_socket.exists() or alive(other_pid)):
+ time.sleep(0.05)
+ assert not list(state.glob("*.sock")), "disable left a cursor socket"
+ assert not alive(other_pid), "disable left a renderer"
+ report["cleanup_verified"] = True
+ report["cross_session_isolation"] = True
+ (args.out / "report.json").write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps(report, indent=2))
+ finally:
+ try:
+ if session_id:
+ cli("session", "end")
+ if other_session:
+ cli("session", "end", other_session)
+ finally:
+ fixture.terminate()
+ try:
+ fixture.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ fixture.kill()
+ fixture.wait(timeout=5)
+ state_directory.cleanup()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/perf-baseline-compare.sh b/scripts/perf-baseline-compare.sh
index 8e5c1d9b7..da59d5971 100755
--- a/scripts/perf-baseline-compare.sh
+++ b/scripts/perf-baseline-compare.sh
@@ -5,7 +5,7 @@
# 1. runs a fixture A/B (snapshots, reads, and fixture-only actions),
# 2. runs the deterministic synthetic locator benchmark on HEAD,
# 3. optionally probes real apps READ-ONLY (snapshot/find timing only),
-# and writes a markdown report + raw JSON.
+# and writes an HTML report + raw JSON.
#
# Usage:
# scripts/perf-baseline-compare.sh [--base <ref>] [--apps "Slack,Google Chrome"]
@@ -35,6 +35,7 @@ cd "$repo"
[ -n "$base_ref" ] || base_ref="$(git merge-base HEAD "$(git rev-parse --verify --quiet origin/main >/dev/null 2>&1 && echo origin/main || echo main)")"
base_sha="$(git rev-parse --short "$base_ref")"
head_sha="$(git rev-parse --short HEAD)"
+if ! git diff --quiet HEAD; then head_sha="${head_sha}+working-tree"; fi
[ -n "$out" ] || out="$(mktemp -d "/tmp/agent-desktop-perf-${head_sha}-vs-${base_sha}.XXXXXX")"
mkdir -p "$out"
echo "== perf compare: HEAD ${head_sha} vs base ${base_sha} -> ${out}"
@@ -65,7 +66,6 @@ cleanup_fixture() {
cleanup() {
cleanup_fixture
git worktree remove --force "$wt" >/dev/null 2>&1 || true
- git worktree prune >/dev/null 2>&1 || true
}
trap cleanup EXIT
(cd "$wt" && cargo build --release -p agent-desktop >/dev/null)
diff --git a/scripts/perf_ab_probe.py b/scripts/perf_ab_probe.py
index c0e04dbd5..62c0d2f30 100755
--- a/scripts/perf_ab_probe.py
+++ b/scripts/perf_ab_probe.py
@@ -13,6 +13,7 @@ never collide. Rounds alternate between binaries to cancel machine drift.
"""
import argparse
import json
+import math
import os
import statistics
import subprocess
@@ -55,11 +56,11 @@ def walk(node):
def tree_stats(env):
tree = env.get("data", {}).get("tree", {})
- nodes = sum(1 for _ in walk(tree))
- depth = 0
+ nodes = depth = 0
def measure(node, level):
- nonlocal depth
+ nonlocal nodes, depth
+ nodes += 1
depth = max(depth, level)
for child in node.get("children", []):
measure(child, level + 1)
@@ -107,6 +108,7 @@ def app_cases(app):
("snapshot -i", ["snapshot", "--app", app, "-i"]),
("snapshot skeleton", ["snapshot", "--app", app, "--skeleton"]),
("snapshot d30", ["snapshot", "--app", app, "--max-depth", "30"]),
+ ("find --role button --first", ["find", "--app", app, "--role", "button", "--first"]),
]
@@ -114,9 +116,13 @@ def collect(binaries, cases_for, rounds):
cases = {label: cases_for(label) for label in binaries}
results = {label: {} for label in binaries}
shapes = {label: {} for label in binaries}
- for _ in range(rounds):
- for label, binary in binaries.items():
- for name, args in cases[label]:
+ labels = list(binaries)
+ for round_index in range(rounds):
+ order = labels if round_index % 2 == 0 else labels[::-1]
+ for case_index in range(len(cases[labels[0]])):
+ for label in order:
+ binary = binaries[label]
+ name, args = cases[label][case_index]
elapsed, proc = run(binary, *args)
env = envelope(proc)
ok = bool(env.get("ok"))
@@ -133,33 +139,13 @@ def summarize(results, shapes):
times = sorted(t for t, ok in samples if ok)
report.setdefault(name, {})[label] = {
"p50_ms": round(statistics.median(times), 1) if times else None,
- "p95_ms": round(times[max(0, int(len(times) * 0.95) - 1)], 1) if times else None,
+ "p95_ms": round(times[math.ceil(len(times) * 0.95) - 1], 1) if times else None,
"ok_rate": sum(1 for _, ok in samples if ok) / len(samples),
"shape": shapes[label].get(name),
}
return report
-def head_only_find(binary, app, rounds, report):
- times, matches = [], None
- for _ in range(rounds):
- elapsed, proc = run(binary, "find", "--app", app, "--role", "button", "--first")
- env = envelope(proc)
- if env.get("ok"):
- times.append(elapsed)
- matches = env.get("data", {}).get("match", {}).get("role")
- if times:
- times.sort()
- report["find --role button --first (HEAD-only)"] = {
- "HEAD": {
- "p50_ms": round(statistics.median(times), 1),
- "p95_ms": round(times[max(0, int(len(times) * 0.95) - 1)], 1),
- "ok_rate": len(times) / rounds,
- "matched_role": matches,
- }
- }
-
-
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=["fixture", "app"], required=True)
@@ -176,8 +162,6 @@ def main():
else:
results, shapes = collect(binaries, lambda _label: app_cases(args.app), args.rounds)
report = summarize(results, shapes)
- if args.mode == "app":
- head_only_find(args.head_bin, args.app, args.rounds, report)
payload = {"mode": args.mode, "app": args.app, "rounds": args.rounds, "cases": report}
if args.json_out:
diff --git a/scripts/perf_ab_probe_test.py b/scripts/perf_ab_probe_test.py
new file mode 100644
index 000000000..e10056969
--- /dev/null
+++ b/scripts/perf_ab_probe_test.py
@@ -0,0 +1,49 @@
+"""Run with python3 scripts/perf_ab_probe_test.py."""
+from unittest.mock import patch
+
+import perf_ab_probe as probe
+import perf_report_html as renderer
+
+
+def check_balanced_order_and_percentile():
+ calls = []
+ with patch.object(probe, "run", side_effect=lambda binary, case: (
+ calls.append((binary, case)) or 1, None
+ )), patch.object(probe, "envelope", return_value={"ok": True}):
+ results, shapes = probe.collect(
+ {"HEAD": "new", "BASE": "old"},
+ lambda _: [("first", ["first"]), ("second", ["second"])],
+ 2,
+ )
+ assert calls == [
+ ("new", "first"), ("old", "first"),
+ ("new", "second"), ("old", "second"),
+ ("old", "first"), ("new", "first"),
+ ("old", "second"), ("new", "second"),
+ ]
+ results["HEAD"]["first"] = [(n, True) for n in range(1, 11)] + [(999, False)]
+ summary = probe.summarize(results, shapes)["first"]["HEAD"]
+ assert summary["p50_ms"] == 5.5
+ assert summary["p95_ms"] == 10
+ assert summary["ok_rate"] == 10 / 11
+
+
+def check_report_and_cases():
+ assert probe.app_cases("fixture")[-1][1] == [
+ "find", "--app", "fixture", "--role", "button", "--first"
+ ]
+ assert probe.tree_stats({"data": {"tree": {"children": [{}]}, "ref_count": 1}}) == (2, 2, 1)
+ payload = {"app": "<script>", "cases": {"find": {
+ "HEAD": {"p50_ms": None, "p95_ms": None, "ok_rate": 0},
+ "BASE": {"p50_ms": 2, "p95_ms": 3, "ok_rate": 1},
+ }}}
+ html = renderer.live_report(payload)
+ assert "&lt;script&gt;" in html and "<script>" not in html
+ assert "not comparable" in html and ">0.00<" in html and ">3.00<" in html
+ html = renderer.synthetic_report({"scenarios": [{"legacy_snapshot": {"correct_all_runs": False}}]})
+ assert "FAIL" in html and "not revision A/B" in html and "Refs re-resolvable" in html
+
+
+if __name__ == "__main__":
+ check_balanced_order_and_percentile()
+ check_report_and_cases()
diff --git a/scripts/perf_report_html.py b/scripts/perf_report_html.py
index 89a1c6fda..eab7559d7 100644
--- a/scripts/perf_report_html.py
+++ b/scripts/perf_report_html.py
@@ -1,400 +1,109 @@
#!/usr/bin/env python3
-"""Render perf-baseline-compare JSON artifacts into one self-contained HTML report.
-
-Usage: python3 scripts/perf_report_html.py <out_dir> --head <sha> --base <sha>
-Reads fixture-ab.json, app-*.json, and locator-synthetic.json from <out_dir> (any may
-be absent) and writes <out_dir>/report.html. Stdlib only.
-"""
+"""Render fixture-ab.json, app-*.json and locator-synthetic.json to report.html."""
import argparse
import datetime
-import glob
import json
-import os
-import sys
-
-import perf_report_svg as chart
-from perf_report_svg import esc
-
-CSS = """
-:root {
- --surface:#fcfcfb; --page:#f9f9f7; --ink:#0b0b0b; --secondary:#52514e; --muted:#898781;
- --grid:#e1e0d9; --baseline:#c3c2b7; --border:rgba(11,11,11,0.10);
- --head:#2a78d6; --base:#1baf7a; --good:#006300; --status-good:#0ca30c;
- --good-tint:rgba(0,99,0,0.10); --status-good-tint:rgba(12,163,12,0.12);
- --secondary-tint:rgba(82,81,78,0.09); --head-tint:rgba(42,120,214,0.10);
-}
-@media (prefers-color-scheme:dark) {
- :root {
- --surface:#1a1a19; --page:#0d0d0d; --ink:#ffffff; --secondary:#c3c2b7; --muted:#898781;
- --grid:#2c2c2a; --baseline:#383835; --border:rgba(255,255,255,0.10);
- --head:#3987e5; --base:#199e70; --good:#0ca30c; --status-good:#0ca30c;
- --good-tint:rgba(12,163,12,0.16); --status-good-tint:rgba(12,163,12,0.16);
- --secondary-tint:rgba(195,194,183,0.10); --head-tint:rgba(57,135,229,0.14);
- }
-}
-* { box-sizing:border-box; }
-body { margin:0; background:var(--page); color:var(--ink); line-height:1.5;
- font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; }
-.col { max-width:1040px; margin:0 auto; padding:0 24px 48px; display:flex; flex-direction:column; gap:24px; }
-header.band, footer.band { max-width:1040px; margin:0 auto; padding:32px 24px 8px; }
-footer.band { padding:8px 24px 40px; }
-header.band h1 { font-size:22px; margin:0 0 6px; letter-spacing:-0.01em; }
-header.band .subtitle, footer.band p { color:var(--secondary); font-size:13px; margin:4px 0; }
-footer.band code, .card code { background:var(--secondary-tint); border-radius:4px; padding:1px 6px; font-size:12px; }
-.tiles { max-width:1040px; margin:0 auto; padding:8px 24px 0; display:grid;
- grid-template-columns:repeat(auto-fit,minmax(190px,1fr)); gap:16px; }
-.tile { background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:18px 20px; }
-.tile-label { font-size:12px; color:var(--muted); margin-bottom:8px; }
-.tile-value { font-size:26px; font-weight:600; }
-.tile-delta { font-size:12px; margin-top:6px; }
-.tile-delta.good { color:var(--good); } .tile-delta.secondary { color:var(--secondary); } .tile-delta.muted { color:var(--muted); }
-.card { background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:28px; }
-.card-head { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px; }
-.card h2 { font-size:16px; margin:0; }
-.hint, .shape-line { font-size:12.5px; color:var(--secondary); }
-.hint { margin:6px 0 4px; } .shape-line { margin:12px 0 0; }
-.legend, .legend-item { display:flex; align-items:center; }
-.legend { gap:16px; font-size:12px; color:var(--secondary); } .legend-item { gap:6px; }
-.swatch { width:10px; height:10px; border-radius:2px; display:inline-block; }
-.swatch-head { background:var(--head); } .swatch-base { background:var(--base); }
-.callout { border:1px solid var(--border); background:var(--head-tint); border-radius:10px;
- padding:14px 16px; font-size:13px; color:var(--secondary); margin:16px 0 4px; }
-.callout strong { color:var(--ink); }
-svg.chart { display:block; width:100%; height:auto; margin:16px 0 4px; }
-svg.chart text { font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; }
-.gridline { stroke:var(--grid); stroke-width:1; } .tick { stroke:var(--ink); stroke-width:1.4; opacity:0.45; }
-.parity { stroke:var(--baseline); stroke-width:1.5; stroke-dasharray:3 3; }
-.bar-head { fill:var(--head); } .bar-base { fill:var(--base); }
-.ink { fill:var(--ink); } .secondary { fill:var(--secondary); } .muted { fill:var(--muted); }
-.tabular { font-variant-numeric:tabular-nums; }
-.hit { fill:transparent; cursor:pointer; }
-.value-label { font-weight:600; }
-.chip-good { fill:var(--good-tint); } .chip-secondary, .chip-info { fill:var(--secondary-tint); }
-.chip-status-good { fill:var(--status-good-tint); }
-.chip-text-good { fill:var(--good); } .chip-text-secondary, .chip-text-info { fill:var(--secondary); }
-.chip-text-status-good { fill:var(--status-good); }
-details { margin-top:14px; }
-summary { cursor:pointer; font-size:13px; color:var(--secondary); }
-.table-wrap { overflow-x:auto; }
-table { width:100%; border-collapse:collapse; margin-top:12px; font-size:12.5px; font-variant-numeric:tabular-nums; }
-th, td { text-align:right; padding:7px 10px; border-bottom:1px solid var(--border); white-space:nowrap; }
-th:first-child, td:first-child { text-align:left; }
-th { color:var(--muted); font-weight:500; }
-.tooltip { position:fixed; pointer-events:none; opacity:0; transition:opacity .08s ease; background:var(--ink);
- color:var(--surface); border-radius:8px; padding:8px 10px; font-size:12px; z-index:20; max-width:240px; }
-.tooltip .tt-title { font-weight:600; margin-bottom:4px; }
-.tooltip .tt-row { display:flex; justify-content:space-between; gap:12px; opacity:.85; }
-@media (max-width:640px) { .card { padding:20px; } .tile-value { font-size:22px; } }
-"""
-
-JS = """
-(function () {
- var tip = document.getElementById('tt');
- document.querySelectorAll('[data-tt-title]').forEach(function (el) {
- el.addEventListener('mousemove', function (evt) {
- var rows = (el.getAttribute('data-tt-rows') || '').split('|').filter(Boolean);
- var html = '<div class="tt-title">' + el.getAttribute('data-tt-title') + '</div>';
- rows.forEach(function (row) {
- var i = row.indexOf('=');
- html += '<div class="tt-row"><span>' + row.slice(0, i) + '</span><b>' + row.slice(i + 1) + '</b></div>';
- });
- tip.innerHTML = html;
- tip.style.left = Math.min(evt.clientX + 14, window.innerWidth - 250) + 'px';
- tip.style.top = (evt.clientY + 14) + 'px'; tip.style.opacity = '1';
- });
- el.addEventListener('mouseleave', function () { tip.style.opacity = '0'; });
- });
-})();
-"""
-
-PAGE = """<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8"/>
-<meta name="viewport" content="width=device-width, initial-scale=1"/>
-<title>{title}</title>
-<style>{css}</style>
-</head>
-<body>
-{body}
-<div id="tt" class="tooltip" role="status"></div>
-<script>{js}</script>
-</body>
-</html>
-"""
-
-
-def load(path):
- if not os.path.exists(path):
- return None
- with open(path) as handle:
- return json.load(handle)
-
-
-def fmt_ms(value):
- return f"{value:.1f} ms" if value is not None else "-"
-
-def ok_pct(value):
- return f"{value * 100:.0f}%"
-
-
-def tip_rows(entry):
- return [("p50", fmt_ms(entry["p50_ms"])), ("p95", fmt_ms(entry["p95_ms"])),
- ("ok rate", ok_pct(entry.get("ok_rate", 1.0)))]
-
-
-def build_ab_rows(payload):
- rows = []
- for name, sides in payload.get("cases", {}).items():
- head, base = sides.get("HEAD"), sides.get("BASE")
- if not head or not base or min(head.get("ok_rate", 1.0), base.get("ok_rate", 1.0)) < 1.0:
- continue
- delta_text, delta_cls = chart.fmt_delta(head["p50_ms"], base["p50_ms"])
- rows.append({
- "label": name,
- "head": {"value": head["p50_ms"], "tick": head["p95_ms"],
- "tip_title": f"{name} — HEAD", "tip_rows": tip_rows(head)},
- "base": {"value": base["p50_ms"], "tick": base["p95_ms"],
- "tip_title": f"{name} — BASE", "tip_rows": tip_rows(base)},
- "delta_text": delta_text, "delta_good": delta_cls == "good",
- })
- return rows
-
-
-def build_single_rows(payload):
- rows = []
- for name, sides in payload.get("cases", {}).items():
- head, base = sides.get("HEAD"), sides.get("BASE")
- if not head or base:
- continue
- label = name.replace(" (HEAD-only)", "")
- rows.append({
- "label": label, "value": head["p50_ms"], "tick": head["p95_ms"],
- "tip_title": f"{label} — HEAD", "tip_rows": tip_rows(head),
- "badge_text": "new in HEAD - no baseline equivalent",
- })
- return rows
-
-
-def case_shapes(payload, case_name):
- sides = payload.get("cases", {}).get(case_name, {})
- return (sides.get("HEAD") or {}).get("shape"), (sides.get("BASE") or {}).get("shape")
-
-
-def shape_line(payload):
- head_shape, base_shape = case_shapes(payload, "snapshot d30")
- if not head_shape or not base_shape:
- return None
- hn, hd, hr = head_shape
- bn, bd, br = base_shape
- return f"HEAD d30: {hn} nodes / depth {hd} / {hr} refs — BASE d30: {bn} nodes / depth {bd} / {br} refs"
+import math
+from html import escape
+from pathlib import Path
-def needs_honesty_callout(payload):
- head_shape, base_shape = case_shapes(payload, "snapshot -i")
- if not head_shape or not base_shape:
- return False
- return base_shape[0] > 0 and head_shape[0] < 0.5 * base_shape[0]
+def table(headers, rows):
+ head = ''.join(f'<th scope="col">{escape(str(h))}</th>' for h in headers)
+ body = ''.join('<tr>' + ''.join(f'<td>{escape(str(c))}</td>' for c in row) + '</tr>' for row in rows)
+ return f'<div class="scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'
-def build_speedup_rows(report):
- rows = []
- for sc in report.get("scenarios", []):
- legacy, live, comp = sc["legacy_snapshot"], sc["live_find_selected_refs"], sc["comparison"]
- attr_delta = chart.pct_delta(live["attributes_requested"], legacy["attributes_requested"])
- rows.append({
- "label": sc["name"], "speedup": comp["p50_find_speedup"], "tip_title": sc["name"],
- "tip_rows": [
- ("legacy p50", f'{legacy["p50_us"] / 1000:.2f} ms'), ("live p50", f'{live["p50_us"] / 1000:.2f} ms'),
- ("legacy p95", f'{legacy["p95_us"] / 1000:.2f} ms'), ("live p95", f'{live["p95_us"] / 1000:.2f} ms'),
- ("attrs legacy/live", f'{legacy["attributes_requested"]} / {live["attributes_requested"]}'),
- ],
- "correctness_fix": comp.get("find_correctness_delta", 0) > 0,
- "sub_label": f"{attr_delta:+.0f}% attribute reads" if attr_delta is not None else None,
- })
- return rows
-
-
-def tile(label, value, head, base):
- delta_text, cls = chart.fmt_delta(head, base)
- return {"label": label, "value": value, "delta_text": f"{delta_text} vs base" if delta_text else "n/a", "cls": cls}
-
-
-def build_tiles(fixture, synthetic):
- tiles = []
- if fixture:
- click = fixture.get("cases", {}).get("click", {})
- if click.get("HEAD", {}).get("ok_rate") == click.get("BASE", {}).get("ok_rate") == 1.0:
- h, b = click["HEAD"]["p50_ms"], click["BASE"]["p50_ms"]
- tiles.append(tile("Click p50 (fixture)", fmt_ms(h), h, b))
- d30 = fixture.get("cases", {}).get("snapshot d30", {})
- if d30.get("HEAD", {}).get("ok_rate") == d30.get("BASE", {}).get("ok_rate") == 1.0:
- h, b = d30["HEAD"]["p50_ms"], d30["BASE"]["p50_ms"]
- tiles.append(tile("Snapshot d30 p50 (fixture)", fmt_ms(h), h, b))
- scenarios = (synthetic or {}).get("scenarios") or []
- if scenarios:
- best = max(scenarios, key=lambda s: s["comparison"]["p50_find_speedup"])
- tiles.append({"label": "Best synthetic find speedup", "value": f'{best["comparison"]["p50_find_speedup"]:.1f}x',
- "delta_text": best["name"].replace("_", " "), "cls": "muted"})
- fixes = sum(1 for s in scenarios if s["comparison"].get("find_correctness_delta", 0) > 0)
- tiles.append({"label": "Correctness fixes", "value": f"{fixes} scenario{'' if fixes == 1 else 's'}",
- "delta_text": "legacy path answered incorrectly" if fixes else "no legacy mismatches observed",
- "cls": "good" if fixes else "muted"})
- return tiles
-
+def number(value, scale=1):
+ return f'{value / scale:.2f}' if isinstance(value, (int, float)) and math.isfinite(value) else 'unknown'
-def tiles_html(tiles):
- if not tiles:
- return ""
- cells = "".join(
- f'<div class="tile"><div class="tile-label">{esc(t["label"])}</div>'
- f'<div class="tile-value">{esc(t["value"])}</div>'
- f'<div class="tile-delta {t["cls"]}">{esc(t["delta_text"])}</div></div>'
- for t in tiles
- )
- return f'<div class="tiles">{cells}</div>'
+def outcome(value):
+ return 'PASS' if value is True else 'FAIL' if value is False else 'unknown'
-LEGEND = ('<div class="legend"><span class="legend-item"><span class="swatch swatch-head"></span>HEAD</span>'
- '<span class="legend-item"><span class="swatch swatch-base"></span>BASE</span></div>')
-
-def table_html(headers, rows):
- thead = "".join(f"<th>{esc(h)}</th>" for h in headers)
- trs = "".join("<tr>" + "".join(f"<td>{esc(c)}</td>" for c in r) + "</tr>" for r in rows)
- return f'<div class="table-wrap"><table><thead><tr>{thead}</tr></thead><tbody>{trs}</tbody></table></div>'
-
-
-def case_rows(payload, require_base):
+def live_report(payload):
rows = []
- for name, sides in payload.get("cases", {}).items():
- head, base = sides.get("HEAD"), sides.get("BASE")
- if not head or (require_base and not base):
- continue
- comparable = base and min(head.get("ok_rate", 1.0), base.get("ok_rate", 1.0)) == 1.0
- delta_text = chart.fmt_delta(head["p50_ms"], base["p50_ms"])[0] if comparable else None
- ok = (f'{ok_pct(base.get("ok_rate", 1.0))}/{ok_pct(head.get("ok_rate", 1.0))}' if base
- else f'-/{ok_pct(head.get("ok_rate", 1.0))}')
- rows.append([name, fmt_ms(base["p50_ms"]) if base else "-", fmt_ms(base["p95_ms"]) if base else "-",
- fmt_ms(head["p50_ms"]), fmt_ms(head["p95_ms"]), delta_text or "not comparable", ok])
- return rows
-
-
-def fixture_section(payload):
- if not payload:
- return ""
- rows = build_ab_rows(payload)
- table = table_html(["Case", "BASE p50", "BASE p95", "HEAD p50", "HEAD p95", "Delta", "OK B/H"],
- case_rows(payload, require_base=True))
- return (
- '<section class="card">'
- f'<div class="card-head"><h2>Fixture A/B (live)</h2>{LEGEND if rows else ""}</div>'
- f'<p class="hint">Alternating rounds, isolated per-binary stores, wall-clock per process invocation '
- f'({payload.get("rounds", "?")} rounds).</p>{chart.grouped_bar_chart(rows)}'
- f'<details><summary>Table view</summary>{table}</details></section>'
- )
-
-
-def app_section(payload):
- if not payload:
- return ""
- ab_rows, single_rows = build_ab_rows(payload), build_single_rows(payload)
- if needs_honesty_callout(payload):
- for row in ab_rows:
- if row["label"] == "snapshot -i":
- row["delta_text"], row["delta_good"] = "not comparable", False
- body = [f'<div class="card-head"><h2>{esc(payload["app"])}</h2>{LEGEND if ab_rows else ""}</div>']
- body.append(f'<p class="hint">Read-only observation ({payload.get("rounds", "?")} rounds).</p>')
- if ab_rows:
- body.append(chart.grouped_bar_chart(ab_rows))
- if needs_honesty_callout(payload):
- body.append(
- '<div class="callout"><strong>Reading note.</strong> HEAD&rsquo;s default <code>snapshot -i</code> '
- 'reads a shallower tree than BASE under the progressive-traversal default-depth change, so the '
- '<code>snapshot -i</code> row above is not like-for-like. The <code>snapshot d30</code> rows are '
- 'the apples-to-apples comparison.</div>')
- shape = shape_line(payload)
- if shape:
- body.append(f'<p class="shape-line tabular">{esc(shape)}</p>')
- if single_rows:
- body.append(chart.single_series_bar_chart(single_rows))
- table = table_html(["Case", "BASE p50", "BASE p95", "HEAD p50", "HEAD p95", "Delta", "OK B/H"],
- case_rows(payload, require_base=False))
- body.append(f'<details><summary>Table view</summary>{table}</details>')
- return f'<section class="card">{"".join(body)}</section>'
-
-
-def synthetic_section(report):
- if not report:
- return ""
- rows = build_speedup_rows(report)
- method = report.get("methodology", {})
- hint = (f'{method.get("measured_runs", "?")} measured runs, {method.get("warmup_runs", "?")} warmup. '
- f'Legacy: {method.get("legacy_path", "legacy snapshot path")}. '
- f'Live: {method.get("live_find_path", "live find path")}.')
- table_rows = []
- for sc in report.get("scenarios", []):
- legacy, live, comp = sc["legacy_snapshot"], sc["live_find_selected_refs"], sc["comparison"]
- table_rows.append([sc["name"], f'{legacy["p50_us"] / 1000:.2f} ms', f'{legacy["p95_us"] / 1000:.2f} ms',
- f'{live["p50_us"] / 1000:.2f} ms', f'{live["p95_us"] / 1000:.2f} ms',
- legacy["attributes_requested"], live["attributes_requested"],
- "yes" if comp.get("find_correctness_delta", 0) > 0 else "no"])
- table = table_html(["Scenario", "Legacy p50", "Legacy p95", "Live p50", "Live p95", "Legacy attrs", "Live attrs", "Fix"],
- table_rows)
- return (
- '<section class="card"><div class="card-head"><h2>Synthetic locator benchmark</h2></div>'
- f'<p class="hint">{esc(hint)}</p>{chart.speedup_bar_chart(rows)}'
- f'<details><summary>Table view</summary>{table}</details></section>'
- )
-
-
-def page_chrome(head, base, rounds, out_dir):
- rounds_part = f" · {rounds} rounds" if rounds else ""
- header = (
- '<header class="band">'
- f'<h1>agent-desktop performance - HEAD {esc(head)} vs base {esc(base)}</h1>'
- f'<p class="subtitle">{datetime.date.today().isoformat()}{rounds_part} · alternating rounds, '
- 'isolated per-binary stores, wall-clock per process invocation</p></header>'
- )
- footer = (
- '<footer class="band">'
- '<p>Regenerate: <code>bash scripts/perf-baseline-compare.sh --apps "Slack,Google Chrome"</code></p>'
- f'<p>Artifacts: <code>{esc(out_dir)}</code> · '
- f'generated {esc(datetime.datetime.now().isoformat(timespec="seconds"))}</p></footer>'
- )
- return header, footer
+ for name, sides in payload.get('cases', {}).items():
+ head, base = sides.get('HEAD') or {}, sides.get('BASE') or {}
+ shapes_match = head.get('shape') == base.get('shape')
+ shapes_known = not name.startswith('snapshot') or head.get('shape') is not None
+ h, b = head.get('p50_ms'), base.get('p50_ms')
+ comparable = (head.get('ok_rate') == base.get('ok_rate') == 1 and shapes_match
+ and shapes_known and number(h) != 'unknown' and number(b) != 'unknown' and b > 0)
+ delta = f'{(h / b - 1) * 100:+.1f}%' if comparable else 'not comparable'
+ for label, side in [('BASE', base), ('HEAD', head)]:
+ shape = side.get('shape')
+ rows.append([name, label, number(side.get('p50_ms')), number(side.get('p95_ms')),
+ number(side.get('ok_rate'), 0.01), json.dumps(shape) if shape is not None else 'unknown',
+ delta if label == 'HEAD' else '—'])
+ intro = (f'<p>{escape(str(payload.get("app", "unknown app")))}; '
+ f'{escape(str(payload.get("rounds", "unknown")))} rounds. '
+ 'Latency uses successful samples only. OK rate includes failures; 100% OK does not verify action effects. '
+ 'Shape = [nodes, depth, refs] from the first successful snapshot, not proof of identical content. '
+ 'Deltas require successful runs and matching known snapshot shapes.</p>')
+ return intro + (table(['Case', 'Side', 'p50 ms', 'p95 ms', 'OK %', 'Shape', 'p50 delta'], rows)
+ if rows else '<p>No case measurements available.</p>')
+
+
+def synthetic_report(payload):
+ body = ['<p>HEAD-only synthetic CPU benchmark: legacy and live paths in the same revision. '
+ 'This is not revision A/B and does not measure native IPC latency or target-app CPU usage.</p>',
+ '<pre>' + escape(json.dumps(payload.get('methodology', {}), indent=2)) + '</pre>']
+ scenarios = payload.get('scenarios', [])
+ if not scenarios:
+ body.append('<p>No synthetic scenarios available.</p>')
+ for scenario in scenarios:
+ body.append('<h3>' + escape(str(scenario.get('name', 'unknown scenario'))) + '</h3>')
+ rows = []
+ for key in ['legacy_snapshot', 'live_arena_direct', 'live_count_no_refmap', 'live_find_selected_refs']:
+ path = scenario.get(key) or {}
+ rows.append([key, number(path.get('p50_us'), 1000), number(path.get('p95_us'), 1000),
+ path.get('attributes_requested', 'unknown'), outcome(path.get('correct_all_runs')),
+ path.get('observed_matches', 'unknown'), path.get('ref_count', 'not applicable'),
+ outcome(path.get('selected_refs_reresolvable')) if key == 'live_find_selected_refs' else 'not applicable'])
+ body.append('<p>Expected matches: ' + escape(str(scenario.get('expectation', {}).get('matches', 'unknown'))) + '</p>')
+ body.append(table(['Path', 'p50 ms', 'p95 ms', 'Attributes', 'Correct all runs', 'Matches', 'Refs', 'Refs re-resolvable'], rows))
+ return ''.join(body)
+
+
+def section(path, synthetic=False):
+ heading = '<h2>' + escape(path.name) + '</h2>'
+ if not path.exists():
+ return heading + '<p>Not collected: artifact missing.</p>'
+ link = f'<p><a href="{escape(path.name, quote=True)}">Raw JSON</a></p>'
+ try:
+ payload = json.loads(path.read_text())
+ except (OSError, ValueError) as error:
+ return heading + link + '<p>Cannot read artifact: ' + escape(str(error)) + '</p>'
+ return heading + link + (synthetic_report(payload) if synthetic else live_report(payload))
def main():
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("out_dir")
- parser.add_argument("--head", required=True)
- parser.add_argument("--base", required=True)
+ parser.add_argument('out_dir', type=Path)
+ parser.add_argument('--head', required=True)
+ parser.add_argument('--base', required=True)
args = parser.parse_args()
-
- fixture = load(os.path.join(args.out_dir, "fixture-ab.json"))
- synthetic = load(os.path.join(args.out_dir, "locator-synthetic.json"))
- apps = [load(p) for p in sorted(glob.glob(os.path.join(args.out_dir, "app-*.json")))]
- apps = [a for a in apps if a]
- sections = [fixture_section(fixture)] + [app_section(a) for a in apps] + [synthetic_section(synthetic)]
- tiles = build_tiles(fixture, synthetic)
- rounds = fixture.get("rounds") if fixture else None
- header, footer = page_chrome(args.head, args.base, rounds, os.path.abspath(args.out_dir))
- body = header + tiles_html(tiles) + '<main class="col">' + "".join(sections) + "</main>" + footer
- title = f"agent-desktop performance - HEAD {args.head} vs base {args.base}"
- html_doc = PAGE.format(title=esc(title), css=CSS, body=body, js=JS)
-
- out_path = os.path.join(args.out_dir, "report.html")
- with open(out_path, "w") as handle:
- handle.write(html_doc)
-
- print(f"agent-desktop performance report: HEAD {args.head} vs base {args.base}")
- for t in tiles:
- print(f' {t["label"]}: {t["value"]} ({t["delta_text"]})')
- print(f" apps covered: {', '.join(a['app'] for a in apps) if apps else 'none'}")
- print(f" report: {out_path}")
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
+ title = f'Performance: HEAD {args.head} vs BASE {args.base}'
+ body = ['<h1>' + escape(title) + '</h1>', '<p>Generated ' + datetime.datetime.now().isoformat(timespec='seconds') + '</p>',
+ '<p>Live probes alternate revisions with isolated stores and measure wall-clock process latency. '
+ 'CPU consumption is not measured by the live probe.</p>', section(args.out_dir / 'fixture-ab.json')]
+ apps = sorted(args.out_dir.glob('app-*.json'))
+ body.extend(section(path) for path in apps)
+ if not apps:
+ body.append('<h2>Real applications</h2><p>No real-app artifacts collected.</p>')
+ body.append(section(args.out_dir / 'locator-synthetic.json', synthetic=True))
+ css = ('body{font:15px system-ui;margin:2rem;line-height:1.5}table{border-collapse:collapse}'
+ 'th,td{border:1px solid #aaa;padding:.4rem;text-align:left}th{background:#eee}'
+ '.scroll{overflow-x:auto}pre{white-space:pre-wrap}td{font-variant-numeric:tabular-nums}')
+ document = ('<!doctype html><html lang="en"><meta charset="utf-8">'
+ '<meta name="viewport" content="width=device-width,initial-scale=1">'
+ '<title>' + escape(title) + '</title><style>' + css + '</style><body>' + ''.join(body) + '</body></html>')
+ output = args.out_dir / 'report.html'
+ output.write_text(document)
+ print(f'Performance report: {output}')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/perf_report_svg.py b/scripts/perf_report_svg.py
deleted file mode 100644
index 1c6ac9de7..000000000
--- a/scripts/perf_report_svg.py
+++ /dev/null
@@ -1,291 +0,0 @@
-#!/usr/bin/env python3
-"""Pure SVG chart builders for the agent-desktop performance report.
-
-No third-party deps, no file or network I/O. Every public function takes
-plain-Python row dicts (already formatted by the caller) and returns a
-self-contained ``<svg>`` string. Colors are applied only via CSS classes
-(``bar-head``, ``bar-base``, ``good``, ``secondary``, ``muted``, ``status-good``,
-``chip-*``) so the same markup adapts to the host page's light/dark tokens.
-"""
-import math
-
-VB_W = 860
-BAR_H = 16
-BAR_GAP = 2
-ROW_GAP = 20
-TOP_PAD = 18
-AXIS_H = 30
-CHIP_GAP = 14
-LABEL_GAP = 14
-CHECK = "✓"
-
-
-def esc(value):
- text = str(value)
- return (
- text.replace("&", "&amp;")
- .replace("<", "&lt;")
- .replace(">", "&gt;")
- .replace('"', "&quot;")
- .replace("'", "&#39;")
- )
-
-
-def pct_delta(head, base):
- if not base:
- return None
- return (head - base) / base * 100.0
-
-
-def fmt_delta(head, base):
- delta = pct_delta(head, base)
- if delta is None:
- return None, "muted"
- return f"{delta:+.0f}%", ("good" if head < base else "secondary")
-
-
-def nice_ticks(max_value, target=4):
- if max_value <= 0:
- return [0, 1]
- raw_step = max_value / target
- magnitude = 10 ** math.floor(math.log10(raw_step))
- step = magnitude
- for mult in (1, 2, 2.5, 5, 10):
- step = mult * magnitude
- if step >= raw_step:
- break
- ticks, value, limit = [], 0.0, max_value + step * 0.5
- while value <= limit:
- ticks.append(round(value, 6))
- value += step
- return ticks
-
-
-def _clamp(value, lo, hi):
- return max(lo, min(hi, value))
-
-
-def _measure(text, size):
- return len(str(text)) * size * 0.54
-
-
-def _bar(x, y, w, h, cls):
- w = max(w, 0.0)
- if w <= 0:
- return ""
- r = min(4.0, w / 2, h / 2)
- out = [f'<rect class="{cls}" x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" rx="{r:.1f}" ry="{r:.1f}"/>']
- if w > r:
- out.append(f'<rect class="{cls}" x="{x:.1f}" y="{y:.1f}" width="{r:.1f}" height="{h:.1f}"/>')
- return "".join(out)
-
-
-def _tick(x, y, h, cls="tick"):
- return f'<line class="{cls}" x1="{x:.1f}" y1="{y - 3:.1f}" x2="{x:.1f}" y2="{y + h + 3:.1f}"/>'
-
-
-def _hit(x, y, w, h, title, rows):
- row_str = esc("|".join(f"{label}={value}" for label, value in rows))
- return (
- f'<rect class="hit" x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" '
- f'data-tt-title="{esc(title)}" data-tt-rows="{row_str}"/>'
- )
-
-
-def _chip(x_right, y_mid, text, cls, size=11):
- w = _measure(text, size) + 18
- h = 20
- x, y = x_right - w, y_mid - h / 2
- return (
- f'<rect class="chip chip-{cls}" x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h}" rx="10" ry="10"/>'
- f'<text class="chip-text chip-text-{cls}" x="{x_right - 9:.1f}" y="{y_mid + 4:.1f}" '
- f'text-anchor="end" font-size="{size}">{esc(text)}</text>'
- )
-
-
-def _axis(sx, ticks, top, bottom, unit, suffix_x=False):
- out = []
- for tick in ticks:
- tx = sx(tick)
- out.append(f'<line class="gridline" x1="{tx:.1f}" y1="{top - 6:.1f}" x2="{tx:.1f}" y2="{bottom + 6:.1f}"/>')
- label = f"{tick:g}x" if suffix_x else f"{tick:g}{unit}"
- out.append(
- f'<text class="axis-tick muted tabular" x="{tx:.1f}" y="{bottom + 22:.1f}" '
- f'text-anchor="middle" font-size="10.5">{label}</text>'
- )
- return "".join(out)
-
-
-def _grouped_summary(rows):
- best = max(rows, key=lambda r: abs(pct_delta(r["head"]["value"], r["base"]["value"]) or 0))
- delta = pct_delta(best["head"]["value"], best["base"]["value"]) or 0
- return (
- f"Grouped horizontal bar chart comparing HEAD and BASE p50 latency across {len(rows)} cases. "
- f"Largest change: {best['label']} at {delta:+.0f}%."
- )
-
-
-def grouped_bar_chart(rows, unit=" ms"):
- if not rows:
- return '<svg class="chart" viewBox="0 0 860 40" role="img" aria-label="No data available"></svg>'
- label_w = _clamp(max(_measure(r["label"], 12.5) for r in rows) + LABEL_GAP, 120, 300)
- chip_w = _clamp(
- max((_measure(r["delta_text"], 11) + 18 for r in rows if r.get("delta_text")), default=50), 50, 200
- )
- x0, x1 = label_w, VB_W - chip_w - CHIP_GAP
- plot_w = max(x1 - x0, 40)
- data_max = max(max(r["head"]["value"], r["head"]["tick"], r["base"]["value"], r["base"]["tick"]) for r in rows)
- ticks = nice_ticks(data_max, 4)
- domain_max = (ticks[-1] or 1) * 1.24
- group_h = BAR_H * 2 + BAR_GAP
- row_pitch = group_h + ROW_GAP
- top = TOP_PAD
- bottom = top + row_pitch * len(rows) - ROW_GAP
- height = bottom + AXIS_H
-
- def sx(v):
- return x0 + (v / domain_max) * plot_w
-
- parts = [
- f'<svg class="chart" viewBox="0 0 {VB_W} {height:.0f}" width="100%" role="img" '
- f'aria-label="{esc(_grouped_summary(rows))}">',
- _axis(sx, ticks, top, bottom, unit),
- ]
- for i, row in enumerate(rows):
- y = top + i * row_pitch
- y_head, y_base, cy = y, y + BAR_H + BAR_GAP, y + group_h / 2
- parts.append(
- f'<text class="row-label ink" x="{x0 - LABEL_GAP:.1f}" y="{cy + 4:.1f}" '
- f'text-anchor="end" font-size="12.5">{esc(row["label"])}</text>'
- )
- for series, sy, cls in (("head", y_head, "bar-head"), ("base", y_base, "bar-base")):
- d = row[series]
- w = max((d["value"] / domain_max) * plot_w, 0)
- parts.append(_bar(x0, sy, w, BAR_H, cls))
- if d.get("tick") is not None:
- parts.append(_tick(sx(d["tick"]), sy, BAR_H))
- parts.append(
- f'<text class="value-label ink tabular" x="{x0 + w + 6:.1f}" y="{sy + BAR_H / 1.4:.1f}" '
- f'font-size="12">{d["value"]:.1f}{unit}</text>'
- )
- parts.append(_hit(0, sy, VB_W, BAR_H, d["tip_title"], d["tip_rows"]))
- if row.get("delta_text"):
- parts.append(_chip(VB_W, cy, row["delta_text"], "good" if row.get("delta_good") else "secondary"))
- parts.append("</svg>")
- return "".join(parts)
-
-
-def _single_summary(rows):
- return f"Bar chart of {len(rows)} HEAD-only measurement(s) with no baseline equivalent."
-
-
-def single_series_bar_chart(rows, unit=" ms"):
- if not rows:
- return '<svg class="chart" viewBox="0 0 860 40" role="img" aria-label="No data available"></svg>'
- label_w = _clamp(max(_measure(r["label"], 12.5) for r in rows) + LABEL_GAP, 120, 300)
- chip_w = _clamp(
- max((_measure(r["badge_text"], 10.5) + 24 for r in rows if r.get("badge_text")), default=0), 0, 320
- )
- gap = CHIP_GAP if chip_w else 0
- x0, x1 = label_w, VB_W - chip_w - gap
- plot_w = max(x1 - x0, 40)
- data_max = max(max(r["value"], r.get("tick") or 0) for r in rows)
- ticks = nice_ticks(data_max, 4)
- domain_max = (ticks[-1] or 1) * 1.24
- row_pitch = BAR_H + ROW_GAP
- top = TOP_PAD
- bottom = top + row_pitch * len(rows) - ROW_GAP
- height = bottom + AXIS_H
-
- def sx(v):
- return x0 + (v / domain_max) * plot_w
-
- parts = [
- f'<svg class="chart" viewBox="0 0 {VB_W} {height:.0f}" width="100%" role="img" '
- f'aria-label="{esc(_single_summary(rows))}">',
- _axis(sx, ticks, top, bottom, unit),
- ]
- for i, row in enumerate(rows):
- y = top + i * row_pitch
- cy = y + BAR_H / 2
- parts.append(
- f'<text class="row-label ink" x="{x0 - LABEL_GAP:.1f}" y="{cy + 4:.1f}" '
- f'text-anchor="end" font-size="12.5">{esc(row["label"])}</text>'
- )
- w = max((row["value"] / domain_max) * plot_w, 0)
- parts.append(_bar(x0, y, w, BAR_H, "bar-head"))
- if row.get("tick") is not None:
- parts.append(_tick(sx(row["tick"]), y, BAR_H))
- parts.append(
- f'<text class="value-label ink tabular" x="{x0 + w + 6:.1f}" y="{cy + 4:.1f}" '
- f'font-size="12">{row["value"]:.1f}{unit}</text>'
- )
- if row.get("badge_text"):
- parts.append(_chip(VB_W, cy, row["badge_text"], "info", size=10.5))
- parts.append(_hit(0, y, VB_W, BAR_H, row["tip_title"], row["tip_rows"]))
- parts.append("</svg>")
- return "".join(parts)
-
-
-def _speedup_summary(rows):
- best = max(rows, key=lambda r: r["speedup"])
- worst = min(rows, key=lambda r: r["speedup"])
- return (
- f"Horizontal speedup bars for {len(rows)} synthetic scenarios, live find path versus legacy snapshot path. "
- f"Speedups range from {worst['speedup']:.1f}x to {best['speedup']:.1f}x against a 1.0x parity reference."
- )
-
-
-def speedup_bar_chart(rows):
- if not rows:
- return '<svg class="chart" viewBox="0 0 860 40" role="img" aria-label="No data available"></svg>'
- badge_text = f"{CHECK} legacy answered wrong - live path correct"
- label_w = _clamp(max(_measure(r["label"], 11.5) for r in rows) + LABEL_GAP, 140, 340)
- chip_w = _clamp(_measure(badge_text, 10.5) + 24 if any(r.get("correctness_fix") for r in rows) else 0, 0, 340)
- gap = CHIP_GAP if chip_w else 0
- x0, x1 = label_w, VB_W - chip_w - gap
- plot_w = max(x1 - x0, 40)
- data_max = max([r["speedup"] for r in rows] + [1.0])
- ticks = nice_ticks(data_max, 4)
- domain_max = (ticks[-1] or 1) * 1.2
- row_pitch = BAR_H + ROW_GAP + 14
- top = TOP_PAD + 6
- bottom = top + row_pitch * len(rows) - ROW_GAP - 14
- height = bottom + AXIS_H
-
- def sx(v):
- return x0 + (v / domain_max) * plot_w
-
- parts = [
- f'<svg class="chart" viewBox="0 0 {VB_W} {height:.0f}" width="100%" role="img" '
- f'aria-label="{esc(_speedup_summary(rows))}">',
- _axis(sx, [t for t in ticks if abs(t - 1.0) > 1e-9], top, bottom, "", suffix_x=True),
- ]
- px = sx(1.0)
- parts.append(f'<line class="parity" x1="{px:.1f}" y1="{top - 6:.1f}" x2="{px:.1f}" y2="{bottom + 6:.1f}"/>')
- parts.append(
- f'<text class="muted" x="{px:.1f}" y="{top - 9:.1f}" text-anchor="middle" font-size="10.5">parity</text>'
- )
- for i, row in enumerate(rows):
- y = top + i * row_pitch
- cy = y + BAR_H / 2
- parts.append(
- f'<text class="row-label ink" x="{x0 - LABEL_GAP:.1f}" y="{cy + 4:.1f}" '
- f'text-anchor="end" font-size="11.5">{esc(row["label"])}</text>'
- )
- w = max((row["speedup"] / domain_max) * plot_w, 0)
- parts.append(_bar(x0, y, w, BAR_H, "bar-head"))
- end_x = x0 + w + 6
- parts.append(
- f'<text class="value-label ink tabular" x="{end_x:.1f}" y="{cy + 4:.1f}" '
- f'font-size="12">{row["speedup"]:.1f}x</text>'
- )
- if row.get("sub_label"):
- parts.append(
- f'<text class="muted" x="{end_x:.1f}" y="{cy + 17:.1f}" font-size="10">{esc(row["sub_label"])}</text>'
- )
- if row.get("correctness_fix"):
- parts.append(_chip(VB_W, cy, badge_text, "status-good", size=10.5))
- parts.append(_hit(0, y - 7, VB_W, BAR_H + 14, row["tip_title"], row["tip_rows"]))
- parts.append("</svg>")
- return "".join(parts)
diff --git a/scripts/run-native-e2e-ci.sh b/scripts/run-native-e2e-ci.sh
index 32b8fc978..dcf995a6a 100755
--- a/scripts/run-native-e2e-ci.sh
+++ b/scripts/run-native-e2e-ci.sh
@@ -13,12 +13,5 @@ if [ "${AGENT_DESKTOP_NATIVE_E2E_RUNNER:-}" != "1" ]; then
exit 2
fi
-cargo build --locked --release -p agent-desktop
-cargo build --locked --release -p agent-desktop-macos --bin agent-desktop-macos-helper
-cargo build --locked --profile release-ffi -p agent-desktop-ffi
-
AGENT_DESKTOP_E2E_EXCLUSIVE=1 \
-AGENT_DESKTOP_E2E_RELEASE_BIN="$ROOT/target/release/agent-desktop" \
-AGENT_DESKTOP_E2E_RELEASE_FFI="$ROOT/target/release-ffi/libagent_desktop_ffi.dylib" \
-AGENT_DESKTOP_E2E_RELEASE_FFI_HELPER="$ROOT/target/release/agent-desktop-macos-helper" \
bash tests/e2e/run.sh
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index 291b5759a..80598a97e 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -96,7 +96,7 @@ When you know the target's role or exact name, use `find --role ... --name ... -
- **Strict resolution:** stale refs return `STALE_REF`; duplicate plausible targets return `AMBIGUOUS_TARGET` instead of choosing arbitrarily.
- **Actionability:** every ref-addressed action checks its applicable live visibility, stability, enabled, editability, policy, supported-action, and hit-test requirements under one bounded budget before a single dispatch. Pointer actions focus before their final geometry read, re-resolve moving endpoints, and return `TIMEOUT` with `details.kind: "actionability_timeout"` instead of sending input after the deadline.
- **Headless vs headed:** ref actions are strictly headless by default: semantic accessibility APIs only, with no focus stealing, cursor movement, or synthesized keyboard input. In headed mode, core focuses the exact ref window before dispatch; pointer actions also require a verified target point, while the adapter owns OS delivery. On macOS, `click`, `right-click`, `type`, `clear`, and `scroll` are physical-first; double/triple-click, hover, and drag are physical-only; expand/collapse and other semantic actions remain semantic. Raw `--xy` input has no window identity and never steals focus. `press` is explicit physical keyboard input; held-input commands (`key-down`, `key-up`, `mouse-down`, `mouse-up`) are reserved and fail closed in the stateless CLI.
-- **Sessions and tracing:** run `session start` once per agent run to create a manifest with `trace: on` (default), then pass its returned ID with `--session` or `AGENT_DESKTOP_SESSION`. Use `session start --screenshots` when you need replay artifacts (`artifacts: full`): pre/post-action PNGs and refmap copies under the session trace directory (sensitive — treat exports like screenshots). Commands in that explicit scope record JSONL automatically to per-process segments under `~/.agent-desktop/sessions/<id>/trace/<pid>-<procTs>.jsonl` — no `--trace` on every call. Read traces back with `trace show` (bounded JSON for agents) or `trace export` (single-file HTML for humans). A session owns both its trace and its latest-snapshot namespace. Snapshot lookup never searches another namespace. **`--session <id>` alone** (no manifest from `session start`) selects only the snapshot namespace — existing callers see no surprise trace files. **`--trace <path>`** still overrides to one atomic file for CI or one-offs. Activation precedence is `--session` > `AGENT_DESKTOP_SESSION` > no session; `session start` does not activate later processes. Multi-agent shared sessions: each agent acts on qualified refs from its own snapshot — implicit latest is not a cross-agent guarantee. Run `status` to see `session_id` and `tracing`. Trace lines include `ts_ms`, monotonic per-process `seq`, and redacted sensitive fields (`text`, `value`, `expected`, `name`, `username`, `description`, `label`, `query`, `secret`, `token`, `password`, `title`, `url`, `help`, `placeholder` → `{ "redacted": true }`). `--trace-strict` fails on trace setup and pre-action writes; post-action success traces are best-effort.
+- **Sessions and tracing:** run `session start` once per task to create a manifest with `trace: on` (default), then pass its returned ID with `--session` or `AGENT_DESKTOP_SESSION`. Use `session start --screenshots` when you need replay artifacts (`artifacts: full`): pre/post-action PNGs and refmap copies under the session trace directory (sensitive — treat exports like screenshots). Commands in that explicit scope record JSONL automatically to per-process segments under `~/.agent-desktop/sessions/<id>/trace/<pid>-<procTs>.jsonl` — no `--trace` on every call. Read traces back with `trace show` (bounded JSON for agents) or `trace export` (single-file HTML for humans). A session owns both its trace and its latest-snapshot namespace. Snapshot lookup never searches another namespace. **`--session <id>` alone** (no manifest from `session start`) selects only the snapshot namespace — existing callers see no surprise trace files. **`--trace <path>`** still overrides to one atomic file for CI or one-offs. Activation precedence is `--session` > `AGENT_DESKTOP_SESSION` > no session; `session start` does not activate later processes. Multi-agent shared sessions: the harness passes the same session ID to every subagent. For independent macOS cursors use `session start --cursor --multi-agent` and assign each subagent a stable `AGENT_DESKTOP_AGENT_ID` or global `--agent-id` (flag wins). Desktop UI actions then require the ID; observations, clipboard operations, and administration do not. Three distinct IDs produce three cursors, in both headless and headed mode. Drags reuse the cursor’s curved motion and show a live accent-colored trail while held, fading after release; the ripple setting controls the trail. Physical pointer commands also show their agent’s overlay; the interaction lease serializes access to the shared OS pointer. Each agent acts on qualified refs from its own snapshot — implicit latest is not a cross-agent guarantee. Optional `--agent-id <id> cursor-overlay enable` styling is saved for that agent’s next presentation; no registration is needed. Disable/end stops every session cursor. Run `status` to see `session_id` and `tracing`. Trace lines include `ts_ms`, monotonic per-process `seq`, and redacted sensitive fields (`text`, `value`, `expected`, `name`, `username`, `description`, `label`, `query`, `secret`, `token`, `password`, `title`, `url`, `help`, `placeholder` → `{ "redacted": true }`). `--trace-strict` fails on trace setup and pre-action writes; post-action success traces are best-effort.
## JSON Output Contract
@@ -240,13 +240,14 @@ agent-desktop wait --notification --app "App" # Wait for new notification
### System
```
-agent-desktop session start [--name LABEL] [--screenshots] [--no-trace] [--cursor] # Creates a session; pass the returned ID explicitly
+agent-desktop session start [--name LABEL] [--screenshots] [--no-trace] [--cursor [--multi-agent]] # Creates a session; pass the returned ID explicitly
agent-desktop session end [id] # Seal manifest
agent-desktop session list # List session manifests
agent-desktop session gc [--older-than SECS] [--ended] # Reclaim ended/stale sessions
-agent-desktop --session <id> cursor-overlay enable [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]
+agent-desktop --session <id> cursor-overlay enable [--multi-agent] [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]
+agent-desktop --session <id> --agent-id ID cursor-overlay enable [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]
export AGENT_DESKTOP_SESSION=<id>
-agent-desktop cursor-overlay disable # Remove the overlay and stop its renderer
+agent-desktop cursor-overlay disable # Stop all cursors in the selected session
agent-desktop trace show [--limit N] [--event PREFIX] # Merge trace segments (default tail 500; 0 = all)
agent-desktop trace export [--out path.html] [--limit N] # Self-contained HTML viewer (default tail 5000)
agent-desktop status # Health, session_id, tracing, artifacts, permissions
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index 39a0aabf5..39c1fc2f5 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -37,6 +37,8 @@ Reach into that overlay with `find --surface sheet` rather than searching the
window. A `delivered_unverified` result with a surface still open usually means
the application is waiting for a confirmation the action did not deliver.
+On macOS, headed clicks on native menu-bar items use AXPress because these items have no ordinary owning window. Other headed ref clicks retain physical target verification. An enabled cursor overlay travels to and highlights that verified target alongside the real pointer.
+
### `--wait-for` / `--wait-for-gone` (global)
Three global flags poll the accessibility tree until a compact selector matches (or, with `--wait-for-gone`, until it no longer matches), then return a snapshot envelope:
@@ -55,9 +57,9 @@ agent-desktop click @s8f3k2p9:e5 --wait-for-gone "progressindicator" --wait-time
**Selector grammar:** one `role:text` string split on the first `:`. Examples: `"button:Submit"` (role + text), `"button"` (role only), `":Saved!"` (text only). Matching uses the same `find` matcher (`node_matches`); text searches name, value, and description.
-**Supported commands:** `snapshot` plus all 18 ref-resolving actions (`click`, `type`, `set-value`, `scroll`, `hover`, `drag`, …) — 19 commands total. Other commands (`find`, `launch`, …) return `INVALID_ARGS`. Workaround: `snapshot --app Foo -w "button:Login"`.
+**Supported commands:** `snapshot`, `press`, and all 18 ref-resolving actions (`click`, `type`, `set-value`, `scroll`, `hover`, `drag`, …). Other commands (`find`, `launch`, …) return `INVALID_ARGS`. Workaround: `snapshot --app Foo -w "button:Login"`.
-**Post-action waits** poll the **acted-on ref's own window** (`entry.source_window_id`, scoped to `entry.source_app`), not the frontmost window — critical in headless and multi-window apps where the terminal or a sibling window has focus. The action result is preserved under `after_action` in the returned envelope.
+**Post-action waits** for ref actions poll the **acted-on ref's own window** (`entry.source_window_id`, scoped to `entry.source_app`). For `press`, `--app` scopes the observation to that app; without it, observation uses the frontmost app. The action result is preserved under `after_action` in the returned envelope.
**Success shape:** a match returns the full snapshot envelope (`app`, `window`, `ref_count`, `snapshot_id`, `tree`) plus `elapsed_ms` and `matched_selector`. The one exception is `--wait-for-gone` when the target **app or window has itself closed**: there is no tree left to capture, so the success payload is the compact `{ "matched_selector", "gone": true, "target_absent": true, "elapsed_ms" }`. On timeout the `wait_timeout` error `details` carry `last_error` (when a poll errored) and the `snapshot_id` of the last tree built.
@@ -229,6 +231,25 @@ agent-desktop press cmd+a --app "TextEdit"
|------|-------------|
| `--app` | Target application; key delivery is PID-targeted, and `--headed` additionally focuses its exact window first |
+`press` reports `delivered_unverified`: delivery does not prove the shortcut produced the intended UI. Use the global CLI selector flags to wait for an expected accessible element in the requested app after sending the key once:
+
+```bash
+agent-desktop press cmd+s --app "TextEdit" --wait-for "button:Save" --wait-timeout 5000
+```
+
+`--wait-for-gone "button:Save"` waits for disappearance instead. Success returns the observed selector result plus the original key delivery under `after_action`; it does not prove an unrelated effect such as audio playback. A timeout retains the delivered result and is unsafe to retry blindly. These global flags apply to the CLI, not batch item arguments or the C ABI.
+
+For a new window, keep the press and event wait in one batch so the baseline is captured before delivery:
+
+```bash
+agent-desktop --headed batch '[
+ {"command":"press","args":{"combo":"cmd+k","app":"GarageBand"}},
+ {"command":"wait","args":{"event":"window-opened","window":"Musical Typing","app":"GarageBand","timeout":5000}}
+]' --stop-on-error
+```
+
+Use the actual window title for the current app language. To check a window that may already be open, use `wait --window "Musical Typing" --app "GarageBand" --timeout 5000`. A failed wait does not make the preceding press safe to repeat.
+
**Key names:** `return`, `escape`, `tab`, `space`, `delete`, `up`, `down`, `left`, `right`, `f1`-`f12`
**Modifiers:** `cmd`, `ctrl`, `alt`, `shift` — combine with `+`
@@ -319,12 +340,14 @@ Synthesizes a scroll-wheel event at absolute coordinates and requires `--headed`
### Agent cursor presentation
-Enable it once per session with `session start --cursor` or `cursor-overlay enable`. Interaction commands take no cursor flags.
+Enable it once per session with `session start --cursor` or `cursor-overlay enable`. Interaction commands inherit styling. For macOS harness subagents, use `session start --cursor --multi-agent` and global `--agent-id` or `AGENT_DESKTOP_AGENT_ID` on each worker. Each ID gets an independent cursor within the same snapshot namespace. Configure optional per-agent styling with `--agent-id <id> cursor-overlay enable`; action-specific cursor flags remain unsupported.
-- The cursor stays alive between eligible headless ref actions and travels from its previous destination.
+- The cursor stays alive between eligible headless or headed actions and travels from its previous destination.
- The action waits for it to land before it dispatches, capped at 900 ms.
- A click plays a ripple and flashes an accent outline around the element.
-- Headed actions hide the overlay and use the real OS cursor. Raw pointer commands keep their headed-only behavior.
+- Headed actions retain each agent’s overlay while using the real OS cursor. Physical clicks present at the verified input point. Raw pointer commands also present the selected agent’s cursor and keep their headed-only behavior. The existing interaction lease serializes physical input; independent overlays do not create additional OS pointers.
+
+Drags reuse the cursor overlay’s curved motion. With the overlay enabled, its cursor and accent-colored trail follow the actual pointer while the button is held, including the destination dwell, then the trail fades after release. The existing ripple setting (`--no-ripple`) and Reduce Motion disable the trail. `--duration` controls travel only (default 300 ms); `--drop-delay 1000` holds over the destination for one second before releasing.
See `commands-system.md` for the style flags.
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index c2214f92f..e2eafadf2 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -330,9 +330,9 @@ When `--snapshot` is omitted, the command polls the caller's latest session refm
### wait (window)
```bash
-agent-desktop wait --window "Save As" --timeout 10000
+agent-desktop wait --window "Save As" --app "TextEdit" --timeout 10000
```
-Blocks until a window with the given title appears.
+Blocks until a window whose title contains the given text is present. `--app` restricts matches to that application; without it, all applications are searched. On timeout, `details.last_observed` reports the scoped window count and up to eight titles, each capped at 120 characters, with `truncated` indicating omitted content. This distinguishes a missing expected window from a shortcut whose key delivery succeeded.
### wait (text)
```bash
@@ -406,7 +406,7 @@ agent-desktop batch '[{"command":"launch","args":{"app":"Obsidian","cdp":0}}]'
```
Execute multiple commands in sequence from a JSON array. Each entry has `command` (string) and `args` (object). Use `args`, not `params`. For ref-consuming commands, pass the output `snapshot_id` as the `snapshot` field.
-Batch uses the same typed `Commands` enum, command policy preflight, permission report, and dispatch path as the CLI. Unknown fields are rejected instead of being silently ignored. Nested `batch` is rejected.
+Batch uses the same typed `Commands` enum, command policy preflight, permission report, and dispatch path as the CLI. Unknown fields are rejected instead of being silently ignored. Nested `batch` is rejected. If an entry’s session ends before dispatch, that entry is reported as `not_started` with reason `session_ended`; `--stop-on-error` stops there, otherwise later entries continue.
Each entry may include `"session": "id"` beside `command` and `args`. If omitted, the entry inherits the top-level resolved session. Use per-entry sessions only when intentionally inspecting or coordinating separate agent runs.
@@ -466,7 +466,7 @@ agent-desktop cursor-overlay disable
No flags gives the default look: white body, near-black rim, blue ripple, blue element outline.
-Style is stored in the session manifest and inherited by every eligible headless command, batch entries included. Action and batch-entry schemas take no cursor flags. Run `enable` again to restyle; it applies at once.
+Style is stored in the session manifest and inherited by every eligible headless or headed command, batch entries included. Action and batch-entry schemas take no cursor flags. Run `enable` again to restyle; it applies at once.
| Flag | Meaning | Default |
|---|---|---|
@@ -482,14 +482,38 @@ Style is stored in the session manifest and inherited by every eligible headless
Behaviour:
- Travel is a human path, 90 to 320 ms. The cursor never rotates or resizes.
-- The action waits for the cursor to land, capped at 900 ms. A slow renderer never blocks it.
+- The action waits for cursor arrival confirmation, capped at 900 ms. An unconfirmed arrival reports a warning and the action still proceeds.
- A click plays a ripple, then flashes an accent outline around the element for 0.9 s. Both draw below the cursor.
- The card shows the label. With no label there is no card.
+- Drags show a live accent-colored path while held and fade after release, controlled by the ripple setting and suppressed under Reduce Motion.
- Idle for 6 s it fades out; the next command restores it.
- `disable` removes it and stops the renderer. Ending the session is not needed.
-- Headed actions hide it while the real pointer is in use.
+- Headed actions retain it while the real pointer is in use.
- macOS renders it natively; other platforms use the adapter's presentation no-op.
+### Shared-session subagent cursors (macOS)
+
+```bash
+agent-desktop session start --cursor --multi-agent
+export AGENT_DESKTOP_SESSION=<returned-session-id>
+```
+
+Cursor presentation works in both headless and headed mode. Physical pointer commands use the same per-agent overlays; the interaction lease coordinates the shared OS pointer.
+
+The harness gives each subagent a stable `AGENT_DESKTOP_AGENT_ID` (or global `--agent-id`, which takes precedence). IDs use 1–64 letters, digits, `-` or `_`. Every desktop UI action in this mode requires the ID; observations, clipboard operations, and session administration do not. Style commands only save a profile; the next verified action presents it. Three active IDs create three independent cursors. Reusing an ID reuses its cursor. There is no extra coordinator cursor or registration step.
+
+Each agent inherits the session style. To customize one agent:
+
+```bash
+agent-desktop --agent-id researcher cursor-overlay enable --label "Checking details" --accent "#FF3B7B"
+agent-desktop --agent-id writer cursor-overlay enable --label "Updating draft" --fill "#FFE080"
+agent-desktop --agent-id reviewer cursor-overlay enable --label "Reviewing result" --accent "#49C98A"
+```
+
+Use the same ID on subsequent actions or export it in that subagent's environment. Profiles persist under the session; they do not create separate snapshots. Invalid profile JSON or style values fall back to the session style with a warning; unsafe or unreadable profile files still fail. Use snapshot-qualified refs when subagents observe concurrently. Distinct overlays do not make concurrent actions on the same application safe; the harness still coordinates dependent work and physical input. Running `cursor-overlay enable --multi-agent` converts the session scope post-hoc and rejects `--agent-id`, so per-agent styling never takes `--multi-agent`.
+
+`cursor-overlay disable` and `session end` remove all session cursors, even when called with an agent ID. Headed actions present the calling agent's overlay. Each inactive cursor keeps the existing six-second fade. Other platforms retain their existing behavior.
+
### session start
```bash
agent-desktop session start
diff --git a/src/batch/execution.rs b/src/batch/execution.rs
index 901c755b6..d5a2d7080 100644
--- a/src/batch/execution.rs
+++ b/src/batch/execution.rs
@@ -78,6 +78,19 @@ pub(super) fn execute(
None => None,
};
+ if let Some(ended_session) = session_ended_for(&commands[index]) {
+ let error = batch_session_ended(index, &commands[index].name, &ended_session);
+ push_small_entry(
+ &mut results,
+ &mut results_bytes,
+ not_started_entry(index, &commands[index].name, "session_ended", error),
+ );
+ if args.stop_on_error {
+ stopped = Some(json!({ "reason": "stop_on_error", "index": index }));
+ break;
+ }
+ continue;
+ }
let item_context = commands[index]
.context
.clone()
@@ -186,6 +199,32 @@ fn baseline_error(
source.into()
}
+fn session_ended_for(command: &PreparedCommand) -> Option<String> {
+ let session_id = command.context.session_id()?;
+ match agent_desktop_core::session::read_manifest(session_id) {
+ Ok(Some(manifest)) if manifest.ended_at.is_some() => Some(session_id.to_owned()),
+ _ => None,
+ }
+}
+
+fn batch_session_ended(index: usize, command: &str, session_id: &str) -> AppError {
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!(
+ "Batch entry {index} ('{command}') was not started because session '{session_id}' has ended"
+ ),
+ )
+ .with_suggestion("Re-run the entry outside the ended session or start a new session")
+ .with_details(json!({
+ "kind": "batch_session_ended",
+ "batch_index": index,
+ "batch_command": command,
+ "session_id": session_id,
+ }))
+ .with_disposition(DeliverySemantics::not_delivered())
+ .into()
+}
+
fn batch_timeout(index: usize, command: &str, timeout_ms: u64) -> AppError {
AdapterError::timeout("Batch deadline elapsed before the entry started")
.with_details(json!({
diff --git a/src/batch/mod.rs b/src/batch/mod.rs
index 9d216c6ab..a8d4d9af9 100644
--- a/src/batch/mod.rs
+++ b/src/batch/mod.rs
@@ -208,6 +208,8 @@ struct BatchSessionStartArgs {
screenshots: bool,
#[serde(default)]
cursor: bool,
+ #[serde(default)]
+ multi_agent: bool,
}
#[derive(Deserialize)]
@@ -234,10 +236,14 @@ fn parse_session(args: Value) -> Result<SessionArgs, AppError> {
}
Some("start") => {
let args: BatchSessionStartArgs = decode("session", rest)?;
+ if args.multi_agent && !args.cursor {
+ return Err(AppError::invalid_input("multi_agent requires cursor"));
+ }
SessionAction::Start(SessionStartArgs {
name: args.name,
no_trace: args.no_trace,
screenshots: args.screenshots,
+ multi_agent: args.multi_agent,
cursor: args.cursor,
})
}
diff --git a/src/batch/preparation.rs b/src/batch/preparation.rs
index 675d0cd78..26e4b06e2 100644
--- a/src/batch/preparation.rs
+++ b/src/batch/preparation.rs
@@ -45,6 +45,8 @@ pub(super) fn prepare(
let item_context = context
.for_batch_item(session)
.map_err(|error| located_error(index, &name, error))?;
+ crate::command_policy::preflight_context(&command, &item_context)
+ .map_err(|error| located_error(index, &name, error))?;
Ok(PreparedCommand {
name,
command,
diff --git a/src/cli/agent_identity_tests.rs b/src/cli/agent_identity_tests.rs
new file mode 100644
index 000000000..e97e92150
--- /dev/null
+++ b/src/cli/agent_identity_tests.rs
@@ -0,0 +1,41 @@
+use super::Cli;
+use clap::Parser;
+
+#[test]
+fn identity_is_global_including_cursor_configuration() {
+ for args in [
+ vec![
+ "agent-desktop",
+ "--session",
+ "run",
+ "--agent-id",
+ "a",
+ "cursor-overlay",
+ "enable",
+ ],
+ vec![
+ "agent-desktop",
+ "cursor-overlay",
+ "enable",
+ "--session",
+ "run",
+ "--agent-id",
+ "a",
+ ],
+ ] {
+ let cli = Cli::try_parse_from(args).unwrap();
+ assert_eq!(cli.identity.session.as_deref(), Some("run"));
+ assert_eq!(cli.identity.agent_id.as_deref(), Some("a"));
+ }
+ assert!(Cli::try_parse_from(["agent-desktop", "session", "start", "--multi-agent"]).is_err());
+ assert!(
+ Cli::try_parse_from([
+ "agent-desktop",
+ "session",
+ "start",
+ "--cursor",
+ "--multi-agent"
+ ])
+ .is_ok()
+ );
+}
diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rs
index df1ca77b4..419f4608a 100644
--- a/src/cli/contract_tests.rs
+++ b/src/cli/contract_tests.rs
@@ -108,7 +108,7 @@ fn cursor_overlay_enable_is_session_scoped_and_bounded() {
};
let config = args.to_core().expect("valid cursor config");
- assert_eq!(cli.session.as_deref(), Some("run-1"));
+ assert_eq!(cli.identity.session.as_deref(), Some("run-1"));
assert!(config.is_enabled());
assert_eq!(config.label(), Some("Opening the profile menu for…"));
assert_eq!(config.style().size(), 2.5);
diff --git a/src/cli/help_after.txt b/src/cli/help_after.txt
index 1305aeb73..57225c05f 100644
--- a/src/cli/help_after.txt
+++ b/src/cli/help_after.txt
@@ -31,7 +31,7 @@ KEYBOARD
MOUSE
hover <ref|--xy> Move cursor to element or coordinates (requires --headed)
- drag Drag from one element/point to another (requires --headed)
+ drag Drag between points; live cursor trail fades after release (requires --headed)
mouse-move --xy x,y Move cursor to absolute coordinates (requires --headed)
mouse-click --xy x,y Click at coordinates (--button, --count; requires --headed)
mouse-down --xy x,y Press mouse button at coordinates (requires --headed)
@@ -83,14 +83,17 @@ SYSTEM
session start Create a trace-enabled session; pass its returned ID explicitly
session start --screenshots Opt in to screenshot/refmap replay artifacts (requires tracing)
session start --cursor Create the session and show the default visual cursor
+ session start --cursor --multi-agent One cursor per harness subagent in headless/headed mode; desktop UI actions require --agent-id
session end Seal a manifest (ID from argument, --session, or environment)
session list List session manifests
session gc Remove ended or provably-stale sessions
- cursor-overlay enable Enable/style the visual cursor for the selected session (no flags = defaults)
- cursor-overlay disable Disable the visual cursor for the selected session
+ cursor-overlay enable Enable/style the session cursor, or the selected --agent-id cursor
+ cursor-overlay disable Stop every cursor in the selected session
ENVIRONMENT
AGENT_DESKTOP_SESSION Session ID fallback when --session is not passed
+ AGENT_DESKTOP_AGENT_ID Stable subagent ID fallback when --agent-id is not passed
+ (1-64 letters, digits, hyphen or underscore; scoped by session)
AGENT_DESKTOP_HOME Relocates the state root; the value is the root itself
(absolute path; default ~/.agent-desktop). Applies to every
command; an invalid value fails with INVALID_ARGS before
@@ -145,6 +148,9 @@ EXAMPLES
agent-desktop snapshot --app Finder -w "button:OK"
agent-desktop click @s8f3k2p9:e5 -w ":Saved!"
agent-desktop session start --name run-a # note data.session_id
+ agent-desktop session start --cursor --multi-agent
+ agent-desktop --session <session_id> --agent-id researcher cursor-overlay enable --label "Checking details"
+ agent-desktop --session <session_id> --agent-id researcher click @s8f3k2p9:e5
agent-desktop --session <session_id> cursor-overlay enable --label "Opening menu" --accent "#4299FF"
agent-desktop --session <session_id> click @s8f3k2p9:e5
agent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}}]'
diff --git a/src/cli/identity.rs b/src/cli/identity.rs
new file mode 100644
index 000000000..8f4dea4f1
--- /dev/null
+++ b/src/cli/identity.rs
@@ -0,0 +1,17 @@
+use clap::Args;
+
+#[derive(Args, Debug)]
+pub(crate) struct IdentityArgs {
+ #[arg(
+ long,
+ global = true,
+ help = "Select the snapshot namespace; session-owned refs require the same scope"
+ )]
+ pub session: Option<String>,
+ #[arg(
+ long,
+ global = true,
+ help = "Harness subagent ID within --session (1-64 letters/digits/-/_; or AGENT_DESKTOP_AGENT_ID)"
+ )]
+ pub agent_id: Option<String>,
+}
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index d46721690..c265f8473 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1,5 +1,6 @@
use clap::Subcommand;
+mod identity;
mod post_action_wait;
mod root;
@@ -198,7 +199,7 @@ impl Commands {
Self::Collapse(_) => CommandMetadata::new("collapse", true),
Self::Scroll(_) => CommandMetadata::new("scroll", true),
Self::ScrollTo(_) => CommandMetadata::new("scroll-to", true),
- Self::Press(_) => CommandMetadata::new("press", false),
+ Self::Press(_) => CommandMetadata::new("press", true),
Self::KeyDown(_) => CommandMetadata::new("key-down", false),
Self::KeyUp(_) => CommandMetadata::new("key-up", false),
Self::Hover(_) => CommandMetadata::new("hover", true),
@@ -325,3 +326,6 @@ mod wait_for_cli_tests;
#[cfg(test)]
#[path = "contract_tests.rs"]
mod contract_tests;
+
+#[cfg(test)]
+mod agent_identity_tests;
diff --git a/src/cli/root.rs b/src/cli/root.rs
index d044f7492..3e349bff2 100644
--- a/src/cli/root.rs
+++ b/src/cli/root.rs
@@ -25,12 +25,8 @@ pub(crate) struct Cli {
help = "Enable debug logging to stderr"
)]
pub verbose: bool,
- #[arg(
- long,
- global = true,
- help = "Select the snapshot namespace; session-owned refs require the same scope"
- )]
- pub session: Option<String>,
+ #[command(flatten)]
+ pub identity: super::identity::IdentityArgs,
#[arg(
long,
global = true,
diff --git a/src/cli/wait_for_cli_tests.rs b/src/cli/wait_for_cli_tests.rs
index 55358c74b..9f38620eb 100644
--- a/src/cli/wait_for_cli_tests.rs
+++ b/src/cli/wait_for_cli_tests.rs
@@ -116,6 +116,7 @@ fn validate_rejects_match_everything_selector_before_dispatch() {
fn validate_accepts_supported_command_with_constraining_selector() {
for supported in [
command(&["snapshot"]),
+ command(&["press", "cmd+k", "--app", "GarageBand"]),
command(&["click", "@e1"]),
command(&["hover", "@e1"]),
command(&["drag", "--from", "@e1", "--to", "@e2"]),
diff --git a/src/cli_args/cursor_overlay_enable.rs b/src/cli_args/cursor_overlay_enable.rs
index ce8daa614..f48d40e04 100644
--- a/src/cli_args/cursor_overlay_enable.rs
+++ b/src/cli_args/cursor_overlay_enable.rs
@@ -2,6 +2,11 @@ use clap::Args;
#[derive(Args, Debug)]
pub(crate) struct CursorOverlayEnableArgs {
+ #[arg(
+ long,
+ help = "Require agent IDs for desktop UI actions; use without --agent-id to configure the session"
+ )]
+ pub multi_agent: bool,
#[arg(
long,
help = "Show caller-authored intent text beside the cursor overlay"
diff --git a/src/cli_args/mod_tests.rs b/src/cli_args/mod_tests.rs
index 97f3ff219..c8e68e90a 100644
--- a/src/cli_args/mod_tests.rs
+++ b/src/cli_args/mod_tests.rs
@@ -2,12 +2,6 @@ use super::*;
use agent_desktop_core::SnapshotSurface;
use clap::ValueEnum;
-/// The exhaustive set of `SnapshotSurface` values the CLI's `Surface` enum is
-/// meant to expose. `SnapshotSurface` is `#[non_exhaustive]`, so a new variant
-/// added to it will not force `Surface::to_core`'s match arms (which match on
-/// the local `Surface`, not on `SnapshotSurface`) to change — this list is the
-/// independent tripwire that must be updated by hand alongside any new
-/// `Surface`/`to_core` arm.
const EXPECTED_CORE_SURFACES: &[SnapshotSurface] = &[
SnapshotSurface::Window,
SnapshotSurface::Focused,
@@ -30,67 +24,15 @@ const EXPECTED_CORE_SURFACES: &[SnapshotSurface] = &[
SnapshotSurface::ActionCenter,
];
-/// Keeps the CLI `Surface` enum and the hand-maintained `EXPECTED_CORE_SURFACES`
-/// tripwire in one-to-one correspondence: every `Surface` variant (enumerated
-/// via its `ValueEnum` derive, so this side stays exhaustive automatically) maps
-/// through `.to_core()` to a distinct `SnapshotSurface`, the tripwire lists each
-/// of those exactly once, and the two sets match. An inconsistent hand-edit — a
-/// `to_core` arm that collides with another, or the tripwire updated without a
-/// matching `Surface`/`to_core` arm (or the reverse) — fails here. The one gap it
-/// cannot close: because `SnapshotSurface` is `#[non_exhaustive]` with no
-/// reflection, a new core variant added with no CLI-side edit keeps both sides
-/// their current size and passes — the by-hand tripwire update is the only
-/// checkpoint for that case (see `EXPECTED_CORE_SURFACES`).
#[test]
fn surface_to_core_maps_one_to_one_onto_expected_core_surfaces() {
- let cli_variants = Surface::value_variants();
- assert_eq!(
- cli_variants.len(),
- EXPECTED_CORE_SURFACES.len(),
- "Surface has {} variants but EXPECTED_CORE_SURFACES has {} — \
- update EXPECTED_CORE_SURFACES (and Surface::to_core) to match",
- cli_variants.len(),
- EXPECTED_CORE_SURFACES.len()
- );
-
- for (i, a) in EXPECTED_CORE_SURFACES.iter().enumerate() {
- for (j, b) in EXPECTED_CORE_SURFACES.iter().enumerate() {
- assert!(
- i == j || a != b,
- "EXPECTED_CORE_SURFACES lists SnapshotSurface::{a:?} more than once — \
- each expected core surface must appear exactly once"
- );
- }
- }
-
- let mapped: Vec<SnapshotSurface> = cli_variants.iter().map(Surface::to_core).collect();
- for (i, a) in mapped.iter().enumerate() {
- for (j, b) in mapped.iter().enumerate() {
- assert!(
- i == j || a != b,
- "Surface::{:?} and Surface::{:?} both map to the same \
- SnapshotSurface::{a:?} via to_core — mapping must be distinct",
- cli_variants[i],
- cli_variants[j]
- );
- }
- }
-
- for expected in EXPECTED_CORE_SURFACES {
- assert!(
- mapped.contains(expected),
- "no Surface variant maps to SnapshotSurface::{expected:?} via to_core — \
- a Surface arm is missing for this core surface"
- );
- }
+ let mapped: Vec<_> = Surface::value_variants()
+ .iter()
+ .map(Surface::to_core)
+ .collect();
+ assert_eq!(mapped, EXPECTED_CORE_SURFACES);
}
-/// God-object regression: `FindArgs` used to carry 14 flat fields; the
-/// match-criteria and result-shaping groups now live in
-/// `FindFilterArgs`/`FindSelectionArgs`, flattened back on. Proves the CLI
-/// surface (flag names, `conflicts_with_all`) is unchanged by the
-/// regrouping — a missing `#[command(flatten)]` would make clap reject these
-/// flags as unrecognized.
#[test]
fn find_args_cli_flags_still_resolve_through_flattened_groups() {
let args = FindArgs::try_parse_from([
@@ -121,9 +63,6 @@ fn find_args_selection_conflicts_still_enforced_across_the_flatten_boundary() {
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
}
-/// Batch JSON is decoded straight into `FindArgs` via serde; a flat payload
-/// (the shape every existing caller sends) must still deserialize now that
-/// the Rust type nests `filter`/`selection`.
#[test]
fn find_args_batch_json_flat_payload_deserializes_into_nested_groups() {
let args: FindArgs = serde_json::from_value(serde_json::json!({
@@ -139,12 +78,6 @@ fn find_args_batch_json_flat_payload_deserializes_into_nested_groups() {
assert!(args.states.is_empty());
}
-/// `WindowScope` (`app`/`window_id`) is shared across `FindArgs`,
-/// `SnapshotArgs`, and `ScreenshotArgs` via `#[serde(flatten)]`, each also
-/// carrying `#[serde(deny_unknown_fields)]` (`F6`). A flat batch payload
-/// (the shape every existing caller sends) must still deserialize into
-/// `.scope.app`/`.scope.window_id` now that the selector lives on its own
-/// struct instead of directly on `FindArgs`.
#[test]
fn find_args_batch_json_flat_scope_deserializes_into_scope_group() {
let args: FindArgs = serde_json::from_value(serde_json::json!({
@@ -158,10 +91,6 @@ fn find_args_batch_json_flat_scope_deserializes_into_scope_group() {
assert!(args.filter.role.is_none());
}
-/// `WindowScope`'s `deny_unknown_fields` must still reject a typo'd scope
-/// field on `FindArgs` instead of silently dropping the window filter — a
-/// mistyped `app` (`ap`) or `window_id` (`windo_id`) should fail loudly
-/// rather than deserialize into a scopeless, all-windows match.
#[test]
fn find_args_batch_json_rejects_scope_field_typo() {
let err = serde_json::from_value::<FindArgs>(serde_json::json!({
@@ -179,9 +108,6 @@ fn find_args_batch_json_rejects_scope_field_typo() {
assert!(err.to_string().contains("`windo_id`"));
}
-/// Same `WindowScope` flatten, pinned for `SnapshotArgs` (`F6`): a flat
-/// `app`/`window_id` payload must still populate `.scope.*` alongside
-/// `SnapshotArgs`'s own defaulted fields.
#[test]
fn snapshot_args_batch_json_flat_scope_deserializes_into_scope_group() {
let args: SnapshotArgs = serde_json::from_value(serde_json::json!({
@@ -195,8 +121,6 @@ fn snapshot_args_batch_json_flat_scope_deserializes_into_scope_group() {
assert_eq!(args.tree.max_depth, 10);
}
-/// `SnapshotArgs` inherits `WindowScope`'s `deny_unknown_fields`; a typo'd
-/// scope field must still be rejected rather than silently ignored.
#[test]
fn snapshot_args_batch_json_rejects_scope_field_typo() {
let err = serde_json::from_value::<SnapshotArgs>(serde_json::json!({
@@ -214,9 +138,6 @@ fn snapshot_args_batch_json_rejects_scope_field_typo() {
assert!(err.to_string().contains("`windo_id`"));
}
-/// Same `WindowScope` flatten, pinned for `ScreenshotArgs` (`F6`): a flat
-/// `app`/`window_id` payload must still populate `.scope.*` alongside
-/// `ScreenshotArgs`'s own optional fields.
#[test]
fn screenshot_args_batch_json_flat_scope_deserializes_into_scope_group() {
let args: ScreenshotArgs = serde_json::from_value(serde_json::json!({
@@ -230,8 +151,6 @@ fn screenshot_args_batch_json_flat_scope_deserializes_into_scope_group() {
assert!(args.screen.is_none());
}
-/// `ScreenshotArgs` inherits `WindowScope`'s `deny_unknown_fields`; a typo'd
-/// scope field must still be rejected rather than silently ignored.
#[test]
fn screenshot_args_batch_json_rejects_scope_field_typo() {
let err = serde_json::from_value::<ScreenshotArgs>(serde_json::json!({
diff --git a/src/cli_args/session.rs b/src/cli_args/session.rs
index 8df005fd0..1200ca859 100644
--- a/src/cli_args/session.rs
+++ b/src/cli_args/session.rs
@@ -31,6 +31,12 @@ pub(crate) struct SessionStartArgs {
pub screenshots: bool,
#[arg(long, help = "Show the visual cursor overlay with its default style")]
pub cursor: bool,
+ #[arg(
+ long,
+ requires = "cursor",
+ help = "Give each harness subagent its own cursor; requires --agent-id on desktop actions"
+ )]
+ pub multi_agent: bool,
}
#[derive(Args, Debug)]
diff --git a/src/command_policy/mod.rs b/src/command_policy/mod.rs
index 66479810b..4fb89d974 100644
--- a/src/command_policy/mod.rs
+++ b/src/command_policy/mod.rs
@@ -110,6 +110,24 @@ pub(crate) fn preflight(cmd: &Commands, report: &PermissionReport) -> Result<(),
Ok(())
}
+pub(crate) fn preflight_context(
+ cmd: &Commands,
+ context: &agent_desktop_core::context::CommandContext,
+) -> Result<(), AppError> {
+ if cfg!(target_os = "macos")
+ && context.multi_agent()
+ && context.agent_id().is_none()
+ && cmd.is_mutating()
+ && policy_for(cmd) == PermissionNeed::Accessibility
+ {
+ return Err(AppError::invalid_input_with_suggestion(
+ "Multi-agent sessions require --agent-id for desktop actions",
+ "Set --agent-id or AGENT_DESKTOP_AGENT_ID before running the command.",
+ ));
+ }
+ Ok(())
+}
+
pub(crate) fn requires_permission_report(cmd: &Commands) -> bool {
policy_for(cmd) != PermissionNeed::None
|| matches!(
diff --git a/src/dispatch/app_window.rs b/src/dispatch/app_window.rs
index 736e9efd8..d2a5ccef5 100644
--- a/src/dispatch/app_window.rs
+++ b/src/dispatch/app_window.rs
@@ -3,10 +3,10 @@ use agent_desktop_core::{
commands::{
close_app as close_app_command, focus_window as focus_window_command, helpers,
launch as launch_command, list_apps as list_apps_command,
- list_displays as list_displays_command, list_surfaces as list_surfaces_command,
- list_windows as list_windows_command, maximize as maximize_command,
- minimize as minimize_command, move_window as move_window_command,
- resize_window as resize_window_command, restore as restore_command,
+ list_surfaces as list_surfaces_command, list_windows as list_windows_command,
+ maximize as maximize_command, minimize as minimize_command,
+ move_window as move_window_command, resize_window as resize_window_command,
+ restore as restore_command,
},
};
use serde_json::Value;
@@ -53,10 +53,6 @@ pub(super) fn list_windows(
)
}
-pub(super) fn list_displays(adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
- list_displays_command::execute(adapter)
-}
-
pub(super) fn list_apps(
args: ListAppsArgs,
adapter: &dyn PlatformAdapter,
diff --git a/src/dispatch/clipboard.rs b/src/dispatch/clipboard.rs
index 5291f05f8..4c19002e2 100644
--- a/src/dispatch/clipboard.rs
+++ b/src/dispatch/clipboard.rs
@@ -1,6 +1,6 @@
use agent_desktop_core::{
AppError, PlatformAdapter,
- commands::{clipboard_clear, clipboard_get, clipboard_set},
+ commands::{clipboard_get, clipboard_set},
context::CommandContext,
};
use serde_json::Value;
@@ -40,7 +40,3 @@ pub(super) fn set(
adapter,
)
}
-
-pub(super) fn clear(adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
- clipboard_clear::execute(adapter)
-}
diff --git a/src/dispatch/cursor_overlay.rs b/src/dispatch/cursor_overlay.rs
index 9ed13a882..39e75af27 100644
--- a/src/dispatch/cursor_overlay.rs
+++ b/src/dispatch/cursor_overlay.rs
@@ -21,12 +21,31 @@ pub(crate) fn dispatch(
})?;
let (action, control) = match args.action {
CursorOverlayAction::Enable(args) => {
- let config = args.to_core()?;
+ let multi_agent = args.multi_agent || context.multi_agent();
+ let config = args.to_core()?.with_multi_agent(multi_agent);
+ let agent_id = context.agent_id().map(str::to_owned);
+ if let Some(agent_id) = agent_id.as_deref() {
+ if args.multi_agent {
+ return Err(AppError::invalid_input(
+ "--multi-agent configures the session; omit --agent-id",
+ ));
+ }
+ agent_desktop_core::session::save_cursor_overlay_profile(
+ session_id,
+ agent_id,
+ config.clone(),
+ )?;
+ return Ok(serde_json::json!({
+ "session_id": session_id,
+ "cursor_overlay": config,
+ "agent_id": agent_id,
+ }));
+ }
let control =
CursorOverlayControl::enable(session_id.to_owned(), config.style().clone());
(
cursor_overlay::CursorOverlayAction::Enable(config),
- Some(control),
+ (!multi_agent).then_some(control),
)
}
CursorOverlayAction::Disable => (
@@ -38,7 +57,24 @@ pub(crate) fn dispatch(
if let Some(control) = control
&& let Err(error) = adapter.update_cursor_overlay(&control)
{
+ if control.is_disable() {
+ return Err(teardown_error(error));
+ }
tracing::warn!(code = %error.code.as_str(), "cursor overlay lifecycle update was skipped");
}
Ok(value)
}
+
+pub(super) fn teardown_error(mut error: agent_desktop_core::AdapterError) -> AppError {
+ error.message = format!(
+ "Session state was saved, but cursor teardown was not confirmed: {}",
+ error.message
+ );
+ error
+ .with_disposition(agent_desktop_core::DeliverySemantics::uncertain())
+ .into()
+}
+
+#[cfg(test)]
+#[path = "cursor_overlay_tests.rs"]
+mod tests;
diff --git a/src/dispatch/cursor_overlay_tests.rs b/src/dispatch/cursor_overlay_tests.rs
new file mode 100644
index 000000000..fb484ccbd
--- /dev/null
+++ b/src/dispatch/cursor_overlay_tests.rs
@@ -0,0 +1,46 @@
+use super::dispatch;
+use crate::cli_args::cursor_overlay::CursorOverlayArgs;
+use crate::cli_args::cursor_overlay_action::CursorOverlayAction;
+use crate::dispatch::test_support::{FailingOverlayAdapter, HomeGuard};
+use agent_desktop_core::context::CommandContext;
+use agent_desktop_core::session::{ArtifactsMode, SessionTraceMode, StartSessionOptions};
+
+#[test]
+fn disable_reports_uncertain_when_overlay_teardown_fails_after_persisting() {
+ let home = HomeGuard::new();
+ let manifest = agent_desktop_core::session::start_session(StartSessionOptions {
+ trace: SessionTraceMode::Off,
+ artifacts: ArtifactsMode::Events,
+ name: None,
+ })
+ .unwrap();
+ agent_desktop_core::session::set_cursor_overlay(
+ &manifest.id,
+ agent_desktop_core::CursorOverlayConfig::enabled(None, 6).unwrap(),
+ )
+ .unwrap();
+ let context = CommandContext::new(Some(manifest.id.clone()), None, false).unwrap();
+ let result = dispatch(
+ CursorOverlayArgs {
+ action: CursorOverlayAction::Disable,
+ },
+ &FailingOverlayAdapter,
+ &context,
+ );
+
+ let error = result.expect_err("failed teardown must be surfaced");
+ assert_eq!(error.code(), "ACTION_FAILED");
+ assert!(error.to_string().contains("Session state was saved"));
+ let agent_desktop_core::AppError::Adapter(adapter_error) = &error else {
+ panic!("teardown failure must preserve adapter disposition");
+ };
+ assert_eq!(
+ adapter_error.disposition,
+ agent_desktop_core::DeliverySemantics::uncertain()
+ );
+ let saved = agent_desktop_core::session::read_manifest(&manifest.id)
+ .unwrap()
+ .expect("manifest remains readable");
+ assert_eq!(saved.cursor_overlay, Default::default());
+ assert!(home.path().join("sessions").join(manifest.id).is_dir());
+}
diff --git a/src/dispatch/mod.rs b/src/dispatch/mod.rs
index 991d65df3..39110623a 100644
--- a/src/dispatch/mod.rs
+++ b/src/dispatch/mod.rs
@@ -10,8 +10,11 @@ mod session;
mod system;
mod trace;
+#[cfg(test)]
+mod test_support;
+
use agent_desktop_core::{
- AppError, CursorOverlayControl, PermissionReport, PlatformAdapter, context::CommandContext,
+ AppError, PermissionReport, PlatformAdapter, commands, context::CommandContext,
};
use serde_json::Value;
@@ -24,20 +27,11 @@ pub(crate) fn dispatch(
context: &CommandContext,
) -> Result<Value, AppError> {
tracing::debug!("dispatch: {}", cmd.name());
- let overlay_session =
- if cmd.is_mutating() && context.is_headed() && context.cursor_overlay().is_enabled() {
- context.session_id().map(str::to_owned)
- } else {
- None
- };
let scope = if cmd.is_mutating() {
context.mutating_command_scope(cmd.name())?
} else {
context.command_scope(cmd.name())?
};
- if let Some(session_id) = overlay_session.as_ref() {
- let _ = adapter.update_cursor_overlay(&CursorOverlayControl::hide(session_id.clone()));
- }
let result = match cmd {
Commands::Snapshot(args) => observation::snapshot(args, adapter, context),
Commands::Find(args) => observation::find(args, adapter, context),
@@ -73,7 +67,7 @@ pub(crate) fn dispatch(
Commands::Launch(args) => app_window::launch(args, adapter),
Commands::CloseApp(args) => app_window::close_app(args, adapter),
Commands::ListWindows(args) => app_window::list_windows(args, adapter),
- Commands::ListDisplays => app_window::list_displays(adapter),
+ Commands::ListDisplays => commands::list_displays::execute(adapter),
Commands::ListApps(args) => app_window::list_apps(args, adapter),
Commands::FocusWindow(args) => app_window::focus_window(args, adapter),
Commands::ResizeWindow(args) => app_window::resize_window(args, adapter),
@@ -90,20 +84,19 @@ pub(crate) fn dispatch(
Commands::NotificationAction(args) => notifications::action(args, adapter, context),
Commands::ClipboardGet(args) => clipboard::get(args, adapter, context),
Commands::ClipboardSet(args) => clipboard::set(args, adapter),
- Commands::ClipboardClear => clipboard::clear(adapter),
+ Commands::ClipboardClear => commands::clipboard_clear::execute(adapter),
Commands::Wait(args) => system::wait(args, adapter, context),
- Commands::Status => system::status(adapter, permission_report, context),
+ Commands::Status => {
+ commands::status::execute_with_report_with_context(adapter, permission_report, context)
+ }
Commands::Permissions(args) => system::permissions(args, adapter, permission_report),
- Commands::Version => system::version(),
- Commands::Batch(args) => system::batch(args, adapter, permission_report, context),
+ Commands::Version => commands::version::execute(),
+ Commands::Batch(args) => crate::batch::execute(args, adapter, permission_report, context),
Commands::Skills(args) => system::skills(args),
- Commands::Session(args) => system::session(args, adapter, context),
+ Commands::Session(args) => session::dispatch(args, adapter, context),
Commands::CursorOverlay(args) => cursor_overlay::dispatch(args, adapter, context),
- Commands::Trace(args) => system::trace(args, context),
+ Commands::Trace(args) => trace::dispatch(args, context),
};
- if let Some(session_id) = overlay_session {
- let _ = adapter.update_cursor_overlay(&CursorOverlayControl::show(session_id));
- }
scope.complete(&result)?;
result
}
diff --git a/src/dispatch/session.rs b/src/dispatch/session.rs
index 49ab89be0..546aa3003 100644
--- a/src/dispatch/session.rs
+++ b/src/dispatch/session.rs
@@ -21,14 +21,16 @@ pub(crate) fn dispatch(
screenshots: s.screenshots,
})?;
if show_cursor {
- show_default_cursor(adapter, &mut value)?;
+ show_default_cursor(adapter, &mut value, s.multi_agent)?;
}
Ok(value)
}
SessionAction::End(e) => {
let id = resolve_end_session_id(e.id, context.session_id())?;
let value = session::execute(session::SessionAction::End { id: id.clone() })?;
- let _ = adapter.update_cursor_overlay(&CursorOverlayControl::disable(id));
+ adapter
+ .update_cursor_overlay(&CursorOverlayControl::disable(id))
+ .map_err(super::cursor_overlay::teardown_error)?;
Ok(value)
}
SessionAction::List => session::execute(session::SessionAction::List),
@@ -39,7 +41,11 @@ pub(crate) fn dispatch(
}
}
-fn show_default_cursor(adapter: &dyn PlatformAdapter, value: &mut Value) -> Result<(), AppError> {
+fn show_default_cursor(
+ adapter: &dyn PlatformAdapter,
+ value: &mut Value,
+ multi_agent: bool,
+) -> Result<(), AppError> {
let Some(id) = value
.get("session_id")
.and_then(Value::as_str)
@@ -47,7 +53,7 @@ fn show_default_cursor(adapter: &dyn PlatformAdapter, value: &mut Value) -> Resu
else {
return Ok(());
};
- let config = CursorOverlayConfig::enabled(None, 6)?;
+ let config = CursorOverlayConfig::enabled(None, 6)?.with_multi_agent(multi_agent);
let control = CursorOverlayControl::enable(id.clone(), config.style().clone());
let enabled =
cursor_overlay::execute(&id, cursor_overlay::CursorOverlayAction::Enable(config))?;
@@ -56,6 +62,9 @@ fn show_default_cursor(adapter: &dyn PlatformAdapter, value: &mut Value) -> Resu
{
map.insert("cursor_overlay".into(), overlay);
}
+ if multi_agent {
+ return Ok(());
+ }
if let Err(error) = adapter.update_cursor_overlay(&control) {
tracing::warn!(code = %error.code.as_str(), "cursor overlay lifecycle update was skipped");
}
diff --git a/src/dispatch/session_tests.rs b/src/dispatch/session_tests.rs
index 9de54c281..9338c12e9 100644
--- a/src/dispatch/session_tests.rs
+++ b/src/dispatch/session_tests.rs
@@ -1,4 +1,8 @@
use super::resolve_end_session_id;
+use crate::cli_args::session::{SessionAction, SessionArgs, SessionEndArgs};
+use crate::dispatch::test_support::{FailingOverlayAdapter, HomeGuard};
+use agent_desktop_core::context::CommandContext;
+use agent_desktop_core::session::{ArtifactsMode, SessionTraceMode, StartSessionOptions};
#[test]
fn explicit_session_end_id_precedes_active_scope() {
@@ -23,3 +27,39 @@ fn session_end_without_any_scope_is_invalid() {
assert_eq!(error.code(), "INVALID_ARGS");
assert!(error.to_string().contains("No session id"));
}
+
+#[test]
+fn session_end_reports_uncertain_when_overlay_teardown_fails_after_persisting() {
+ let home = HomeGuard::new();
+ let manifest = agent_desktop_core::session::start_session(StartSessionOptions {
+ trace: SessionTraceMode::Off,
+ artifacts: ArtifactsMode::Events,
+ name: None,
+ })
+ .unwrap();
+ let result = super::dispatch(
+ SessionArgs {
+ action: SessionAction::End(SessionEndArgs {
+ id: Some(manifest.id.clone()),
+ }),
+ },
+ &FailingOverlayAdapter,
+ &CommandContext::default(),
+ );
+
+ let error = result.expect_err("failed teardown must be surfaced");
+ assert_eq!(error.code(), "ACTION_FAILED");
+ assert!(error.to_string().contains("Session state was saved"));
+ let agent_desktop_core::AppError::Adapter(adapter_error) = &error else {
+ panic!("teardown failure must preserve adapter disposition");
+ };
+ assert_eq!(
+ adapter_error.disposition,
+ agent_desktop_core::DeliverySemantics::uncertain()
+ );
+ let ended = agent_desktop_core::session::read_manifest(&manifest.id)
+ .unwrap()
+ .expect("manifest remains readable");
+ assert!(ended.ended_at.is_some());
+ assert!(home.path().join("sessions").join(manifest.id).is_dir());
+}
diff --git a/src/dispatch/system.rs b/src/dispatch/system.rs
index 49972553a..f658b1578 100644
--- a/src/dispatch/system.rs
+++ b/src/dispatch/system.rs
@@ -1,21 +1,17 @@
use agent_desktop_core::{
AppError, PermissionReport, PlatformAdapter,
commands::{
- permissions as permissions_command, skills as skills_command, status as status_command,
- version as version_command, wait as wait_command, wait_surface::SurfaceWait,
+ permissions as permissions_command, skills as skills_command, wait as wait_command,
+ wait_surface::SurfaceWait,
},
context::CommandContext,
};
use serde_json::Value;
use crate::cli_args::{
- batch::BatchArgs,
- session::SessionArgs,
skills::{SkillsAction, SkillsArgs},
system::{PermissionsArgs, WaitArgs},
- trace::TraceArgs,
};
-use crate::dispatch::{session as session_dispatch, trace as trace_dispatch};
pub(super) fn wait(
args: WaitArgs,
@@ -52,14 +48,6 @@ pub(super) fn wait(
)
}
-pub(super) fn status(
- adapter: &dyn PlatformAdapter,
- permission_report: &PermissionReport,
- context: &CommandContext,
-) -> Result<Value, AppError> {
- status_command::execute_with_report_with_context(adapter, permission_report, context)
-}
-
pub(super) fn permissions(
args: PermissionsArgs,
adapter: &dyn PlatformAdapter,
@@ -74,10 +62,6 @@ pub(super) fn permissions(
)
}
-pub(super) fn version() -> Result<Value, AppError> {
- version_command::execute()
-}
-
pub(super) fn skills(args: SkillsArgs) -> Result<Value, AppError> {
match args.action.unwrap_or(SkillsAction::List) {
SkillsAction::List => skills_command::list(),
@@ -89,24 +73,3 @@ pub(super) fn skills(args: SkillsArgs) -> Result<Value, AppError> {
}),
}
}
-
-pub(super) fn session(
- args: SessionArgs,
- adapter: &dyn PlatformAdapter,
- context: &CommandContext,
-) -> Result<Value, AppError> {
- session_dispatch::dispatch(args, adapter, context)
-}
-
-pub(super) fn trace(args: TraceArgs, context: &CommandContext) -> Result<Value, AppError> {
- trace_dispatch::dispatch(args, context)
-}
-
-pub(super) fn batch(
- args: BatchArgs,
- adapter: &dyn PlatformAdapter,
- permission_report: &PermissionReport,
- context: &CommandContext,
-) -> Result<Value, AppError> {
- crate::batch::execute(args, adapter, permission_report, context)
-}
diff --git a/src/dispatch/test_support.rs b/src/dispatch/test_support.rs
new file mode 100644
index 000000000..8508c3d8d
--- /dev/null
+++ b/src/dispatch/test_support.rs
@@ -0,0 +1,65 @@
+use std::path::PathBuf;
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use agent_desktop_core::{ActionOps, AdapterError, ErrorCode, InputOps, ObservationOps, SystemOps};
+
+static HOME_LOCK: Mutex<()> = Mutex::new(());
+static HOME_ID: AtomicU64 = AtomicU64::new(1);
+
+pub(crate) struct HomeGuard {
+ lock: Option<std::sync::MutexGuard<'static, ()>>,
+ previous: Option<std::ffi::OsString>,
+ path: PathBuf,
+}
+
+impl HomeGuard {
+ pub(crate) fn new() -> Self {
+ let lock = HOME_LOCK.lock().unwrap();
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-dispatch-test-{}-{}",
+ std::process::id(),
+ HOME_ID.fetch_add(1, Ordering::Relaxed)
+ ));
+ std::fs::create_dir_all(&path).unwrap();
+ let previous = std::env::var_os("AGENT_DESKTOP_HOME");
+ unsafe { std::env::set_var("AGENT_DESKTOP_HOME", &path) };
+ Self {
+ lock: Some(lock),
+ previous,
+ path,
+ }
+ }
+
+ pub(crate) fn path(&self) -> &std::path::Path {
+ &self.path
+ }
+}
+
+impl Drop for HomeGuard {
+ fn drop(&mut self) {
+ match self.previous.take() {
+ Some(previous) => unsafe { std::env::set_var("AGENT_DESKTOP_HOME", previous) },
+ None => unsafe { std::env::remove_var("AGENT_DESKTOP_HOME") },
+ }
+ self.lock.take();
+ }
+}
+
+pub(crate) struct FailingOverlayAdapter;
+
+impl ObservationOps for FailingOverlayAdapter {}
+impl ActionOps for FailingOverlayAdapter {}
+impl InputOps for FailingOverlayAdapter {}
+
+impl SystemOps for FailingOverlayAdapter {
+ fn update_cursor_overlay(
+ &self,
+ _control: &agent_desktop_core::CursorOverlayControl,
+ ) -> Result<(), AdapterError> {
+ Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "overlay teardown failed",
+ ))
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 299cc14ae..82b301a03 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -129,7 +129,7 @@ fn run() -> ExitCode {
Err(error) => return finish(cmd_name, Err(error)),
};
let session_id = match resolve_active_session(
- cli.session.as_deref(),
+ cli.identity.session.as_deref(),
std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref(),
) {
Ok(session_id) => session_id,
@@ -145,6 +145,15 @@ fn run() -> ExitCode {
return finish(cmd_name, Err(pre_dispatch_error(err)));
}
};
+ let agent_id = cli
+ .identity
+ .agent_id
+ .clone()
+ .or_else(|| std::env::var("AGENT_DESKTOP_AGENT_ID").ok());
+ let context = match context.with_agent_id(agent_id) {
+ Ok(context) => context,
+ Err(err) => return finish(cmd_name, Err(pre_dispatch_error(err))),
+ };
if let Some(wait) = wait_selector.as_ref() {
if let Err(err) = validate_wait_for_command(&cmd, wait) {
return finish(cmd_name, Err(err));
@@ -214,6 +223,9 @@ fn run_with_adapter(cmd: Commands, cmd_name: &str, context: &CommandContext) ->
if let Err(err) = command_policy::preflight(&cmd, &report) {
return finish(cmd_name, Err(err));
}
+ if let Err(err) = command_policy::preflight_context(&cmd, context) {
+ return finish(cmd_name, Err(err));
+ }
let result = dispatch::dispatch(cmd, adapter, &report, context);
finish(cmd_name, result)
diff --git a/src/tests/cli_process.rs b/src/tests/cli_process.rs
index d2a9a1084..c685dc32d 100644
--- a/src/tests/cli_process.rs
+++ b/src/tests/cli_process.rs
@@ -218,3 +218,133 @@ fn malformed_permission_helper_invocation_bypasses_clap_and_tracing() {
assert_eq!(response["ok"], false);
assert_eq!(response["error"], "invalid_helper_invocation");
}
+
+#[test]
+fn agent_identity_flag_overrides_environment_and_rejects_invalid_ids() {
+ let output = binary()
+ .args(["--agent-id", "worker-a", "session", "list"])
+ .env("AGENT_DESKTOP_AGENT_ID", "../invalid")
+ .env_remove("AGENT_DESKTOP_SESSION")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+ let output = binary()
+ .args(["session", "list"])
+ .env("AGENT_DESKTOP_AGENT_ID", "../invalid")
+ .env_remove("AGENT_DESKTOP_SESSION")
+ .output()
+ .unwrap();
+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(response["error"]["code"], "INVALID_ARGS");
+}
+
+#[cfg(unix)]
+fn create_private_dir(dir: &std::path::Path) {
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(dir)
+ .expect("create state root");
+}
+
+#[cfg(not(unix))]
+fn create_private_dir(dir: &std::path::Path) {
+ std::fs::create_dir_all(dir).expect("create state root");
+}
+
+#[test]
+fn batch_entry_after_mid_batch_session_end_is_skipped_without_aborting_batch() {
+ let dir = std::env::temp_dir().join(format!(
+ "agent-desktop-cli-batch-session-end-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ create_private_dir(&dir);
+ let start = binary()
+ .args(["session", "start", "--no-trace"])
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("binary starts");
+ let start_envelope: serde_json::Value =
+ serde_json::from_slice(&start.stdout).expect("stdout is one JSON envelope");
+ assert!(start.status.success());
+ let session_id = start_envelope["data"]["session_id"]
+ .as_str()
+ .expect("session start returns a session id")
+ .to_owned();
+ let commands = serde_json::json!([
+ {"command": "session", "session": session_id, "args": {"action": "end"}},
+ {"command": "clipboard-clear", "session": session_id, "args": {}},
+ {"command": "version", "args": {}},
+ ]);
+ let output = binary()
+ .arg("batch")
+ .arg(commands.to_string())
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("binary starts");
+ let envelope: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("stdout is one JSON envelope");
+
+ assert!(output.status.success());
+ assert_eq!(envelope["ok"], true);
+ let data = &envelope["data"];
+ assert_eq!(data["results"][0]["execution"], "completed");
+ assert_eq!(data["results"][0]["ok"], true);
+ assert_eq!(data["results"][0]["data"]["session_id"], session_id);
+ assert!(data["results"][0]["data"]["ended_at"].is_number());
+ assert_eq!(data["results"][1]["execution"], "not_started");
+ assert_eq!(data["results"][1]["not_started_reason"], "session_ended");
+ assert_eq!(data["results"][1]["ok"], false);
+ assert_eq!(data["results"][1]["error"]["code"], "INVALID_ARGS");
+ assert!(
+ data["results"][1]["error"]["message"]
+ .as_str()
+ .is_some_and(|message| message.contains(session_id.as_str()))
+ );
+ assert_eq!(data["results"][2]["execution"], "completed");
+ assert_eq!(data["results"][2]["ok"], true);
+ assert_eq!(data["total_entries"], 3);
+ assert_eq!(data["completed_entries"], 2);
+ assert_eq!(data["not_started_entries"], 1);
+ assert!(data.get("stopped").is_none());
+ let start = binary()
+ .args(["session", "start", "--no-trace"])
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("new session starts");
+ let new_session: serde_json::Value = serde_json::from_slice(&start.stdout).unwrap();
+ let next_id = new_session["data"]["session_id"].as_str().unwrap();
+ let stopped = binary()
+ .arg("batch")
+ .arg(
+ serde_json::json!([
+ {"command": "session", "session": next_id, "args": {"action": "end"}},
+ {"command": "version", "session": next_id, "args": {}},
+ {"command": "version", "args": {}}
+ ])
+ .to_string(),
+ )
+ .arg("--stop-on-error")
+ .env("AGENT_DESKTOP_HOME", &dir)
+ .output()
+ .expect("batch starts");
+ let stopped: serde_json::Value = serde_json::from_slice(&stopped.stdout).unwrap();
+ assert_eq!(stopped["data"]["stopped"]["reason"], "stop_on_error");
+ assert_eq!(stopped["data"]["results"].as_array().unwrap().len(), 2);
+ let manifest: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(dir.join("sessions").join(&session_id).join("session.json"))
+ .expect("ended manifest remains on disk"),
+ )
+ .expect("manifest is JSON");
+ assert!(manifest["ended_at"].is_number());
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/tests/e2e/run.sh b/tests/e2e/run.sh
index 2bd55dab2..e2e815f85 100755
--- a/tests/e2e/run.sh
+++ b/tests/e2e/run.sh
@@ -136,4 +136,23 @@ source "$here/scenarios/trace_performance.sh"
# shellcheck source=tests/e2e/scenarios/notifications.sh
source "$here/scenarios/notifications.sh"
+note "Multi-agent cursor probe"
+if "$bin" close-app "$app" --force >/dev/null 2>&1; then
+ fixture_owned=0
+ for mode in headless headed; do
+ cursor_flags=()
+ if [[ "$mode" == headed ]]; then cursor_flags=(--headed); fi
+ if python3 "$repo/scripts/cursor-multi-agent-probe.py" \
+ --bin "$raw_bin" \
+ --fixture "$fixture_app/Contents/MacOS/AgentDeskFixture" \
+ --out "$suite_root/multi-agent-cursor-$mode" "${cursor_flags[@]}"; then
+ okmsg "$mode multi-agent cursors share session state and preserve renderer isolation"
+ else
+ badmsg "$mode multi-agent cursor probe failed"
+ fi
+ done
+else
+ badmsg "fixture could not be restarted for the multi-agent cursor probe"
+fi
+
finish
diff --git a/tests/e2e/test_harness_contract.py b/tests/e2e/test_harness_contract.py
index 11e2f9fac..db53c5f7f 100644
--- a/tests/e2e/test_harness_contract.py
+++ b/tests/e2e/test_harness_contract.py
@@ -55,31 +55,6 @@ class HarnessContractTests(unittest.TestCase):
self.assertEqual(offenders, [])
- def test_wait_scenarios_use_independent_oracles(self):
- source = (E2E_ROOT / "scenarios" / "reliability.sh").read_text()
-
- self.assertIn('is_target "$delayed" enabled', source)
- self.assertIn('is_target "$primary" visible', source)
- self.assertIn('get_target "$text_input" --property value', source)
- self.assertIn("require_value actionable_before click-status", source)
- self.assertIn("require_value actionable_after click-status", source)
-
- def test_acceptance_visibility_uses_a_qualified_zero_bounds_ref(self):
- source = (E2E_ROOT / "scenarios" / "acceptance.sh").read_text()
-
- self.assertIn("require_target zero_target button zero-bounds-button", source)
- self.assertIn('is_target "$zero_target" visible', source)
- self.assertIn('data.applicable)" = "True"', source)
- self.assertIn('data.result)" = "False"', source)
-
- def test_hover_uses_the_headed_qualified_ref_pipeline(self):
- source = (E2E_ROOT / "scenarios" / "interaction.sh").read_text()
-
- self.assertIn("require_target hover_target button hover-target", source)
- self.assertIn('act_target "$hover_target" hover', source)
- self.assertIn("require_value hover_after hover-status", source)
- self.assertNotIn("hover --xy", source)
-
def test_denied_automation_skips_when_notification_center_cannot_be_closed(self):
source = (E2E_ROOT / "scenarios" / "acceptance.sh").read_text()
@@ -102,6 +77,15 @@ class HarnessContractTests(unittest.TestCase):
focused_fixture = source.index("prepare_native_harness")
self.assertLess(safe_gate, focused_fixture)
+ def test_multi_agent_probe_runs_before_the_interaction_lease_is_released(self):
+ source = (E2E_ROOT / "run.sh").read_text()
+ probe = source.index("cursor-multi-agent-probe.py")
+ finish = source.index("\nfinish", probe)
+ self.assertLess(probe, finish)
+
+ probe_source = (E2E_ROOT.parent.parent / "scripts/cursor-multi-agent-probe.py").read_text()
+ self.assertIn("pass_fds=cli_pass_fds", probe_source)
+
def test_native_runner_builds_locked_canonical_artifacts_before_desktop_lock(self):
source = (E2E_ROOT / "run.sh").read_text()
@@ -171,41 +155,6 @@ cleanup
self.assertLess(body.index('verify_immutable_binary "$ffi_dylib"'), decision)
self.assertLess(body.index('verify_immutable_binary "$ffi_helper"'), decision)
- def test_fixture_status_oracles_use_stable_native_identifiers(self):
- source = (E2E_ROOT / "lib.sh").read_text()
-
- self.assertIn('--role statictext --native-id "$name" --first', source)
-
- def test_trace_artifact_actions_use_the_session_that_created_their_refs(self):
- source = (E2E_ROOT / "scenarios" / "trace_performance.sh").read_text()
-
- self.assertIn('"$bin" --session "$trace_session" find', source)
- self.assertIn('trace_click="$("$bin" --session "$trace_session" click', source)
- self.assertIn(
- 'trace_session_type="$("$bin" --headed --session "$trace_session" type',
- source,
- )
-
- def test_sheet_scenarios_scroll_the_button_before_clicking(self):
- fixtures = [
- (
- "scenarios/surfaces.sh",
- 'act_target "$open_sheet" scroll-to',
- 'act_target "$open_sheet" click',
- ),
- (
- "scenarios/acceptance.sh",
- 'act_target "$open_sheet" scroll-to',
- 'batch_payload="$(python3',
- ),
- ]
- for filename, scroll_marker, click_marker in fixtures:
- with self.subTest(filename=filename):
- source = (E2E_ROOT / filename).read_text()
- scroll = source.index(scroll_marker)
- click = source.index(click_marker)
- self.assertLess(scroll, click)
-
def test_recoverable_trash_moves_artifact_with_available_backend(self):
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
diff --git a/tests/e2e/test_interaction_lock.py b/tests/e2e/test_interaction_lock.py
index 737661f9b..abe071317 100644
--- a/tests/e2e/test_interaction_lock.py
+++ b/tests/e2e/test_interaction_lock.py
@@ -42,6 +42,29 @@ class InteractionLockTests(unittest.TestCase):
os.close(fd)
self.assertEqual(self.probe(path), 0)
+ def test_inherited_holder_can_forward_lease_to_a_child(self):
+ with tempfile.TemporaryDirectory() as root:
+ fd = interaction_lock.acquire(root)
+ self.assertIsNotNone(fd)
+ environment = os.environ.copy()
+ environment[interaction_lock.LEASE_FD_ENV] = str(fd)
+ forwarder = """
+import os, subprocess, sys
+fd = int(os.environ['AGENT_DESKTOP_INTERACTION_LEASE_FD'])
+subprocess.run(
+ [sys.executable, '-c', 'import os,sys; os.fstat(int(sys.argv[1]))', str(fd)],
+ pass_fds=(fd,),
+ check=True,
+)
+"""
+ subprocess.run(
+ [sys.executable, "-c", forwarder],
+ env=environment,
+ pass_fds=(fd,),
+ check=True,
+ )
+ os.close(fd)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/native/cursor_overlay_trail_test.m b/tests/native/cursor_overlay_trail_test.m
new file mode 100644
index 000000000..e6f7c0257
--- /dev/null
+++ b/tests/native/cursor_overlay_trail_test.m
@@ -0,0 +1,43 @@
+#import "../../crates/macos/src/system/cursor_overlay_chrome_bridge.m"
+#import "../../crates/macos/src/system/cursor_overlay_display_bridge.m"
+#import "../../crates/macos/src/system/cursor_overlay_bridge.m"
+
+static void require(bool condition, const char *message) {
+ if (!condition) {
+ fprintf(stderr, "%s\n", message);
+ exit(1);
+ }
+}
+
+int main(void) {
+ @autoreleasepool {
+ [NSApplication sharedApplication];
+ NSRect desktop = NSMakeRect(0.0, 0.0, 800.0, 600.0);
+ NSPoint start = NSMakePoint(NSMidX(desktop) - 20.0, NSMidY(desktop));
+ NSPoint end = NSMakePoint(start.x + 40.0, start.y + 20.0);
+
+ ADTrailBeginInFrame(start, desktop);
+ ADTrailAppend(end);
+ require(ADTrailWindow != nil && ADTrailLayer.path != NULL, "trail must be visible");
+ require(ADTrailWindow.frame.size.width < desktop.size.width &&
+ ADTrailWindow.frame.size.height < desktop.size.height,
+ "trail window must stay bounded to the path");
+ CGRect bounds = CGPathGetBoundingBox(ADTrailLayer.path);
+ require(bounds.size.width >= 40.0 && bounds.size.height >= 20.0,
+ "trail path must contain the sampled movement");
+
+ ADTrailFinish(0.9);
+ CAAnimation *fade = [ADTrailLayer animationForKey:@"agent-drag-trail-fade"];
+ require(fade != nil && fabs(fade.duration - 0.9) < 0.001,
+ "trail must use the requested fade duration");
+ ADTrailStop();
+ require(ADTrailWindow == nil && ADTrailLayer == nil && ADTrailPath == NULL,
+ "trail stop must release native state");
+
+ agent_desktop_cursor_overlay_drag_begin(start.x, start.y, false);
+ require(agent_desktop_cursor_overlay_drag_active(), "drag begin must arm tracking");
+ agent_desktop_cursor_overlay_drag_end(end.x, end.y, false);
+ require(!agent_desktop_cursor_overlay_drag_active(), "drag cancel must disarm tracking");
+ }
+ return 0;
+}