Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

test(cua-driver): prune redundant Windows adapter tests (#4119)

Francesco Bonaccib5c605113510
diff --git a/.github/workflows/ci-rust-windows.yml b/.github/workflows/ci-rust-windows.yml
index 3c2f064f8c..61fefa672d 100644
--- a/.github/workflows/ci-rust-windows.yml
+++ b/.github/workflows/ci-rust-windows.yml
@@ -95,6 +95,10 @@ jobs:
# be silently left out by a hand-maintained module filter list.
- name: Run platform-windows unit tests
working-directory: libs/cua-driver/rust
+ env:
+ # The hosted runner's clipboard is disposable; opt in to the native
+ # clipboard round trip that would clobber a developer's clipboard.
+ CUA_TEST_ALLOW_CLIPBOARD: "1"
run: cargo test --locked -p platform-windows --lib
- name: Run MCP proxy lifecycle regressions
working-directory: libs/cua-driver/rust
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
index 11dd682235..a48dbc9a52 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
@@ -347,7 +347,7 @@ where
}
fn exact_allow_button(nodes: &[UiaNode]) -> Result<Option<usize>, BrowserRefusal> {
- Ok(exact_consent_actions_with(nodes, native_button_properties)?.map(|actions| actions.0))
+ exact_allow_button_with(nodes, native_button_properties)
}
fn exact_cancel_button(nodes: &[UiaNode]) -> Result<Option<usize>, BrowserRefusal> {
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
index 5e51256b78..08837dc75d 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
@@ -782,17 +782,6 @@ fn parse_netstat_loopback_listeners(text: &str, allowed_pids: &[u32]) -> Vec<(u1
listeners
}
-#[cfg(test)]
-fn parse_netstat_loopback_ports(text: &str, allowed_pids: &[u32]) -> Vec<u16> {
- let mut ports = parse_netstat_loopback_listeners(text, allowed_pids)
- .into_iter()
- .map(|(port, _owner_pid)| port)
- .collect::<Vec<_>>();
- ports.sort_unstable();
- ports.dedup();
- ports
-}
-
fn system_directory_path() -> Result<PathBuf, BrowserRefusal> {
let mut buffer = [0u16; 32768];
let length = unsafe { GetSystemDirectoryW(Some(&mut buffer)) } as usize;
@@ -2195,21 +2184,14 @@ mod tests {
TCP 127.0.0.1:9222 0.0.0.0:0 LISTENING 42\n\
TCP 0.0.0.0:9333 0.0.0.0:0 LISTENING 43\n\
TCP [::1]:9444 [::]:0 LISTENING 43\n\
+ TCP 127.0.0.1:9666 127.0.0.1:50000 ESTABLISHED 42\n\
TCP 127.0.0.1:9555 0.0.0.0:0 LISTENING 7\n";
assert_eq!(
- parse_netstat_loopback_ports(input, &[42, 43]),
- vec![9222, 9444]
+ parse_netstat_loopback_listeners(input, &[42, 43]),
+ vec![(9222, 42), (9444, 43)]
);
}
- #[test]
- fn netstat_parser_rejects_unrelated_process_trees() {
- let input = "\
- TCP 127.0.0.1:9222 0.0.0.0:0 LISTENING 42\n\
- TCP 127.0.0.1:9555 0.0.0.0:0 LISTENING 99\n";
- assert_eq!(parse_netstat_loopback_ports(input, &[42, 43]), vec![9222]);
- }
-
#[test]
fn netstat_parser_preserves_the_exact_listener_owner() {
let input = "\
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/clipboard.rs b/libs/cua-driver/rust/crates/platform-windows/src/clipboard.rs
index 2f8a85d3e0..999e75fa1a 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/clipboard.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/clipboard.rs
@@ -89,8 +89,12 @@ mod tests {
}
#[test]
- fn native_clipboard_round_trips_text_in_ci() {
- if std::env::var_os("CI").is_none() {
+ fn native_clipboard_round_trips_text_when_opted_in() {
+ // Overwrites the system clipboard, so it runs only where a job opts
+ // in explicitly. `CI` alone is not enough: developers export it too.
+ if std::env::var_os("CUA_TEST_ALLOW_CLIPBOARD").as_deref()
+ != Some(std::ffi::OsStr::new("1"))
+ {
return;
}
let backend = WindowsClipboard::new();
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs b/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs
index fe90fa39e6..2c8c11e194 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs
@@ -232,25 +232,6 @@ mod tests {
assert!(entry.message.contains("cua-driver "));
}
- #[test]
- fn session_active_passes() {
- let entry = check_session_active();
- assert_eq!(entry.status, CheckStatus::Pass);
- }
-
- #[test]
- fn tcc_and_bundle_are_skipped_with_canonical_message() {
- for name in [
- NAME_TCC_ACCESSIBILITY,
- NAME_TCC_SCREEN_RECORDING,
- NAME_BUNDLE_IDENTITY,
- ] {
- let entry = skip_not_applicable(name);
- assert_eq!(entry.status, CheckStatus::Skip, "{name} must be skipped");
- assert_eq!(entry.message, "not applicable on Windows");
- }
- }
-
// End-to-end through the dispatcher: every Windows canonical name
// appears in the response, in declared order. Run on every host so
// CI matrices that don't target Windows still verify the schema
@@ -286,6 +267,7 @@ mod tests {
.iter()
.map(|c| (c["name"].as_str().unwrap(), c))
.collect();
+ assert_eq!(by_name[NAME_SESSION_ACTIVE]["status"], "pass");
for name in [
NAME_TCC_ACCESSIBILITY,
NAME_TCC_SCREEN_RECORDING,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs
index 649f1989b6..6b75d8ac31 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs
@@ -468,19 +468,6 @@ mod iconic_sentinel_tests {
/// the capture-path guard in `capture.rs`.
const ICONIC_RECT: (i32, i32, i32, i32) = (-32000, -32000, -31840, -31972);
- #[test]
- fn iconic_rect_passes_the_positive_extent_check_that_guards_the_bounds_path() {
- // This is why #2015 is silent rather than refused: the sentinel rect is
- // a *well-formed* rectangle, so validity checks phrased as
- // "right > left && bottom > top" admit it.
- let (left, top, right, bottom) = ICONIC_RECT;
- assert!(right > left, "sentinel width is positive: {right} > {left}");
- assert!(
- bottom > top,
- "sentinel height is positive: {bottom} > {top}"
- );
- }
-
#[test]
fn virtual_desktop_membership_has_no_magic_negative_ceiling() {
assert!(point_in_rect(-31920, 50, -40000, 0, 50000, 2000));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs
index 30c9c92182..42d7c5b32c 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs
@@ -1077,7 +1077,7 @@ mod nc_hit_tests {
#[cfg(test)]
mod wheel_tests {
- use super::{posted_press_message, wheel_mouse_data, WHEEL_DELTA};
+ use super::{posted_press_message, wheel_mouse_data};
use windows::Win32::UI::WindowsAndMessaging::{WM_LBUTTONDBLCLK, WM_LBUTTONDOWN};
#[test]
@@ -1101,28 +1101,17 @@ mod wheel_tests {
}
#[test]
- fn wheel_data_up_is_positive_one_notch() {
- // +1 tick (up / right) → +WHEEL_DELTA, bit-cast to u32.
- assert_eq!(wheel_mouse_data(1), WHEEL_DELTA as u32);
- assert_eq!(wheel_mouse_data(1), 120u32);
- }
-
- #[test]
- fn wheel_data_down_is_negative_one_notch() {
- // -1 tick (down / left) → -WHEEL_DELTA, bit-cast: 0xFFFFFF88.
- assert_eq!(wheel_mouse_data(-1), (-WHEEL_DELTA) as u32);
- assert_eq!(wheel_mouse_data(-1), 0xFFFF_FF88);
- }
-
- #[test]
- fn wheel_data_scales_with_ticks() {
- assert_eq!(wheel_mouse_data(3), (3 * WHEEL_DELTA) as u32);
- assert_eq!(wheel_mouse_data(3), 360u32);
- assert_eq!(wheel_mouse_data(-3) as i32, -360);
- }
-
- #[test]
- fn wheel_data_zero_is_zero() {
- assert_eq!(wheel_mouse_data(0), 0);
+ fn wheel_data_is_signed_wheel_delta_per_tick_bit_cast_to_u32() {
+ // +ticks scroll up / right; -ticks down / left. The signed notch count
+ // is carried as a two's-complement u32 in `mouseData`.
+ for (ticks, expected) in [
+ (0, 0u32),
+ (1, 120),
+ (3, 360),
+ (-1, 0xFFFF_FF88),
+ (-3, 0xFFFF_FE98),
+ ] {
+ assert_eq!(wheel_mouse_data(ticks), expected, "ticks={ticks}");
+ }
}
}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs b/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs
index 3a97749a16..1dcb54a238 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs
@@ -183,100 +183,4 @@ mod tests {
let bad_y = pack_xy(0, 65000);
assert!(matches!(bad_y, Err(LParamPackError::YOutOfRange(v)) if v == 65000));
}
-
- #[test]
- fn round_trip_negative_x_does_not_sign_flip_to_primary_monitor() {
- // The structural worry behind #1979's PostMessage half: a packing bug
- // that maps a negative-X click (secondary-monitor window-local coord)
- // to a positive X (primary-monitor coord) would manifest as the agent
- // reporting "click at (-1198, 292)" while the actual click lands on
- // the primary monitor.
- //
- // The receiver-side macro `GET_X_LPARAM` sign-extends via
- // `(int)(short)LOWORD(lp)`. As long as our packed `x` keeps its
- // two's-complement bit pattern in the low 16 bits, the receiver
- // recovers the original negative value. This test fails if anyone
- // ever replaces the implicit `i16` truncation with a zero-extending
- // cast (e.g. `(x as u32) & 0xFFFF` from an `i32::abs()`-style change).
- for x in [-32768_i32, -10000, -1795, -1198, -1, 0, 1, 1000] {
- let lp = pack_xy(x, 0).unwrap();
- let rx = unpack_x(lp);
- assert_eq!(rx, x, "sign-flip: x={x} round-tripped to {rx}");
- // And the same `x` must produce a strictly smaller LPARAM's low
- // word when its neighbour does — i.e. the bit pattern is
- // monotone in the i16 sense. We can check that by re-decoding
- // adjacent samples.
- if x < i16::MAX as i32 {
- let lp2 = pack_xy(x + 1, 0).unwrap();
- let rx2 = unpack_x(lp2);
- assert_eq!(rx2, x + 1, "monotonicity decode failed");
- }
- }
- }
-
- #[test]
- fn screen_coord_to_window_local_then_pack_monotonic() {
- // Approximate the full coord-translation pipeline for the reporter's
- // window: a window at screen origin (-1834, 0) (the DWM frame the
- // reporter's `bitmap_to_screen` math implies). For two adjacent screen
- // pixels (sx, y) and (sx+1, y), the window-local x increases by 1, so
- // the packed LPARAM's low word (when re-interpreted as i16) must also
- // increase by 1.
- //
- // This mirrors the #1980 `monotonic_in_x_and_y` test for the SendInput
- // path: any sign-mangling bug that folded negatives back into the
- // positive band would break the monotonicity here. Adjacent screen
- // pixels must produce adjacent packed coords for any sx along the
- // secondary monitor (`sx in [-1834, -915)`).
- let window_origin_x: i32 = -1834;
- let window_origin_y: i32 = 0;
- // Screen pixels sweeping across the secondary monitor (1920 px wide).
- let mut prev: Option<i32> = None;
- for sx in window_origin_x..(window_origin_x + 1920) {
- let local_x = sx - window_origin_x; // 0..1920 — well inside i16
- let local_y = 383 - window_origin_y;
- let lp =
- pack_xy(local_x, local_y).expect("post-ScreenToClient coords always fit in i16");
- let rx = unpack_x(lp);
- if let Some(p) = prev {
- assert_eq!(
- rx,
- p + 1,
- "non-monotonic at sx={sx}: prev decoded x={p}, current decoded x={rx}"
- );
- }
- prev = Some(rx);
- }
- }
-
- #[test]
- fn full_reporter_scenario_screen_minus_1795_through_postmessage_pipeline() {
- // End-to-end reconstruction of the reporter's `(-1795, 383)` path:
- //
- // 1. Agent passes window_id with DWM frame at screen X=-1834 and
- // bitmap pixel (38, 40) → screen (-1795, 383) (per bitmap_to_screen).
- // 2. post_click_screen → deepest_child → ScreenToClient(window, (-1795, 383))
- // = (39, 383) (window-local; positive; well inside i16).
- // 3. ChildWindowFromPointEx finds the deepest descendant; we'll assume the
- // target is the same window (a single-HWND app) for this pure-math test.
- // 4. make_lparam(39, 383) → LPARAM payload.
- // 5. Receiver decodes via GET_X_LPARAM / GET_Y_LPARAM.
- //
- // The assertion: the decoded coords must match step (2) exactly. Any
- // sign-flip or truncation in steps (4)-(5) would land the click on the
- // wrong screen — which is the reporter's symptom.
- let window_screen_left: i32 = -1834;
- let click_screen_x: i32 = -1795;
- let click_screen_y: i32 = 383;
- let local_x = click_screen_x - window_screen_left; // 39
- let local_y = click_screen_y; // window top at y=0
- assert_eq!(local_x, 39);
- let lp = pack_xy(local_x, local_y).unwrap();
- let (rx, ry) = (unpack_x(lp), unpack_y(lp));
- assert_eq!(
- (rx, ry),
- (39, 383),
- "PostMessage LPARAM packing dropped the reporter's coords on the floor"
- );
- }
}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
index d9ecc74bfa..87cdf875cd 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
@@ -1402,20 +1402,6 @@ struct WinZOrderEnforcer {
hwnd_isize: isize,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum WinZOrderPlacement {
- AboveTarget,
- ForceFrontNonTopmost,
-}
-
-fn win_z_order_placement(has_live_target: bool) -> WinZOrderPlacement {
- if has_live_target {
- WinZOrderPlacement::AboveTarget
- } else {
- WinZOrderPlacement::ForceFrontNonTopmost
- }
-}
-
/// Of the given window ids, return the one highest in the current z-order (the
/// first encountered walking top→bottom), or `None` if none are present. Used to
/// pick the single window the overlay should pin just above so it covers every
@@ -1480,11 +1466,8 @@ impl ZOrderEnforcer for WinZOrderEnforcer {
// pitfall macOS / Linux dodge by virtue of their explicit
// `orderWindow:above:` / `StackMode::ABOVE` APIs.
//
- match (
- win_z_order_placement(pinned_target.is_some()),
- pinned_target,
- ) {
- (WinZOrderPlacement::AboveTarget, Some(target)) => {
+ match pinned_target {
+ Some(target) => {
// Preserve the target-bound contract: normalize out of the
// topmost band, then insert exactly one slot above target.
let _ = SetWindowPos(
@@ -1512,7 +1495,7 @@ impl ZOrderEnforcer for WinZOrderEnforcer {
| SWP_NOOWNERZORDER,
);
}
- (WinZOrderPlacement::ForceFrontNonTopmost, None) => {
+ None => {
// HWND_TOP is subject to the foreground lock and can leave
// the overlay in a stale ordinary-band slot. A temporary
// topmost transition is lock-free; immediately demoting it
@@ -1527,7 +1510,6 @@ impl ZOrderEnforcer for WinZOrderEnforcer {
let _ = SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, flags);
let _ = SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, flags);
}
- _ => unreachable!("z-order placement must match target liveness"),
}
let _ = target;
@@ -1552,15 +1534,6 @@ mod tests {
assert_eq!(state.core.cfg.cursor_id, "session-blueprint");
}
- #[test]
- fn windows_z_order_branch_tracks_live_target_presence() {
- assert_eq!(win_z_order_placement(true), WinZOrderPlacement::AboveTarget);
- assert_eq!(
- win_z_order_placement(false),
- WinZOrderPlacement::ForceFrontNonTopmost
- );
- }
-
fn empty_map() -> RenderMap {
let mut cursors = IndexMap::new();
cursors.insert(
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs b/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs
index 92f6d1ea04..d4e94ed15d 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs
@@ -189,16 +189,6 @@ mod tests {
}
}
- #[test]
- fn windows_terminal_and_mintty_present() {
- // Spot-check the trio called out in the bug report so the
- // regression that motivated this list can't quietly slip back
- // out during a refactor.
- assert!(class_matches_terminal("CASCADIA_HOSTING_WINDOW_CLASS"));
- assert!(class_matches_terminal("mintty"));
- assert!(class_matches_terminal("ConsoleWindowClass"));
- }
-
#[test]
fn native_consolehost_refuses_both_delivery_modes() {
assert_eq!(
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index 20f036d0eb..8400c45f91 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -1181,8 +1181,7 @@ static GWS_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
#[cfg(test)]
mod get_window_state_max_image_dimension_tests {
- use super::{resolve_max_image_dimension, GetWindowStateTool, ToolState};
- use cua_driver_core::tool::Tool;
+ use super::resolve_max_image_dimension;
#[test]
fn canonical_override_wins_and_zero_requests_native_resolution() {
@@ -1202,16 +1201,6 @@ mod get_window_state_max_image_dimension_tests {
assert_eq!(resolve_max_image_dimension(800, None, Some(1568)), 800);
assert_eq!(resolve_max_image_dimension(0, None, Some(800)), 800);
}
-
- #[test]
- fn schema_advertises_canonical_override_and_native_resolution() {
- let tool = GetWindowStateTool {
- state: ToolState::new(None),
- };
- let property = &tool.def().input_schema["properties"]["max_image_dimension"];
- assert_eq!(property["type"], "integer");
- assert_eq!(property["minimum"], 0);
- }
}
/// Slack past `timeout_ms` before the walk task is abandoned.
@@ -4341,50 +4330,6 @@ mod pixel_click_transport_tests {
ActionExecutionRecord, ActionTransport, ActualDelivery, RequestedDelivery,
};
- #[test]
- fn pixel_uia_only_completed_miss_reaches_fallback_transport() {
- for (outcome, status) in [
- (PointInvokeOutcome::Invoked, None),
- (PointInvokeOutcome::Busy, Some("busy")),
- (PointInvokeOutcome::Timeout, Some("timeout")),
- (PointInvokeOutcome::Unavailable, Some("unavailable")),
- ] {
- // Exercise the same early-return boundary used before either
- // targeted injection or PostMessage in the pixel click route.
- let mut fallback_calls = 0;
- let result = finish_pixel_uia_attempt(outcome, 42, 10, 20).unwrap_or_else(|| {
- fallback_calls += 1;
- posted_pixel_click_result(42, "click")
- });
- assert_eq!(fallback_calls, 0, "{outcome:?}");
- assert_eq!(result.is_error.unwrap_or(false), status.is_some());
- let data = result.structured_content.unwrap();
- assert_eq!(data["path"], "ax");
- assert_eq!(data["effect"], "unverifiable");
- if let Some(status) = status {
- assert_eq!(data["uia_status"], status);
- assert_eq!(data["code"], "background_unavailable");
- }
- let record = ActionExecutionRecord::from_legacy(
- "click",
- &serde_json::json!({ "delivery_mode": "background" }),
- &data,
- )
- .expect("UIA outcome should normalize into the public action contract");
- let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))
- .expect("serialize ActionResult");
- assert_eq!(public["effect"], "unverifiable");
- }
- let mut fallback_calls = 0;
- let result =
- finish_pixel_uia_attempt(PointInvokeOutcome::Miss, 42, 10, 20).unwrap_or_else(|| {
- fallback_calls += 1;
- posted_pixel_click_result(42, "click")
- });
- assert_eq!(fallback_calls, 1);
- assert_eq!(result.structured_content.unwrap()["path"], "post_message");
- }
-
#[test]
fn uia_unavailable_errors_advertise_foreground_escalation() {
use cua_driver_core::action_record::EscalationKind;
@@ -4403,6 +4348,8 @@ mod pixel_click_transport_tests {
.expect("structured error");
assert_eq!(data["code"], "background_unavailable");
assert_eq!(data["uia_status"], status);
+ assert_eq!(data["path"], "ax");
+ assert_eq!(data["effect"], "unverifiable");
assert_eq!(
data["suggestion"].as_str(),
Some("Retry this action with delivery_mode:\"foreground\"."),
@@ -4436,6 +4383,15 @@ mod pixel_click_transport_tests {
text.contains("delivery_mode:\"foreground\""),
"text must surface the escalation: {text}"
);
+ let record = ActionExecutionRecord::from_legacy(
+ "click",
+ &serde_json::json!({ "delivery_mode": "background" }),
+ data,
+ )
+ .expect("UIA refusal should normalize into the public action contract");
+ let public = serde_json::to_value(record.public_result().expect("valid ActionResult"))
+ .expect("serialize ActionResult");
+ assert_eq!(public["effect"], "unverifiable", "{outcome:?}");
}
// The completed-miss boundary is unchanged: only Miss falls through,
// and a delivered Invoke carries no escalation hint.
@@ -4444,8 +4400,19 @@ mod pixel_click_transport_tests {
.expect("invoked click reports success");
assert!(!ok.is_error.unwrap_or(false));
let ok_data = ok.structured_content.as_ref().expect("structured success");
+ assert_eq!(ok_data["path"], "ax");
assert!(ok_data.get("escalation").is_none());
assert!(ok_data.get("suggestion").is_none());
+ let ok_record = ActionExecutionRecord::from_legacy(
+ "click",
+ &serde_json::json!({ "delivery_mode": "background" }),
+ ok_data,
+ )
+ .expect("UIA invoke should normalize into the public action contract");
+ let ok_public =
+ serde_json::to_value(ok_record.public_result().expect("valid ActionResult"))
+ .expect("serialize ActionResult");
+ assert_eq!(ok_public["effect"], "unverifiable");
// The hint must flow into the existing escalation pipeline, not sit
// as inert metadata: Timeout (the #3621 case) normalizes to a
// foreground-delivery escalation on the internal record.
@@ -10652,20 +10619,6 @@ mod cursor_key_resolution_tests {
NO_CURSOR
);
}
-
- #[test]
- fn two_parallel_sessions_resolve_distinct_keys() {
- // The regression this whole port fixes: two concurrent runs each declare
- // their own `session`, so they resolve DISTINCT cursor keys and own
- // separate overlay cursors instead of clobbering one shared cursor.
- let a =
- resolve_cursor_key(&json!({ "pid": 10, "element_index": 1, "session": "calc-2plus1" }));
- let b =
- resolve_cursor_key(&json!({ "pid": 20, "element_index": 1, "session": "calc-5plus6" }));
- assert_eq!(a, "calc-2plus1");
- assert_eq!(b, "calc-5plus6");
- assert_ne!(a, b);
- }
}
#[cfg(test)]
@@ -10674,118 +10627,41 @@ mod launch_focus_restore_decision_tests {
first_unopened_shell_url_index, should_restore_foreground_after_launch, LaunchTargetShape,
};
- fn empty() -> LaunchTargetShape {
- LaunchTargetShape {
- has_aumid: false,
- has_bundle_id: false,
- has_name: false,
- has_path: false,
- has_launch_path: false,
- has_urls: false,
- }
- }
-
#[test]
- fn urls_only_skips_restore() {
- // `launch_app({urls: ["https://example.com"]})` — user explicitly
- // asked for navigation in the default browser. The freshly-launched
- // browser instance IS the legitimate foreground; restoring would
- // hide the page the user wanted to see.
- let shape = LaunchTargetShape {
- has_urls: true,
- ..empty()
- };
- assert!(!should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn name_only_restores() {
- let shape = LaunchTargetShape {
- has_name: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn path_only_restores() {
- let shape = LaunchTargetShape {
- has_path: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn aumid_only_restores() {
- // Note: AUMID path has its own synchronous restore in launch_uwp.rs,
- // but the decision function still says "yes, this is an
- // app-identifying launch" — the caller (`LaunchAppTool::invoke`)
- // gates the polling spawn on `aumid_for_uwp.is_none()` so we don't
- // double-restore.
- let shape = LaunchTargetShape {
- has_aumid: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn bundle_id_only_restores() {
- let shape = LaunchTargetShape {
- has_bundle_id: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn launch_path_only_restores() {
- let shape = LaunchTargetShape {
- has_launch_path: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn name_with_urls_restores() {
- // App-identifying field present alongside urls — the user wants
- // the named app to open these URLs in the background, NOT for the
- // urls to take over the default browser's foreground. Restore.
- let shape = LaunchTargetShape {
- has_name: true,
- has_urls: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn path_with_urls_restores() {
- let shape = LaunchTargetShape {
- has_path: true,
- has_urls: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn aumid_with_urls_restores() {
- let shape = LaunchTargetShape {
- has_aumid: true,
- has_urls: true,
- ..empty()
- };
- assert!(should_restore_foreground_after_launch(shape));
- }
-
- #[test]
- fn no_target_does_not_restore() {
- // Empty params (validated as an error before launch dispatch) — no
- // restore needed because nothing was launched.
- assert!(!should_restore_foreground_after_launch(empty()));
+ fn only_app_identifying_launches_restore_foreground() {
+ for (fields, restore) in [
+ // A urls-only launch explicitly asks for navigation in the default
+ // browser; that browser is the legitimate foreground.
+ (&["urls"][..], false),
+ (&["name"], true),
+ (&["path"], true),
+ // The AUMID path restores synchronously in launch_uwp.rs; the
+ // caller gates the polling restore on `aumid_for_uwp.is_none()`.
+ (&["aumid"], true),
+ (&["bundle_id"], true),
+ (&["launch_path"], true),
+ // An app-identifying field alongside urls opens them in that app
+ // in the background, so the prior foreground is restored.
+ (&["name", "urls"], true),
+ (&["path", "urls"], true),
+ (&["aumid", "urls"], true),
+ // Nothing was launched.
+ (&[], false),
+ ] {
+ let shape = LaunchTargetShape {
+ has_aumid: fields.contains(&"aumid"),
+ has_bundle_id: fields.contains(&"bundle_id"),
+ has_name: fields.contains(&"name"),
+ has_path: fields.contains(&"path"),
+ has_launch_path: fields.contains(&"launch_path"),
+ has_urls: fields.contains(&"urls"),
+ };
+ assert_eq!(
+ should_restore_foreground_after_launch(shape),
+ restore,
+ "{fields:?}"
+ );
+ }
}
#[test]
@@ -10912,32 +10788,20 @@ mod chromium_flag_injection_tests {
}
#[cfg(test)]
-mod click_button_schema_tests {
+mod click_capture_id_schema_tests {
use super::ClickTool;
use cua_driver_core::tool::Tool;
- /// Surface 5: schema must keep advertising the three canonical button
- /// values. Windows was already shipping `button` (pre-Surface-5) so this
- /// test is the freeze test — guards against an inadvertent rename/removal.
+ /// The portable click contract pins `button` and the other accepted
+ /// fields. A live schema may broaden `capture_id`, which the subset gate
+ /// allows, so the non-empty bound is pinned here.
#[test]
- fn schema_advertises_button_enum() {
+ fn schema_requires_non_empty_capture_id() {
let tool = ClickTool {
state: super::ToolState::new(None),
};
let d = tool.def();
let props = d.input_schema.get("properties").expect("properties");
- let button = props.get("button").expect("button field present");
- assert_eq!(button.get("type").and_then(|v| v.as_str()), Some("string"));
- let enum_vals: Vec<&str> = button
- .get("enum")
- .and_then(|v| v.as_array())
- .expect("button.enum present")
- .iter()
- .filter_map(|v| v.as_str())
- .collect();
- for need in ["left", "right", "middle"] {
- assert!(enum_vals.contains(&need), "missing {need} in button.enum");
- }
let capture_id = props.get("capture_id").expect("capture_id field present");
assert_eq!(capture_id["type"], "string");
assert_eq!(capture_id["minLength"], 1);
@@ -10947,7 +10811,6 @@ mod click_button_schema_tests {
#[cfg(test)]
mod snapshot_coordinate_tests {
use super::{focus_by_pixel_click_args, ToolState, ZoomTool};
- use crate::uia::cache::{CachedSnapshot, SnapshotKind};
use cua_driver_core::tool::Tool;
#[test]
@@ -10958,33 +10821,6 @@ mod snapshot_coordinate_tests {
let required = tool.def().input_schema["required"].as_array().unwrap();
assert!(!required.iter().any(|field| field == "pid"));
assert!(tool.def().input_schema["properties"].get("pid").is_some());
-
- tool.state.element_cache.publish_for_session(
- 42,
- 7,
- CachedSnapshot::from_nodes(&[], SnapshotKind::Uia),
- Some("zoom-optional-pid-windows"),
- Some(2.0),
- );
- let (pid, context) = tool
- .state
- .element_cache
- .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-windows"))
- .unwrap();
- assert_eq!(pid, 42);
- assert_eq!(context.window_id, 7);
- tool.state.element_cache.publish_for_session(
- 43,
- 7,
- CachedSnapshot::from_nodes(&[], SnapshotKind::Uia),
- Some("zoom-optional-pid-windows"),
- Some(1.0),
- );
- assert!(tool
- .state
- .element_cache
- .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-windows"))
- .is_err());
}
#[test]
@@ -11111,20 +10947,19 @@ mod desktop_scope_tests {
// ── get_desktop_state schema ──────────────────────────────────────────────
#[test]
- fn get_desktop_state_schema_shape() {
+ fn get_desktop_state_schema_rejects_window_scoped_fields() {
let tool = GetDesktopStateTool {
state: super::ToolState::new(None),
};
+ // The portable get_desktop_state contract pins the accepted fields and
+ // annotations; it cannot see a window-scoped field added to live.
let d = tool.def();
- assert!(d.read_only, "get_desktop_state must be read_only");
let props = d.input_schema["properties"].as_object().unwrap();
assert!(!props.contains_key("pid"), "must not accept pid");
assert!(
!props.contains_key("window_id"),
"must not accept window_id"
);
- assert!(props.contains_key("session"));
- assert!(props.contains_key("screenshot_out_file"));
assert_eq!(d.input_schema["additionalProperties"], json!(false));
}
}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs
index e4107a4e98..9f6e95d0fb 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs
@@ -1,5 +1,5 @@
-//! Runtime reproduction + regression guard for the UIA element-cache
-//! use-after-free fixed in d95b89a1 (retain-under-lock / `RetainedElement`).
+//! Regression guard for the UIA element-cache use-after-free fixed in
+//! d95b89a1 (retain-under-lock / `RetainedElement`).
//!
//! THE RACE (what these tests model):
//! Two concurrent sessions drive the same (pid, hwnd).
@@ -8,32 +8,25 @@
//! every cached `IUIAutomationElement`.
//! - Session B: `click` / `type_text` / `set_value` looked the element up out
//! of the cache and is mid-action, dereferencing the same COM pointer.
-//! With the PRE-FIX accessor (`get_element_ptr`, a bare `usize` copy with no
-//! AddRef) B's pointer can be `Release`d to zero by A between the lookup and
-//! the dereference → use-after-free → daemon crash. This is the Windows
-//! analogue of the macOS #1796 `AXUIElementCopyActionNames` fault.
+//! A bare pointer copy with no AddRef could be `Release`d to zero by A
+//! between the lookup and the dereference → use-after-free → daemon crash.
+//! This is the Windows analogue of the macOS #1796
+//! `AXUIElementCopyActionNames` fault.
//!
//! HOW WE REPRODUCE IT DETERMINISTICALLY WITHOUT A GUI:
//! The cache only ever calls IUnknown vtable slots on the cached pointers
//! (`AddRef` via `clone()`, `Release` via `drop`). So we feed it a real,
//! independently-refcounted COM-ABI object of our own (`FakeObj`) with a
//! hand-rolled IUnknown vtable. The cache's real `with_snapshot` mutex, real
-//! `CachedSnapshot::drop`, and the real `get_element_retained` AddRef-under-
-//! lock all run unchanged against it.
+//! `CachedSnapshot::drop`, and the real retain-under-lock resolution all run
+//! unchanged against it. An AddRef/Release seen while the refcount is
+//! already <= 0 bumps a shared `uaf_hits` counter (a use-after-free that a
+//! sanitizer would flag); memory stays mapped so the assertion is
+//! deterministic and the test process never actually faults.
//!
-//! `FakeObj` is instrumented two ways:
-//! - logical: an AddRef/Release seen while the refcount is already <= 0
-//! bumps a shared `uaf_hits` counter (a use-after-free that a sanitizer
-//! would flag) — memory stays mapped so the assertion is deterministic
-//! and the test process never actually faults.
-//! - poison: on Release-to-zero we overwrite the object's vtable pointer
-//! with garbage, so the *next* AddRef dereferences it and the process
-//! takes a real STATUS_ACCESS_VIOLATION — the dramatic "old code crashes"
-//! demonstration. Gated behind `#[ignore]` so it never aborts the suite.
-//!
-//! `force_interleave` pins the dangerous ordering (B looks up → A replaces +
-//! releases → B dereferences) with channels instead of relying on luck, so
-//! BEFORE deterministically trips and AFTER deterministically survives.
+//! `run_forced_interleave` pins the dangerous ordering (B looks up → A
+//! replaces + releases → B dereferences) with channels instead of relying on
+//! luck.
use super::{CachedSnapshot, ElementCache, RetainedElement, SnapshotKind};
use cua_driver_core::element_token::{token_for, ResolvedElement};
@@ -61,8 +54,6 @@ struct FakeObj {
/// Shared counter: bumped whenever AddRef/Release touches us while our
/// refcount is already <= 0 — i.e. a use-after-free.
uaf_hits: *const AtomicUsize,
- /// When true, Release-to-zero poisons `vtbl` so the next vtable call faults.
- poison_on_zero: bool,
}
unsafe extern "system" fn fake_query_interface(
@@ -92,14 +83,7 @@ unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 {
if prev <= 0 {
(*(*obj).uaf_hits).fetch_add(1, Ordering::SeqCst);
}
- let now = prev - 1;
- if now == 0 && (*obj).poison_on_zero {
- // Overwrite the vtable pointer in place. The allocation stays mapped,
- // but the next AddRef will read this garbage and call through it.
- let vtbl_slot = std::ptr::addr_of_mut!((*obj).vtbl) as *mut usize;
- vtbl_slot.write(0xD15E_A5ED_DEAD_BEEFusize);
- }
- now.max(0) as u32
+ (prev - 1).max(0) as u32
}
static VTBL: FakeVtbl = FakeVtbl {
@@ -110,14 +94,12 @@ static VTBL: FakeVtbl = FakeVtbl {
/// Allocate a fake COM object with refcount 1 (the single ref the cache "owns",
/// matching the walker's clone()+forget() hand-off). Leaked on purpose: the
-/// logical tests must keep the memory mapped to observe post-free touches; the
-/// poison test crashes before cleanup would matter.
-fn make_fake(uaf_hits: &'static AtomicUsize, poison_on_zero: bool) -> usize {
+/// tests must keep the memory mapped to observe post-free touches.
+fn make_fake(uaf_hits: &'static AtomicUsize) -> usize {
let obj = Box::new(FakeObj {
vtbl: &VTBL as *const FakeVtbl,
refcount: AtomicIsize::new(1),
uaf_hits: uaf_hits as *const AtomicUsize,
- poison_on_zero,
});
Box::into_raw(obj) as usize
}
@@ -137,10 +119,6 @@ fn snapshot_with(ptrs: Vec<usize>) -> CachedSnapshot {
}
}
-fn old_get_element_ptr(cache: &ElementCache, snapshot: u32, idx: usize) -> Option<usize> {
- acquire(cache, snapshot, idx).map(|guard| guard.as_ptr())
-}
-
fn acquire(cache: &ElementCache, snapshot: u32, idx: usize) -> Option<RetainedElement> {
match cache
.resolve_element_args(
@@ -160,7 +138,7 @@ fn acquire(cache: &ElementCache, snapshot: u32, idx: usize) -> Option<RetainedEl
/// The mid-action dereference a tool performs: reconstruct the interface from
/// the raw pointer and touch its vtable (AddRef then Release). On a live object
-/// this is harmless; on a freed/poisoned one it is the use-after-free.
+/// this is harmless; on a freed one it is the use-after-free.
unsafe fn touch_vtable(ptr: usize) {
let elem: IUIAutomationElement = IUIAutomationElement::from_raw(ptr as *mut c_void);
let dup = elem.clone(); // AddRef — reads the vtable
@@ -172,14 +150,13 @@ const PID: u32 = 4242;
const HWND: u64 = (1_u64 << 40) | 0x1234;
/// Forced interleave: B looks up the element, THEN A replaces+releases the
-/// snapshot, THEN B dereferences. `use_retained` selects the fixed path
-/// (`get_element_retained`, AddRef under lock) vs the pre-fix bare path.
-/// Returns the number of use-after-free touches observed.
-fn run_forced_interleave(use_retained: bool, poison_on_zero: bool) -> usize {
+/// snapshot, THEN B dereferences through its retained guard. Returns the
+/// number of use-after-free touches observed.
+fn run_forced_interleave() -> usize {
let uaf_hits: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
let cache = Arc::new(ElementCache::new());
- let ptr = make_fake(uaf_hits, poison_on_zero);
+ let ptr = make_fake(uaf_hits);
let snapshot = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));
let (b_looked_up_tx, b_looked_up_rx) = mpsc::channel::<()>();
@@ -187,20 +164,12 @@ fn run_forced_interleave(use_retained: bool, poison_on_zero: bool) -> usize {
let cache_b = cache.clone();
let worker_b = thread::spawn(move || {
- if use_retained {
- // FIXED path: AddRef under the lock; guard pins the object alive.
- let guard = acquire(&cache_b, snapshot, 0).expect("element present");
- b_looked_up_tx.send(()).unwrap();
- a_replaced_rx.recv().unwrap(); // A has now replaced + released
- unsafe { touch_vtable(guard.as_ptr()) }; // safe: guard holds +1
- drop(guard);
- } else {
- // PRE-FIX path: bare pointer, no AddRef.
- let raw = old_get_element_ptr(&cache_b, snapshot, 0).expect("element present");
- b_looked_up_tx.send(()).unwrap();
- a_replaced_rx.recv().unwrap(); // A has now replaced + released → freed
- unsafe { touch_vtable(raw) }; // USE-AFTER-FREE
- }
+ // AddRef under the lock; the guard pins the object alive.
+ let guard = acquire(&cache_b, snapshot, 0).expect("element present");
+ b_looked_up_tx.send(()).unwrap();
+ a_replaced_rx.recv().unwrap(); // A has now replaced + released
+ unsafe { touch_vtable(guard.as_ptr()) }; // safe: guard holds +1
+ drop(guard);
});
let cache_a = cache.clone();
@@ -217,29 +186,15 @@ fn run_forced_interleave(use_retained: bool, poison_on_zero: bool) -> usize {
uaf_hits.load(Ordering::SeqCst)
}
-// ---- Regression guards (run in the normal suite) ----------------------------
-
-/// AFTER: the fixed `get_element_retained` path survives the exact dangerous
-/// interleave with zero use-after-free touches.
+/// The retained resolution path survives the exact dangerous interleave with
+/// zero use-after-free touches.
#[test]
fn fixed_path_survives_concurrent_replace() {
- let uaf = run_forced_interleave(/* use_retained */ true, /* poison */ false);
+ let uaf = run_forced_interleave();
assert_eq!(uaf, 0, "retained path must not touch a released element");
}
-/// BEFORE: the pre-fix bare-pointer path deterministically commits a
-/// use-after-free under the same interleave. Asserting `> 0` documents the bug
-/// the fix closes (this test PASSES — it proves the old code was unsafe).
-#[test]
-fn prefix_path_commits_use_after_free() {
- let uaf = run_forced_interleave(/* use_retained */ false, /* poison */ false);
- assert!(
- uaf > 0,
- "pre-fix path must hit the released element (the UAF)"
- );
-}
-
-/// AFTER, under real (unforced) concurrency: hammer get_element_retained +
+/// Under real (unforced) concurrency: hammer retained resolution +
/// snapshot-replace from many threads in a tight loop; assert zero UAF.
#[test]
fn fixed_path_stress_no_uaf() {
@@ -247,7 +202,7 @@ fn fixed_path_stress_no_uaf() {
let cache = Arc::new(ElementCache::new());
// Seed a snapshot of several elements.
- let seed: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits, false)).collect();
+ let seed: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits)).collect();
let latest = Arc::new(std::sync::atomic::AtomicU32::new(cache.publish(
PID as i32,
HWND,
@@ -263,7 +218,7 @@ fn fixed_path_stress_no_uaf() {
let latest = latest.clone();
handles.push(thread::spawn(move || {
for _ in 0..ITERS {
- let fresh: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits, false)).collect();
+ let fresh: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits)).collect();
let snapshot = cache_r.publish(PID as i32, HWND, snapshot_with(fresh));
latest.store(snapshot, Ordering::SeqCst);
}
@@ -297,7 +252,7 @@ fn fixed_path_stress_no_uaf() {
fn exact_snapshot_retains_matching_identity_and_geometry() {
let hits = Box::leak(Box::new(AtomicUsize::new(0)));
let cache = ElementCache::new();
- let ptr = make_fake(hits, false);
+ let ptr = make_fake(hits);
let mut payload = snapshot_with(vec![ptr]);
payload.elements[0].kind = SnapshotKind::Msaa;
payload.elements[0].center = (31, 47);
@@ -305,11 +260,7 @@ fn exact_snapshot_retains_matching_identity_and_geometry() {
payload.elements[0].msaa_role = Some(0x38);
let first = cache.publish(PID as i32, HWND, payload);
let guard = acquire(&cache, first, 0).unwrap();
- let second = cache.publish(
- PID as i32,
- HWND,
- snapshot_with(vec![make_fake(hits, false)]),
- );
+ let second = cache.publish(PID as i32, HWND, snapshot_with(vec![make_fake(hits)]));
assert!(acquire(&cache, first, 0).is_none());
assert_eq!(guard.as_ptr(), ptr);
assert_eq!(guard.kind, SnapshotKind::Msaa);
@@ -344,19 +295,19 @@ fn exact_snapshot_retains_matching_identity_and_geometry() {
fn eviction_remove_and_clear_release_payload_but_not_acquired_guard() {
let hits = Box::leak(Box::new(AtomicUsize::new(0)));
let cache = ElementCache::new();
- let ptr = make_fake(hits, false);
+ let ptr = make_fake(hits);
let first = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));
let guard = acquire(&cache, first, 0).unwrap();
for offset in 1..=cua_driver_core::element_token::LRU_CAP_PER_PID {
cache.publish(
PID as i32,
HWND + offset as u64,
- snapshot_with(vec![make_fake(hits, false)]),
+ snapshot_with(vec![make_fake(hits)]),
);
}
assert!(acquire(&cache, first, 0).is_none());
unsafe { touch_vtable(guard.as_ptr()) };
- let removed_ptr = make_fake(hits, false);
+ let removed_ptr = make_fake(hits);
let removed = cache.publish(PID as i32, HWND, snapshot_with(vec![removed_ptr]));
cache.remove(PID as i32, HWND);
assert!(acquire(&cache, removed, 0).is_none());
@@ -384,8 +335,8 @@ fn eviction_remove_and_clear_release_payload_but_not_acquired_guard() {
async fn detached_worker_keeps_only_admitted_target_and_geometry() {
let hits = Box::leak(Box::new(AtomicUsize::new(0)));
let cache = ElementCache::new();
- let target = make_fake(hits, false);
- let sibling = make_fake(hits, false);
+ let target = make_fake(hits);
+ let sibling = make_fake(hits);
let mut payload = snapshot_with(vec![target, sibling]);
payload.elements[0].center = (71, 83);
payload.elements[0].rect = Some((61, 73, 81, 93));
@@ -445,7 +396,7 @@ fn recording_metadata_uses_snapshot_without_native_geometry() {
let hits = Box::leak(Box::new(AtomicUsize::new(0)));
let cache = Arc::new(ElementCache::new());
cua_driver_core::element_cache::register_runtime_cache(&cache);
- let ptr = make_fake(hits, false);
+ let ptr = make_fake(hits);
let id = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));
let args = serde_json::json!({"element_token": token_for(id, 0)});
assert_eq!(
@@ -471,7 +422,7 @@ fn null_native_pointer_is_not_an_actionable_member() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cancelled_caller_keeps_the_blocking_workers_native_target_alive() {
let hits = Box::leak(Box::new(AtomicUsize::new(0)));
- let ptr = make_fake(hits, false);
+ let ptr = make_fake(hits);
let cache = ElementCache::new();
let snapshot = cache.publish(PID as i32, HWND, snapshot_with(vec![ptr]));
let guard = acquire(&cache, snapshot, 0).unwrap();
@@ -509,7 +460,7 @@ async fn cancelled_caller_keeps_the_blocking_workers_native_target_alive() {
#[test]
fn unpublished_payload_releases_its_walker_retain() {
let hits = Box::leak(Box::new(AtomicUsize::new(0)));
- let ptr = make_fake(hits, false);
+ let ptr = make_fake(hits);
drop(snapshot_with(vec![ptr]));
assert_eq!(
unsafe { (*(ptr as *const FakeObj)).refcount.load(Ordering::SeqCst) },
@@ -517,31 +468,3 @@ fn unpublished_payload_releases_its_walker_retain() {
);
assert_eq!(hits.load(Ordering::SeqCst), 0);
}
-
-// ---- Hard-crash demonstrations (run manually, never in the suite) -----------
-
-/// BEFORE (real fault): the pre-fix path takes a genuine
-/// STATUS_ACCESS_VIOLATION. Poison-on-zero makes the otherwise heap-reuse-
-/// dependent UAF deterministic. Run with:
-/// cargo test -p platform-windows -- --ignored --exact \
-/// uia::cache::cache_uaf_repro::prefix_path_real_access_violation
-/// EXPECTED: the test process crashes (exception 0xC0000005); it does NOT
-/// print "test result: ok".
-#[test]
-#[ignore]
-fn prefix_path_real_access_violation() {
- let uaf = run_forced_interleave(/* use_retained */ false, /* poison */ true);
- // Unreachable in practice — the dereference of the poisoned vtable faults.
- println!("SURVIVED unexpectedly (uaf_hits={uaf})");
-}
-
-/// AFTER (control): the same poison-on-zero setup, but the retained guard keeps
-/// the refcount above zero during the dereference, so the vtable is never
-/// poisoned while in use. EXPECTED: clean exit, prints the survival line.
-#[test]
-#[ignore]
-fn fixed_path_no_access_violation() {
- let uaf = run_forced_interleave(/* use_retained */ true, /* poison */ true);
- assert_eq!(uaf, 0);
- println!("SURVIVED as expected (uaf_hits={uaf})");
-}