Skip to content

Computer use CLI for AI agents

fix: honor windows scroll viewports and native input effects

Lahfir628e9536a670
diff --git a/crates/windows/src/actions/scroll_into_view.rs b/crates/windows/src/actions/scroll_into_view.rs
index 718228ecd..4fcb94309 100644
--- a/crates/windows/src/actions/scroll_into_view.rs
+++ b/crates/windows/src/actions/scroll_into_view.rs
@@ -95,7 +95,11 @@ mod imp {
match scroll_into_view_judged_for(deadline, before, invoke_failure, VERIFY_WINDOW, || {
observe_visibility(
element,
- viewport.as_ref().and_then(viewport_bounds),
+ viewport
+ .as_ref()
+ .map(viewport_bounds)
+ .transpose()?
+ .flatten(),
deadline,
"after ScrollIntoView",
)
diff --git a/crates/windows/src/actions/scroll_ladder.rs b/crates/windows/src/actions/scroll_ladder.rs
index 91897bca6..77c60a0ec 100644
--- a/crates/windows/src/actions/scroll_ladder.rs
+++ b/crates/windows/src/actions/scroll_ladder.rs
@@ -4,44 +4,42 @@
//! Direction comes from the target's fresh bounds against the nearest
//! ScrollPattern-available ancestor viewport (macOS `direction_for_visibility`
//! parity). Visibility uses the shipped ScrollIntoView predicate — IsOffscreen
-//! false, positive-area bounds, and viewport intersection — because provider
+//! false, positive-area bounds, and viewport containment when the target fits — because provider
//! rects are unclipped (A18-2).
use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics, Direction, ErrorCode, Rect};
use crate::actions::chain::DeliveryOutcome;
-use crate::actions::scroll::SCROLL_LABEL;
use crate::system::permissions::ensure_budget;
use crate::tree::element::UIAElement;
pub(crate) const MAX_ANCESTOR_SCROLLS: usize = 10;
-pub(crate) const LADDER_SCROLL_LABEL: &str = SCROLL_LABEL;
+pub(crate) const LADDER_SCROLL_LABEL: &str = "ScrollPattern";
-/// Bring-into-view step size for the ladder, deliberately larger than the
-/// direct `scroll` command's `SmallIncrement`/`SmallDecrement` nudge
-/// (`crate::actions::scroll::scroll_amounts`). Measured live against the
-/// Windows fixture's own AutoScroll form: a `SmallDecrement` rung moved the
-/// target 5px, so the 10-rung budget covered 50px total against a target
-/// that a single native-focus jump had displaced 1361px — an ancestor with
-/// real distance to cover exhausted every rung and still reported
-/// `ACTION_FAILED` on a target that was never occluded, only never reached.
-/// `LargeIncrement`/`LargeDecrement` map to a page-sized native scroll step,
-/// so the same MAX_ANCESTOR_SCROLLS budget covers a page's multiple.
+/// Center the target without page-sized oscillation; view size is percent of content.
#[cfg(target_os = "windows")]
-pub(crate) fn ladder_scroll_amounts(
- direction: &Direction,
-) -> (
- uiautomation::types::ScrollAmount,
- uiautomation::types::ScrollAmount,
-) {
- use uiautomation::types::ScrollAmount;
-
- match direction {
- Direction::Down => (ScrollAmount::NoAmount, ScrollAmount::LargeIncrement),
- Direction::Up => (ScrollAmount::NoAmount, ScrollAmount::LargeDecrement),
- Direction::Right => (ScrollAmount::LargeIncrement, ScrollAmount::NoAmount),
- Direction::Left => (ScrollAmount::LargeDecrement, ScrollAmount::NoAmount),
+pub(crate) fn centered_scroll_percent(
+ current: f64,
+ view_percent: f64,
+ viewport_extent: f64,
+ offset: f64,
+) -> Result<f64, AdapterError> {
+ if !current.is_finite()
+ || !(0.0..=100.0).contains(&current)
+ || !view_percent.is_finite()
+ || view_percent <= 0.0
+ || view_percent >= 100.0
+ || !viewport_extent.is_finite()
+ || viewport_extent <= 0.0
+ || !offset.is_finite()
+ {
+ return Err(
+ AdapterError::new(ErrorCode::ActionFailed, "Invalid scroll viewport metrics")
+ .with_disposition(DeliverySemantics::not_delivered()),
+ );
}
+ let scrollable = viewport_extent * (100.0 - view_percent) / view_percent;
+ Ok((current + offset / scrollable * 100.0).clamp(0.0, 100.0))
}
#[cfg(target_os = "windows")]
@@ -78,6 +76,9 @@ pub(crate) fn visibility_verified(sample: &VisibilitySample) -> bool {
return false;
}
match sample.viewport {
+ Some(viewport) if bounds.width <= viewport.width && bounds.height <= viewport.height => {
+ direction_for_visibility(bounds, viewport).is_none()
+ }
Some(viewport) => intersects(bounds, viewport),
None => true,
}
@@ -132,7 +133,7 @@ pub(crate) fn direction_after_visibility_miss(
///
/// `next_direction` returns `None` when the target is in view (live path folds
/// the intersection predicate into that signal so an unclipped straddler does
-/// not verify — A18-2). `scroll_once` fires one SmallIncrement write.
+/// not verify — A18-2). `scroll_once` performs one semantic scroll write.
pub(crate) fn ladder_judged_for(
deadline: Deadline,
next_direction: &mut dyn FnMut() -> Result<Option<Direction>, AdapterError>,
@@ -163,8 +164,13 @@ pub(crate) fn ladder_judged_for(
fn budget_disposition(scrolled: bool, error: AdapterError) -> AdapterError {
if scrolled {
error.with_disposition(DeliverySemantics::delivered_unverified())
- } else {
+ } else if matches!(
+ error.disposition,
+ DeliverySemantics::Unknown | DeliverySemantics::NotDelivered
+ ) {
error.with_disposition(DeliverySemantics::not_delivered())
+ } else {
+ error
}
}
@@ -172,12 +178,12 @@ fn budget_disposition(scrolled: bool, error: AdapterError) -> AdapterError {
mod imp {
use super::{
AdapterError, Deadline, DeliveryOutcome, DeliverySemantics, Direction, LADDER_SCROLL_LABEL,
- UIAElement, VisibilitySample, ladder_judged_for, ladder_scroll_amounts,
+ UIAElement, VisibilitySample, centered_scroll_percent, ladder_judged_for,
visibility_verified,
};
use crate::actions::mutation::{classify_success, classify_write};
use crate::system::permissions::ensure_budget;
- use crate::tree::automation::automation_client;
+ use crate::tree::automation::{automation_client, uia_error};
use crate::tree::live_read::corroborate_verified_process;
use crate::tree::properties::read_one;
use crate::tree::property_ids::TreeProperty;
@@ -213,10 +219,10 @@ mod imp {
ancestor: &UIAElement,
deadline: Deadline,
) -> Result<DeliveryOutcome, AdapterError> {
- let viewport = viewport_bounds(ancestor);
- let mut next_direction = || direction_when_not_visible(element, viewport, deadline);
+ let mut next_direction =
+ || direction_when_not_visible(element, viewport_bounds(ancestor)?, deadline);
let mut scroll_once =
- |direction: &Direction| scroll_cached_ancestor(ancestor, direction, deadline);
+ |direction: &Direction| scroll_cached_ancestor(element, ancestor, direction, deadline);
ladder_judged_for(deadline, &mut next_direction, &mut scroll_once)
}
@@ -273,6 +279,7 @@ mod imp {
}
fn scroll_cached_ancestor(
+ element: &UIAElement,
ancestor: &UIAElement,
direction: &Direction,
deadline: Deadline,
@@ -289,15 +296,47 @@ mod imp {
));
}
};
- let (horizontal, vertical) = ladder_scroll_amounts(direction);
- match pattern.scroll(horizontal, vertical) {
+ if matches!(direction, Direction::Left | Direction::Right) {
+ let amount = if matches!(direction, Direction::Left) {
+ uiautomation::types::ScrollAmount::LargeDecrement
+ } else {
+ uiautomation::types::ScrollAmount::LargeIncrement
+ };
+ return match pattern.scroll(amount, uiautomation::types::ScrollAmount::NoAmount) {
+ Ok(()) => classify_success().map(|_| ()),
+ Err(error) => {
+ require_scroll_delivery(classify_write("Scroll", LADDER_SCROLL_LABEL, &error))
+ }
+ };
+ }
+ let bounds = crate::actions::scroll::known_bounds(element).ok_or_else(|| {
+ AdapterError::new(ErrorCode::ActionFailed, "Missing scroll target bounds")
+ })?;
+ let viewport = viewport_bounds(ancestor)?.ok_or_else(|| {
+ AdapterError::new(ErrorCode::ActionFailed, "Missing scroll viewport bounds")
+ })?;
+ let current = pattern.get_vertical_scroll_percent();
+ let size = pattern.get_vertical_view_size();
+ let extent = viewport.height;
+ let offset = bounds.y + bounds.height / 2.0 - viewport.y - viewport.height / 2.0;
+ let percent = centered_scroll_percent(
+ current.map_err(|error| uia_error(&error, "read scroll position"))?,
+ size.map_err(|error| uia_error(&error, "read scroll view size"))?,
+ extent,
+ offset,
+ )?;
+ ensure_budget(deadline)?;
+ corroborate_verified_process(ancestor)?;
+ match pattern.set_scroll_percent(-1.0, percent) {
Ok(()) => {
classify_success()?;
Ok(())
}
- Err(error) => {
- require_scroll_delivery(classify_write("Scroll", LADDER_SCROLL_LABEL, &error))
- }
+ Err(error) => require_scroll_delivery(classify_write(
+ "SetScrollPercent",
+ LADDER_SCROLL_LABEL,
+ &error,
+ )),
}
}
diff --git a/crates/windows/src/actions/scroll_ladder_tests.rs b/crates/windows/src/actions/scroll_ladder_tests.rs
index 9201e5e7e..288002b9c 100644
--- a/crates/windows/src/actions/scroll_ladder_tests.rs
+++ b/crates/windows/src/actions/scroll_ladder_tests.rs
@@ -1,16 +1,14 @@
use super::{
- MAX_ANCESTOR_SCROLLS, apply_ladder_seam, direction_after_visibility_miss,
- direction_for_visibility, ladder_judged_for, ladder_scroll_amounts,
+ MAX_ANCESTOR_SCROLLS, apply_ladder_seam, centered_scroll_percent,
+ direction_after_visibility_miss, direction_for_visibility, ladder_judged_for,
};
use crate::actions::chain::DeliveryOutcome;
-use crate::actions::scroll::scroll_amounts;
use crate::actions::scroll_into_view::{VisibilitySample, visibility_verified};
use crate::system::test_time::deadline;
use agent_desktop_core::{
AdapterError, Deadline, DeliveryDisposition, DeliverySemantics, Direction, ErrorCode, Rect,
};
use std::cell::Cell;
-use uiautomation::types::ScrollAmount;
fn rect(x: f64, y: f64, width: f64, height: f64) -> Rect {
Rect {
@@ -181,20 +179,26 @@ fn absence_ok_false_does_not_count_as_scroll_delivery() {
#[test]
fn classified_write_error_aborts_without_further_scrolls() {
- let calls = Cell::new(0u8);
- let mut next = || Ok(Some(Direction::Down));
- let mut scroll = |_: &Direction| {
- calls.set(calls.get() + 1);
- Err(AdapterError::new(ErrorCode::PermDenied, "denied write")
- .with_disposition(DeliverySemantics::not_delivered()))
- };
- let error = ladder_judged_for(deadline(5_000), &mut next, &mut scroll).expect_err("denied");
- assert_eq!(error.code, ErrorCode::PermDenied);
- assert_eq!(calls.get(), 1);
- assert_eq!(
- error.disposition.delivery(),
- DeliveryDisposition::NotDelivered
- );
+ for disposition in [
+ DeliverySemantics::not_delivered(),
+ DeliverySemantics::uncertain(),
+ DeliverySemantics::delivered_unverified(),
+ ] {
+ let calls = Cell::new(0u8);
+ let mut next = || Ok(Some(Direction::Down));
+ let mut scroll = |_: &Direction| {
+ calls.set(calls.get() + 1);
+ Err(
+ AdapterError::new(ErrorCode::AppUnresponsive, "write failed")
+ .with_disposition(disposition),
+ )
+ };
+ let error =
+ ladder_judged_for(deadline(5_000), &mut next, &mut scroll).expect_err("write failed");
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert_eq!(calls.get(), 1);
+ assert_eq!(error.disposition, disposition);
+ }
}
#[test]
@@ -313,35 +317,42 @@ fn contained_but_not_visible_does_not_invent_down() {
);
}
-/// Measured live (see `ladder_scroll_amounts` doc comment): a `SmallDecrement`
-/// rung moved a real ancestor's viewport 5px, so `MAX_ANCESTOR_SCROLLS` rungs
-/// of the direct `scroll` command's small-nudge amount never covers a target
-/// displaced hundreds of pixels by a native focus jump. The ladder must use
-/// its own page-sized amount, distinct from `scroll::scroll_amounts` — this
-/// guards against the two call sites being collapsed back onto one shared
-/// small-step function.
#[test]
-fn ladder_uses_large_amounts_distinct_from_the_scroll_commands_small_nudge() {
- for direction in [
- Direction::Up,
- Direction::Down,
- Direction::Left,
- Direction::Right,
+fn precise_scroll_centers_targets_and_clamps_at_content_edges() {
+ assert_eq!(
+ centered_scroll_percent(0.0, 20.0, 100.0, 240.0).unwrap(),
+ 60.0
+ );
+ assert_eq!(
+ centered_scroll_percent(60.0, 20.0, 100.0, -240.0).unwrap(),
+ 0.0
+ );
+ assert_eq!(
+ centered_scroll_percent(90.0, 20.0, 100.0, 240.0).unwrap(),
+ 100.0
+ );
+ let next = centered_scroll_percent(0.0, 50.0, 611.0, 365.5).unwrap();
+ let moved_y = 666.0 - next / 100.0 * 611.0;
+ assert!(
+ direction_for_visibility(
+ rect(84.0, moved_y, 400.0, 150.0),
+ rect(48.0, 71.0, 867.0, 611.0)
+ )
+ .is_none()
+ );
+}
+
+#[test]
+fn invalid_scroll_metrics_never_produce_a_write() {
+ for (current, size, extent, offset) in [
+ (-1.0, 20.0, 100.0, 10.0),
+ (0.0, 0.0, 100.0, 10.0),
+ (0.0, 100.0, 100.0, 10.0),
+ (0.0, 20.0, 0.0, 10.0),
+ (f64::NAN, 20.0, 100.0, 10.0),
+ (0.0, 20.0, 100.0, f64::INFINITY),
] {
- let (ladder_h, ladder_v) = ladder_scroll_amounts(&direction);
- let (small_h, small_v) = scroll_amounts(&direction);
- assert_ne!(
- (ladder_h, ladder_v),
- (small_h, small_v),
- "ladder amount must not match the direct scroll command's small nudge for {direction:?}"
- );
- let large = match direction {
- Direction::Down => (ScrollAmount::NoAmount, ScrollAmount::LargeIncrement),
- Direction::Up => (ScrollAmount::NoAmount, ScrollAmount::LargeDecrement),
- Direction::Right => (ScrollAmount::LargeIncrement, ScrollAmount::NoAmount),
- Direction::Left => (ScrollAmount::LargeDecrement, ScrollAmount::NoAmount),
- };
- assert_eq!((ladder_h, ladder_v), large);
+ assert!(centered_scroll_percent(current, size, extent, offset).is_err());
}
}
@@ -374,3 +385,16 @@ fn an_unresolvable_viewport_does_not_make_an_on_screen_element_invisible() {
positive-area rect are what remain, and both say visible"
);
}
+
+#[test]
+fn a_small_target_must_be_wholly_inside_the_scroll_viewport() {
+ let sample = VisibilitySample {
+ bounds: Some(rect(10.0, 95.0, 20.0, 20.0)),
+ offscreen: Some(false),
+ viewport: Some(rect(0.0, 0.0, 100.0, 100.0)),
+ };
+ assert!(
+ !visibility_verified(&sample),
+ "a clipped target midpoint cannot receive input"
+ );
+}
diff --git a/crates/windows/src/tree/hit_test.rs b/crates/windows/src/tree/hit_test.rs
index b3e8e9c30..45dbe584d 100644
--- a/crates/windows/src/tree/hit_test.rs
+++ b/crates/windows/src/tree/hit_test.rs
@@ -29,6 +29,8 @@ use agent_desktop_core::{
#[cfg(target_os = "windows")]
#[path = "hit_test_classify.rs"]
mod classify;
+#[cfg(target_os = "windows")]
+pub(crate) use classify::intersect_rects;
#[cfg(target_os = "windows")]
#[path = "hit_test_corroborate.rs"]
diff --git a/crates/windows/src/tree/live_read.rs b/crates/windows/src/tree/live_read.rs
index 1527e2c69..87dcd348e 100644
--- a/crates/windows/src/tree/live_read.rs
+++ b/crates/windows/src/tree/live_read.rs
@@ -74,12 +74,13 @@ mod imp {
deadline: Deadline,
) -> Result<LiveRead, AdapterError> {
let element = uia_element(handle)?;
- let owning_window_minimized =
- crate::tree::minimized::owning_window_minimized(element, deadline).unwrap_or(false);
+ let outside_visible_area =
+ crate::tree::minimized::owning_window_minimized(element, deadline).unwrap_or(false)
+ || crate::tree::minimized::outside_scroll_viewports(element, deadline)?;
read_live_element_core(
element,
deadline,
- owning_window_minimized,
+ outside_visible_area,
corroborate_verified_process,
|element| read_live_bounded(element, deadline),
|element| read_label(element, false),
@@ -193,11 +194,8 @@ pub(crate) fn live_value(read: &LiveRead) -> Option<String> {
/// The state projection.
///
-/// `enabled` and `offscreen` read the provider's own flags from the property
-/// set - UIA exposes `IsOffscreen` directly, the deliberate divergence from
-/// macOS's window-bounds arithmetic. `hidden` has no Windows producer (UIA's
-/// offscreen signal is the closest, and reading it twice would double-count), so it
-/// stays unset.
+/// Provider flags include the shared read's minimized-window and viewport
+/// clipping corrections. `hidden` stays unset because UIA has no separate flag.
pub(crate) fn live_state(read: &LiveRead) -> Result<ElementState, AdapterError> {
let role = read
.evidence
diff --git a/crates/windows/src/tree/minimized.rs b/crates/windows/src/tree/minimized.rs
index 3e711b44c..948954170 100644
--- a/crates/windows/src/tree/minimized.rs
+++ b/crates/windows/src/tree/minimized.rs
@@ -23,6 +23,54 @@ pub(crate) fn owning_window_minimized(element: &UIAElement, deadline: Deadline)
})
}
+/// WinForms reports unclipped descendants as on-screen; intersect their scroll viewports.
+pub(crate) fn outside_scroll_viewports(
+ element: &UIAElement,
+ deadline: Deadline,
+) -> Result<bool, agent_desktop_core::AdapterError> {
+ use crate::tree::automation::uia_error;
+ use crate::tree::properties::read_one;
+ use crate::tree::walker_source::{parent_step, viewport_bounds};
+ let Some(mut visible) = read_one(element, TreeProperty::BoundingRectangle)
+ .bounds()
+ .known()
+ .copied()
+ else {
+ return Ok(false);
+ };
+ let client = automation_client()?;
+ let walker = client
+ .get_raw_view_walker()
+ .map_err(|error| uia_error(&error, "read scroll ancestors"))?;
+ let mut current = element.clone();
+ for _ in 0..crate::tree::walker::DEFAULT_MAX_RAW_DEPTH {
+ crate::system::permissions::ensure_budget(deadline)?;
+ current = match parent_step(&walker, &current) {
+ Ok(Some(parent)) => parent,
+ Ok(None) => return Ok(false),
+ Err(()) => {
+ return Err(agent_desktop_core::AdapterError::new(
+ agent_desktop_core::ErrorCode::AppUnresponsive,
+ "Could not inspect scroll clipping",
+ ));
+ }
+ };
+ if read_one(&current, TreeProperty::ScrollAvailable).flag() != Some(true) {
+ continue;
+ }
+ if let Some(viewport) = viewport_bounds(&current)? {
+ match crate::tree::hit_test::intersect_rects(visible, viewport) {
+ Some(intersection) => visible = intersection,
+ None => return Ok(true),
+ }
+ }
+ }
+ Err(agent_desktop_core::AdapterError::new(
+ agent_desktop_core::ErrorCode::AppUnresponsive,
+ "Scroll ancestor traversal exceeded its limit",
+ ))
+}
+
/// Reports a minimized owner's whole subtree offscreen in the read set.
///
/// A minimized top-level window keeps reporting usable rectangles and a
diff --git a/crates/windows/src/tree/walker_source.rs b/crates/windows/src/tree/walker_source.rs
index 084ece968..b71c6d5cb 100644
--- a/crates/windows/src/tree/walker_source.rs
+++ b/crates/windows/src/tree/walker_source.rs
@@ -97,10 +97,42 @@ mod imp {
///
/// Which ancestor clips the target is fixed for the life of one operation;
/// its rectangle is not. A poller re-reads this and never the climb.
- pub fn viewport_bounds(viewport: &UIAElement) -> Option<Rect> {
+ pub fn viewport_bounds(viewport: &UIAElement) -> Result<Option<Rect>, AdapterError> {
+ use windows::Win32::Foundation::HWND;
+ use windows_sys::Win32::Foundation::{POINT, RECT};
+ use windows_sys::Win32::Graphics::Gdi::ClientToScreen;
+ use windows_sys::Win32::UI::WindowsAndMessaging::GetClientRect;
+
+ let handle: HWND = viewport
+ .0
+ .get_native_window_handle()
+ .map_err(|error| uia_error(&error, "read viewport window"))?
+ .into();
+ if !handle.0.is_null() {
+ let mut rect = RECT::default();
+ let mut origin = POINT::default();
+ if unsafe { GetClientRect(handle.0, &mut rect) } == 0
+ || unsafe { ClientToScreen(handle.0, &mut origin) } == 0
+ {
+ return Err(AdapterError::new(
+ agent_desktop_core::ErrorCode::ActionFailed,
+ "Could not read the native scroll viewport",
+ ));
+ }
+ return Ok(Some(Rect {
+ x: f64::from(origin.x),
+ y: f64::from(origin.y),
+ width: f64::from(rect.right - rect.left),
+ height: f64::from(rect.bottom - rect.top),
+ }));
+ }
match read_one(viewport, TreeProperty::BoundingRectangle).bounds() {
- LocatorField::Known(bounds) if rect_has_area(&bounds) => Some(bounds),
- _ => None,
+ LocatorField::Known(bounds) if rect_has_area(&bounds) => Ok(Some(bounds)),
+ LocatorField::Absent => Ok(None),
+ _ => Err(AdapterError::new(
+ agent_desktop_core::ErrorCode::ActionFailed,
+ "Could not read the scroll viewport bounds",
+ )),
}
}
@@ -111,9 +143,12 @@ mod imp {
walker: &UITreeWalker,
deadline: Deadline,
) -> Result<Option<Rect>, BudgetExpired> {
- Ok(nearest_scroll_viewport(target, walker, deadline)?
+ nearest_scroll_viewport(target, walker, deadline)?
.as_ref()
- .and_then(viewport_bounds))
+ .map(viewport_bounds)
+ .transpose()
+ .map(Option::flatten)
+ .map_err(|_| BudgetExpired)
}
/// The production enumeration surface: the raw view walker, plus the cache
diff --git a/crates/windows/src/tree/walker_source_tests.rs b/crates/windows/src/tree/walker_source_tests.rs
index d4ff6ff8d..07520abd6 100644
--- a/crates/windows/src/tree/walker_source_tests.rs
+++ b/crates/windows/src/tree/walker_source_tests.rs
@@ -84,6 +84,20 @@ mod windows_only {
use crate::tree::fixture::HostedFixture;
use crate::tree::walker_fake::deadline;
+ #[test]
+ fn native_viewport_excludes_the_window_caption() {
+ crate::tree::fixture::ensure_test_apartment();
+ let fixture = HostedFixture::spawn().expect("fixture");
+ let root = root_from_hwnd(fixture.handle(), deadline()).expect("root");
+ let outer = root.0.get_bounding_rectangle().unwrap();
+ let viewport = viewport_bounds(&root).unwrap().unwrap();
+ assert!(
+ viewport.y > f64::from(outer.get_top()),
+ "caption is not content"
+ );
+ assert!(viewport.height < f64::from(outer.get_bottom() - outer.get_top()));
+ }
+
/// A live fixture with no scrollable ancestor climbs to the true root and
/// reports `Ok(None)` - the confident "no viewport" answer a completed
/// climb gives. This is a regression guard on the healthy path only: it
diff --git a/tests/e2e-windows/InteractionHeaded.ps1 b/tests/e2e-windows/InteractionHeaded.ps1
index dd2ee5b1b..4c115b710 100644
--- a/tests/e2e-windows/InteractionHeaded.ps1
+++ b/tests/e2e-windows/InteractionHeaded.ps1
@@ -26,33 +26,22 @@ function Invoke-HeadedInteractionLegs {
id resolve loop leaves the AutoScroll viewport scrolled deep
into the scroll-row list, so a stale off-screen bounds reading
can never be clicked. scroll-to is a no-op when visible. #>
- $diagProc = Get-Process -Name 'AgentDeskFixture' -ErrorAction SilentlyContinue | Select-Object -First 1
- Write-Host "DIAG headed-legs-entry: fixtureHwnd=$($diagProc.MainWindowHandle) foregroundHwnd=$(Get-NativeForegroundWindowHandle)"
try {
$target = Require-Target -Target (Find-Target -App $App -NativeId 'double-target' -TimeoutSeconds 10) -Description 'double-target'
Invoke-Target -Target $target -Action 'scroll-to' -RequireOk -Description 'double-target (scroll into view)' | Out-Null
$status = Require-Target -Target (Find-Target -App $App -NativeId 'double-status' -TimeoutSeconds 10) -Description 'double-status'
- $diagEnvelope = Invoke-Target -Target $target -Action 'double-click' -Headed
- Write-Host "DIAG double-click-envelope: $($diagEnvelope | ConvertTo-Json -Depth 12 -Compress)"
- if ($diagEnvelope['error'] -and $diagEnvelope['error']['details']) {
- Write-Host "DIAG double-click-details: $($diagEnvelope['error']['details'] | ConvertTo-Json -Depth 12 -Compress)"
- }
- Start-Sleep -Milliseconds 500
- Write-Host "DIAG double-click-status-after-sleep: $(Get-Target -Target $status -Property 'value')"
- if ($diagEnvelope['ok'] -eq $true -and (Get-Target -Target $status -Property 'value') -like 'double-clicked*') {
- Add-Pass -Leg 'headed-double-click'
- } else {
- throw "DIAG single-attempt did not reach double-clicked (ok=$($diagEnvelope['ok']))"
- }
- } catch {
- Write-Host "DIAG double-click-fail: foregroundHwnd=$(Get-NativeForegroundWindowHandle) fixtureHwnd=$($diagProc.MainWindowHandle)"
- Add-Fail -Leg 'headed-double-click' -Reason $_.Exception.Message
- }
+ Assert-Effect -Target $target -StatusTarget $status -Property 'value' -Expected 'double-clicked' -ExpectedIsPrefix -Action 'double-click' -Headed | Out-Null
+ Add-Pass -Leg 'headed-double-click'
+ } catch { Add-Fail -Leg 'headed-double-click' -Reason $_.Exception.Message }
try {
$target = Require-Target -Target (Find-Target -App $App -NativeId 'triple-target' -TimeoutSeconds 10) -Description 'triple-target'
Invoke-Target -Target $target -Action 'scroll-to' -RequireOk -Description 'triple-target (scroll into view)' | Out-Null
$status = Require-Target -Target (Find-Target -App $App -NativeId 'triple-status' -TimeoutSeconds 10) -Description 'triple-status'
+ Add-Type -AssemblyName System.Windows.Forms
+ $resetWindow = [System.Windows.Forms.SystemInformation]::DoubleClickTime * 2 + 100
+ $twoClicks = Assert-NoEffect -Target $target -StatusTarget $status -Property 'value' -Action 'double-click' -Headed -WindowMs $resetWindow
+ Assert-Envelope -Envelope $twoClicks -Ok
Assert-Effect -Target $target -StatusTarget $status -Property 'value' -Expected 'triple-clicked' -ExpectedIsPrefix -Action 'triple-click' -Headed | Out-Null
Add-Pass -Leg 'headed-triple-click'
} catch { Add-Fail -Leg 'headed-triple-click' -Reason $_.Exception.Message }
@@ -89,10 +78,11 @@ function Invoke-HeadedInteractionLegs {
and verifies it; this leg only needs to scroll the target
into view first, the same as every other physical leg in
this file. #>
+ Assert-Envelope -Envelope (Invoke-AgentDesktop -Arguments @('--headed', 'mouse-move', '--xy', '5,5')) -Ok
$mover = Require-Target -Target (Find-Target -App $App -NativeId 'hover-target' -TimeoutSeconds 10) -Description 'hover-target'
Invoke-Target -Target $mover -Action 'scroll-to' -RequireOk -Description 'hover-target (scroll into view)' | Out-Null
$status = Require-Target -Target (Find-Target -App $App -NativeId 'hover-status' -TimeoutSeconds 10) -Description 'hover-status'
- Assert-Effect -Target $mover -StatusTarget $status -Property 'value' -Expected 'hovered' -ExpectedIsPrefix -Action 'hover' -Headed | Out-Null
+ Assert-Effect -Target $mover -StatusTarget $status -Property 'value' -Expected 'hovered' -ExpectedIsPrefix -AnyChange -Action 'hover' -Headed | Out-Null
Add-Pass -Leg 'headed-hover'
} catch { Add-Fail -Leg 'headed-hover' -Reason $_.Exception.Message }
diff --git a/tests/e2e-windows/InteractionPress.ps1 b/tests/e2e-windows/InteractionPress.ps1
new file mode 100644
index 000000000..4495774df
--- /dev/null
+++ b/tests/e2e-windows/InteractionPress.ps1
@@ -0,0 +1,74 @@
+#Requires -Version 5.1
+
+Set-StrictMode -Version 2.0
+
+function Invoke-PressLegs {
+ param([Parameter(Mandatory = $true)][string]$App)
+ Enter-Stage -Lock DesktopLease -Body {
+ Enter-Stage -Lock ForegroundStage -Body {
+ try {
+ $textInput = Require-Target -Target (Find-Target -App $App -NativeId 'text-input' -TimeoutSeconds 10) -Description 'text-input'
+ Invoke-Target -Target $textInput -Action 'scroll-to' -RequireOk -Description 'text-input (scroll into view)' | Out-Null
+ Invoke-Target -Target $textInput -Action 'set-value' -ActionArgs @('abc') -RequireOk -Description 'text-input (seed)' | Out-Null
+ Invoke-Target -Target $textInput -Action 'focus' -Headed -RequireOk -Description 'text-input (keyboard focus)' | Out-Null
+ if ((Get-Target -Target $textInput -Property 'value') -ne 'abc') { throw 'text-input did not hold the seed value before the press' }
+ Assert-Envelope -Envelope (Invoke-AgentDesktop -Arguments @('--headed', 'press', 'ctrl+a', '--app', $App)) -Ok
+ Assert-Envelope -Envelope (Invoke-AgentDesktop -Arguments @('--headed', 'press', 'backspace', '--app', $App)) -Ok
+ $clock = [System.Diagnostics.Stopwatch]::StartNew()
+ $observed = Get-Target -Target $textInput -Property 'value'
+ while ($observed -ne '' -and $clock.Elapsed.TotalSeconds -lt 5) {
+ Start-Sleep -Milliseconds 150
+ $observed = Get-Target -Target $textInput -Property 'value'
+ }
+ if ($observed -ne '') { throw "ctrl+a then backspace left text-input at '$observed'; expected the whole value removed (a dropped ctrl would leave a partial value, an undelivered press leaves 'abc')" }
+ Add-Pass -Leg 'press-ctrl-a-backspace-clears-text'
+ } catch { Add-Fail -Leg 'press-ctrl-a-backspace-clears-text' -Reason $_.Exception.Message }
+
+ try {
+ $textInput = Require-Target -Target (Find-Target -App $App -NativeId 'text-input' -TimeoutSeconds 10) -Description 'text-input'
+ Invoke-Target -Target $textInput -Action 'focus' -Headed -RequireOk -Description 'text-input (keyboard focus)' | Out-Null
+ if (-not (Test-Target -Target $textInput -Property 'focused')) { throw 'text-input was not focused before shift+tab; the leg would prove nothing' }
+ Assert-Envelope -Envelope (Invoke-AgentDesktop -Arguments @('--headed', 'press', 'shift+tab', '--app', $App)) -Ok
+ $clock = [System.Diagnostics.Stopwatch]::StartNew()
+ $stillFocused = Test-Target -Target $textInput -Property 'focused'
+ while ($stillFocused -and $clock.Elapsed.TotalSeconds -lt 5) {
+ Start-Sleep -Milliseconds 150
+ $stillFocused = Test-Target -Target $textInput -Property 'focused'
+ }
+ if ($stillFocused) { throw 'text-input still reports focused after shift+tab' }
+ Add-Pass -Leg 'press-shift-tab-moves-focus'
+ } catch { Add-Fail -Leg 'press-shift-tab-moves-focus' -Reason $_.Exception.Message }
+
+ try {
+ $button = Require-Target -Target (Find-Target -App $App -NativeId 'primary-button' -TimeoutSeconds 10) -Description 'primary-button'
+ Invoke-Target -Target $button -Action 'scroll-to' -RequireOk -Description 'primary-button (scroll into view)' | Out-Null
+ Invoke-Target -Target $button -Action 'focus' -Headed -RequireOk -Description 'primary-button (keyboard focus)' | Out-Null
+ $clickStatus = Require-Target -Target (Find-Target -App $App -NativeId 'click-status' -TimeoutSeconds 10) -Description 'click-status'
+ $before = Get-Target -Target $clickStatus -Property 'value'
+ Assert-Envelope -Envelope (Invoke-AgentDesktop -Arguments @('--headed', 'press', 'return', '--app', $App)) -Ok
+ $clock = [System.Diagnostics.Stopwatch]::StartNew()
+ $after = Get-Target -Target $clickStatus -Property 'value'
+ while ($after -eq $before -and $clock.Elapsed.TotalSeconds -lt 5) {
+ Start-Sleep -Milliseconds 150
+ $after = Get-Target -Target $clickStatus -Property 'value'
+ }
+ if ($after -eq $before -or $after -notlike 'clicked#*') { throw "return on the focused primary-button left click-status at '$after' (was '$before')" }
+ Add-Pass -Leg 'press-return-activates-focused-button'
+ } catch { Add-Fail -Leg 'press-return-activates-focused-button' -Reason $_.Exception.Message }
+
+ try {
+ $foregroundBefore = Get-NativeForegroundWindowHandle
+ $refused = Invoke-AgentDesktop -Arguments @('press', 'meta+x', '--app', $App)
+ Assert-Envelope -Envelope $refused -ErrorCode 'POLICY_DENIED' -Delivery 'not_delivered'
+ if (-not ([string]$refused['error']['message']).Contains('blocked for safety')) { throw "win+x was refused with an unexpected message: '$($refused['error']['message'])'" }
+ $clock = [System.Diagnostics.Stopwatch]::StartNew()
+ while ($clock.ElapsedMilliseconds -lt 1500) {
+ if ((Get-NativeForegroundWindowHandle) -ne $foregroundBefore) { throw 'foreground window changed after a refused win+x; the combo may have been delivered' }
+ Start-Sleep -Milliseconds 150
+ }
+ if (-not (Get-WindowId -Where { $_['title'] -eq 'AgentDeskFixture' } -TimeoutSeconds 5)) { throw 'the fixture window is no longer listed after the refused combo' }
+ Add-Pass -Leg 'press-blocked-combo-refused'
+ } catch { Add-Fail -Leg 'press-blocked-combo-refused' -Reason $_.Exception.Message }
+ }
+ }
+}
diff --git a/tests/e2e-windows/scenarios/Interaction.ps1 b/tests/e2e-windows/scenarios/Interaction.ps1
index 884195f07..72b92e407 100644
--- a/tests/e2e-windows/scenarios/Interaction.ps1
+++ b/tests/e2e-windows/scenarios/Interaction.ps1
@@ -28,6 +28,7 @@ Set-StrictMode -Version 2.0
file under the 400-line cap. It is not under scenarios/ itself: see that
file's own header for why. #>
. (Join-Path (Split-Path -Parent $PSScriptRoot) 'InteractionHeaded.ps1')
+. (Join-Path (Split-Path -Parent $PSScriptRoot) 'InteractionPress.ps1')
function Get-InteractionHeadlessLegTable {
@(
@@ -83,6 +84,7 @@ function Assert-RefusalLeg {
Assert-Envelope -Envelope $envelope -ErrorCode 'POLICY_DENIED' -Delivery 'not_delivered' -Retry 'safe'
return
}
+ Invoke-Target -Target $target -Action 'scroll-to' -RequireOk -Description $Leg.TargetId | Out-Null
$statusTarget = Require-Target -Target (Find-Target -App $App -NativeId $Leg.StatusId -TimeoutSeconds 10) -Description $Leg.StatusId
$envelope = Assert-NoEffect -Target $target -StatusTarget $statusTarget -Property 'value' -Action $Leg.Action
Assert-Envelope -Envelope $envelope -ErrorCode 'POLICY_DENIED' -Delivery 'not_delivered' -Retry 'safe'
@@ -98,6 +100,8 @@ function Invoke-InteractionScenario {
'mouse-move-refused', 'mouse-click-refused', 'mouse-wheel-refused', 'surface-menu-closed-is-window-not-found',
'headed-double-click', 'headed-triple-click', 'headed-right-click-then-choose', 'headed-hover',
'headed-drag', 'headed-type', 'headed-press-app',
+ 'press-ctrl-a-backspace-clears-text', 'press-shift-tab-moves-focus',
+ 'press-return-activates-focused-button', 'press-blocked-combo-refused',
'interaction-scroll-to-visibility', 'interaction-focus-refused-headless', 'interaction-focus-headed-oracle'
))
@@ -162,6 +166,7 @@ function Invoke-InteractionScenario {
Invoke-HeldInputRefusalLegs
Invoke-SurfaceClosedMenuLeg -App $App
Invoke-HeadedInteractionLegs -App $App
+ Invoke-PressLegs -App $App
Invoke-ScrollToVisibilityLeg -App $App
Invoke-FocusRefusalLeg -App $App
Invoke-FocusOracleLeg -App $App
diff --git a/tests/fixture-app-windows/FixtureCardsClicks.cs b/tests/fixture-app-windows/FixtureCardsClicks.cs
index 2345223d0..21749de88 100644
--- a/tests/fixture-app-windows/FixtureCardsClicks.cs
+++ b/tests/fixture-app-windows/FixtureCardsClicks.cs
@@ -34,29 +34,16 @@ namespace AgentDeskFixtureApp
BuildTwinControls(card, CardLayout.RowY(5));
}
- /// <summary>
- /// A physical N-click delivers N separate WM_LBUTTONDOWN/UP pairs
- /// (Windows only special-cases the second click as
- /// WM_LBUTTONDBLCLK; there is no native "triple" message, and a
- /// stock <see cref="Button"/> does not raise <see
- /// cref="Control.DoubleClick"/> at all - measured live, probe A20-4
- /// found a Button sink stuck at its pre-click value across every
- /// inter-click timing it tried and had to switch its own working
- /// target to a ListBox; see probes/windows/FINDINGS.md). Counting
- /// <see cref="Control.Click"/> events instead works for any control
- /// that raises Click, a Button included, and resets the counter once
- /// twice the system double-click interval has elapsed since the run's
- /// first click - a click arriving after that window starts a fresh
- /// count of one rather than accumulating forever.
- /// </summary>
+ // Count physical releases once; WinForms can raise Click twice for one press.
private static void BuildCountedClickTarget(
GroupBox card, string id, string label, int y, string statusId, string statusValue, int targetCount)
{
CountedClickButton target = CountedClickButton.Create(card, id, label, 16, y, 110);
int clickCount = 0;
DateTime windowStart = DateTime.MinValue;
- target.Click += delegate
+ target.MouseUp += delegate(object sender, MouseEventArgs e)
{
+ if (e.Button != MouseButtons.Left) { return; }
DateTime now = DateTime.UtcNow;
double windowMs = SystemInformation.DoubleClickTime * 2;
if (clickCount == 0 || (now - windowStart).TotalMilliseconds > windowMs)
@@ -184,19 +171,7 @@ namespace AgentDeskFixtureApp
};
}
- /// <summary>
- /// A <see cref="Button"/> that raises <see cref="Control.Click"/> for the
- /// second press of a physical double-click.
- ///
- /// Windows delivers that press as WM_LBUTTONDBLCLK rather than another
- /// WM_LBUTTONDOWN/UP pair, and a stock Button has StandardDoubleClick
- /// disabled, so it swallows the message and raises nothing. A counter
- /// watching Click therefore stops at one and a double-click target never
- /// reaches two - while a triple-click target still passes, because its
- /// third press arrives as an ordinary click. Enabling the style makes the
- /// second press raise Click like every other press, which is what the
- /// counting approach already assumes.
- /// </summary>
+ // Preserve native double-click messages while counting each physical release.
internal sealed class CountedClickButton : Button
{
internal CountedClickButton()
diff --git a/tests/fixture-app-windows/FixtureCardsInput.cs b/tests/fixture-app-windows/FixtureCardsInput.cs
index fdd8e337a..eade379d0 100644
--- a/tests/fixture-app-windows/FixtureCardsInput.cs
+++ b/tests/fixture-app-windows/FixtureCardsInput.cs
@@ -17,6 +17,14 @@ namespace AgentDeskFixtureApp
FixtureIdentity.Assign(textInput, "text-input");
textInput.Location = new Point(16, CardLayout.RowY(0));
textInput.Width = 200;
+ textInput.KeyDown += delegate(object sender, KeyEventArgs e)
+ {
+ if (e.Control && e.KeyCode == Keys.A)
+ {
+ textInput.SelectAll();
+ e.SuppressKeyPress = true;
+ }
+ };
card.Controls.Add(textInput);
textInput.TextChanged += delegate { FixtureStatus.SetValue("text-status", "changed"); };
NewStatus(card, "text-status", 226, CardLayout.RowY(0), 200);