Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.
//! Integration test against the CuaTestHarness.AppKit Swift app.
//!
//! Mirror of `harness_wpf_test.rs` for the macOS AppKit hosting pattern.
//! The harness app lives at `libs/cua-driver/tests/fixtures/apps/macos/appkit`
//! and is published into `libs/cua-driver/rust/test-apps/harness-appkit/`
//! by `libs/cua-driver/tests/fixtures/build/macos.sh`.
//!
//! Scenarios (see `libs/cua-driver/tests/fixtures/shared/scenarios.json`
//! `appkit` section):
//! - counter : NSButton AXPress invocation increments counter
//! - text_body : get_window_state extracts known marker text
//! - text_input : type_text into NSTextField updates mirror label
//! - click_target : right_click / double_click recognised by NSView
//! - scroll_target : scroll updates VerticalOffset label
//! - ns_menubar : main menubar item enumerable (Mac-specific)
//!
//! Run locally (after `libs/cua-driver/tests/fixtures/build/macos.sh`):
//! cargo test --test harness_appkit_test -- --ignored --nocapture
//!
//! Tests are `#[ignore]` so they don't run in plain `cargo test`.
//!
//! The macOS lane preflight verifies the installed daemon identity and TCC
//! grants before these tests run. Missing fixtures or AX trees fail here too.
#![cfg(target_os = "macos")]
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use cua_driver_testkit::ax::{element_index_by_id, element_index_containing, has_id, looks_empty};
use cua_driver_testkit::e2e::{
execute_case, native_background_case, native_foreground_case, native_readonly_case,
recording_evidence, DriverRoute, Evidence, Observation, OracleKind, Targeting,
};
use cua_driver_testkit::observer::{NativeObserver, ObserverBackend, TargetWindow};
use cua_driver_testkit::sentinel::{run_with_background_oracles, ForegroundSentinel};
use cua_driver_testkit::{Driver, McpDriver, ToolResponse};
#[path = "support/appkit_snapshot_publication.rs"]
mod snapshot_publication;
// ── paths ────────────────────────────────────────────────────────────────────
fn harness_app() -> PathBuf {
if let Ok(p) = std::env::var("HARNESS_APPKIT_APP") {
let pb = PathBuf::from(p);
if pb.exists() {
return pb;
}
}
cua_driver_testkit::harness_app("harness-appkit", "CuaTestHarness.AppKit.app")
}
fn harness_exe() -> PathBuf {
harness_app().join("Contents/MacOS/CuaTestHarness.AppKit")
}
// ── harness fixture ──────────────────────────────────────────────────────────
struct Harness {
_app: Child,
pid: u32,
}
impl Harness {
fn launch() -> Self {
Self::launch_with_command_oracle(None)
}
fn launch_with_command_oracle(command_oracle: Option<&Path>) -> Self {
Self::launch_with_oracles(command_oracle, None)
}
fn launch_with_oracles(command_oracle: Option<&Path>, pointer_oracle: Option<&Path>) -> Self {
Self::launch_with_options(command_oracle, pointer_oracle, false)
}
fn launch_with_options(
command_oracle: Option<&Path>,
pointer_oracle: Option<&Path>,
keep_ordered_front: bool,
) -> Self {
Self::spawn(
command_oracle,
pointer_oracle,
keep_ordered_front,
None,
&[],
)
.presented()
}
/// Launch with the opt-in erroring toggles (`erroring_toggles` scenario).
fn launch_with_erroring_toggles() -> Self {
Self::spawn(
None,
None,
false,
None,
&[("CUA_APPKIT_ERRORING_TOGGLES", "1")],
)
.presented()
}
/// Launch with the opt-in disabled checkbox (`disabled_control` scenario).
fn launch_with_disabled_control() -> Self {
Self::spawn(
None,
None,
false,
None,
&[("CUA_APPKIT_DISABLED_CONTROL", "1")],
)
.presented()
}
fn presented(self) -> Self {
// Settle for window creation + activation.
std::thread::sleep(Duration::from_millis(800));
self.await_presented();
self
}
/// Launch a harness that holds off entering its run loop for `delay`
/// after registering its window, without waiting for its launch posture.
fn launch_slowly(delay: Duration) -> Self {
Self::spawn(None, None, false, Some(delay), &[])
}
fn spawn(
command_oracle: Option<&Path>,
pointer_oracle: Option<&Path>,
keep_ordered_front: bool,
launch_delay: Option<Duration>,
env: &[(&str, &str)],
) -> Self {
let exe = harness_exe();
assert!(
exe.exists(),
"required AppKit harness is missing at {exe:?}; run the fixture build"
);
// Launch the binary directly (not via `open`) so we control the pid
// and can kill it cleanly on Drop. The app still installs an AppKit
// window via NSApp.run().
let mut command = Command::new(&exe);
command.stdout(Stdio::null()).stderr(Stdio::null());
if let Some(path) = command_oracle {
command.env("CUA_APPKIT_COMMAND_ORACLE", path);
}
if let Some(path) = pointer_oracle {
command.env("CUA_APPKIT_POINTER_ORACLE", path);
}
if keep_ordered_front {
command.env("CUA_APPKIT_KEEP_ORDERED_FRONT", "1");
}
if let Some(delay) = launch_delay {
command.env("CUA_APPKIT_LAUNCH_DELAY_MS", delay.as_millis().to_string());
}
command.envs(env.iter().copied());
let app = command
.spawn()
.unwrap_or_else(|error| panic!("launch AppKit harness {exe:?}: {error}"));
let pid = app.id();
Self { _app: app, pid }
}
/// Wait until the harness has finished launching and shows its window.
///
/// Its window is registered with WindowServer before the app enters its
/// run loop, so `find_window` can succeed while every accessibility
/// request still fails. On a cold hosted runner the first launch spends
/// seconds in that state; a case must not start there.
fn await_presented(&self) {
let deadline = Instant::now() + HARNESS_LAUNCH_TIMEOUT;
while !cua_driver_testkit::observer::macos::application_presented(self.pid) {
assert!(
Instant::now() < deadline,
"AppKit harness pid {} did not finish launching and show its window within {:?}",
self.pid,
HARNESS_LAUNCH_TIMEOUT
);
std::thread::sleep(Duration::from_millis(50));
}
}
}
/// Upper bound for a harness launch, cold first launches included.
const HARNESS_LAUNCH_TIMEOUT: Duration = Duration::from_secs(20);
impl Drop for Harness {
fn drop(&mut self) {
let _ = self._app.kill();
let _ = self._app.wait();
std::thread::sleep(Duration::from_millis(200));
}
}
// ── window / element helpers ─────────────────────────────────────────────────
fn snapshot_elements(driver: &mut McpDriver, pid: u32, window_id: u64) -> ToolResponse {
driver.call(
"get_window_state",
serde_json::json!({
"pid": pid as i64,
"window_id": window_id,
"capture_mode": "ax"
}),
)
}
struct FrontWindow {
window_id: u64,
z_index: i64,
app_name: String,
title: String,
}
impl std::fmt::Display for FrontWindow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"window {} (z_index {}, {} {:?})",
self.window_id, self.z_index, self.app_name, self.title
)
}
}
/// The window WindowServer ranks first in the global layer-0 order, read from
/// `list_windows` (`z_index`: higher values are closer to the front) so the
/// observation does not depend on the tool under test.
fn front_layer_zero_window(driver: &mut McpDriver) -> Option<FrontWindow> {
let response = driver.call("list_windows", serde_json::json!({"on_screen_only": true}));
response.structured()["windows"]
.as_array()?
.iter()
.filter(|window| window["layer"].as_i64() == Some(0))
.filter_map(|window| {
Some(FrontWindow {
window_id: window["window_id"].as_u64()?,
z_index: window["z_index"].as_i64()?,
app_name: window["app_name"].as_str().unwrap_or_default().to_owned(),
title: window["title"].as_str().unwrap_or_default().to_owned(),
})
})
.max_by_key(|window| window.z_index)
}
/// Poll the global layer-0 order until `window_id` leads it, up to 3s, and
/// return the last observation so a caller can name whatever leads instead.
fn await_front_layer_zero_window(driver: &mut McpDriver, window_id: u64) -> Option<FrontWindow> {
let deadline = Instant::now() + Duration::from_secs(3);
loop {
let front = front_layer_zero_window(driver);
if front.as_ref().map(|window| window.window_id) == Some(window_id)
|| Instant::now() >= deadline
{
return front;
}
std::thread::sleep(Duration::from_millis(100));
}
}
fn element_token_by_id(snapshot: &ToolResponse, identifier: &str) -> String {
let index = element_index_by_id(snapshot.tree_text(), identifier)
.unwrap_or_else(|| panic!("{identifier} element_index not found"));
snapshot.structured()["elements"]
.as_array()
.and_then(|elements| {
elements
.iter()
.find(|element| element["element_index"].as_u64() == Some(index))
})
.and_then(|element| element["element_token"].as_str())
.unwrap_or_else(|| panic!("{identifier} element_token not found"))
.to_owned()
}
fn element_pixel_frame(snapshot: &ToolResponse, identifier: &str) -> (f64, f64, f64, f64) {
let index = element_index_by_id(snapshot.tree_text(), identifier)
.unwrap_or_else(|| panic!("{identifier} element_index not found"));
let elements = snapshot.structured()["elements"]
.as_array()
.expect("AppKit structured elements");
let element = elements
.iter()
.find(|element| element["element_index"].as_u64() == Some(index))
.unwrap_or_else(|| panic!("{identifier} element frame not found"));
let window = elements
.iter()
.find(|element| element["role"].as_str() == Some("AXWindow"))
.expect("AppKit window frame");
let scale = snapshot.structured()["screenshot_width"]
.as_f64()
.unwrap_or(1.0)
/ window["frame"]["w"].as_f64().unwrap_or(1.0).max(1.0);
(
(element["frame"]["x"].as_f64().unwrap_or(0.0)
- window["frame"]["x"].as_f64().unwrap_or(0.0))
* scale,
(element["frame"]["y"].as_f64().unwrap_or(0.0)
- window["frame"]["y"].as_f64().unwrap_or(0.0))
* scale,
element["frame"]["w"].as_f64().unwrap_or(0.0) * scale,
element["frame"]["h"].as_f64().unwrap_or(0.0) * scale,
)
}
fn run_case(
case: cua_driver_testkit::e2e::CaseSpec,
test: impl FnOnce(u32, u64, &mut McpDriver) -> Observation,
) {
let cell_id = case.cell_id.clone();
let delivery = case.delivery;
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&cell_id)
.expect("start installed macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let harness = Harness::launch();
let (wid, _) = driver
.find_window(harness.pid as i64, "CuaTestHarness AppKit")
.expect("AppKit main window not found");
if delivery != cua_driver_testkit::e2e::Delivery::Background {
driver.start_behavior_recording();
}
test(harness.pid, wid, &mut driver)
});
}
fn run_background_case(
action: &str,
route: DriverRoute,
test: impl FnOnce(u32, u64, &mut McpDriver),
) {
run_background_case_targeting(action, Targeting::Ax, route, test);
}
fn run_background_case_targeting(
action: &str,
targeting: Targeting,
route: DriverRoute,
test: impl FnOnce(u32, u64, &mut McpDriver),
) {
run_case(
native_background_case("appkit", action, targeting, route),
|pid, wid, driver| {
let (_, passed) = run_with_background_oracles(
driver,
TargetWindow {
pid,
native_id: wid,
},
|driver| test(pid, wid, driver),
)
.unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));
Observation::delivered_with_fixture_state(passed)
},
);
}
// ── tests ────────────────────────────────────────────────────────────────────
#[test]
#[ignore]
fn harness_appkit_exact_activation_with_agent_cursor() {
let mut case = native_foreground_case(
"appkit",
"exact_activation_with_agent_cursor",
Targeting::NotApplicable,
DriverRoute::WindowState,
);
case.oracles.extend([OracleKind::Focus, OracleKind::Cursor]);
run_case(case, |pid, wid, driver| {
let snapshot = snapshot_elements(driver, pid, wid);
assert!(!snapshot.is_error(), "snapshot: {}", snapshot.text());
let target = TargetWindow {
pid,
native_id: wid,
};
let observer = NativeObserver::new();
let before = observer.snapshot(target).expect("observe native desktop");
let socket = std::env::var("CUA_E2E_MACOS_DAEMON_SOCKET")
.expect("canonical installed daemon socket");
let mut peer = McpDriver::spawn_daemon_proxy_unrecorded(&socket)
.expect("start concurrent cursor session");
let verifies_target = |response: &ToolResponse| {
let state = response.structured();
!response.is_error()
&& state["activated"] == true
&& state["observed"]["focused_window_id"].as_u64() == Some(wid)
&& state["observed"]["frontmost_ordinary_window_id"].as_u64() == Some(wid)
&& state["observed"]["frontmost_pid"].as_u64() == Some(u64::from(pid))
};
let stopped = std::sync::atomic::AtomicBool::new(false);
let (ready, started) = std::sync::mpsc::sync_channel(1);
let activated = std::thread::scope(|scope| {
let moving = scope.spawn(|| {
let snapshot = snapshot_elements(&mut peer, pid, wid);
assert!(!snapshot.is_error(), "peer snapshot: {}", snapshot.text());
let motion = peer.call(
"set_agent_cursor_motion",
serde_json::json!({"idle_hide_ms": 0, "glide_duration_ms": 0}),
);
assert!(!motion.is_error(), "cursor motion: {}", motion.text());
let deadline = std::time::Instant::now() + Duration::from_secs(60);
let mut first = true;
let mut x = 120;
while !stopped.load(std::sync::atomic::Ordering::Relaxed)
&& std::time::Instant::now() < deadline
{
let moved = peer.call(
"move_cursor",
serde_json::json!({
"target": {"kind": "window", "pid": pid, "window_id": wid},
"x": x,
"y": 100
}),
);
assert!(!moved.is_error(), "agent cursor: {}", moved.text());
if first {
ready.send(()).expect("cursor readiness");
first = false;
}
x = if x == 120 { 121 } else { 120 };
std::thread::sleep(Duration::from_millis(20));
}
assert!(
stopped.load(std::sync::atomic::Ordering::Relaxed),
"cursor producer expired before the activation interval completed"
);
});
started
.recv_timeout(Duration::from_secs(15))
.expect("live cursor ready");
let mut result = driver.call(
"bring_to_front",
serde_json::json!({"pid": pid, "window_id": wid}),
);
for _ in 1..20 {
if !verifies_target(&result) {
break;
}
result = driver.call(
"bring_to_front",
serde_json::json!({"pid": pid, "window_id": wid}),
);
}
stopped.store(true, std::sync::atomic::Ordering::Relaxed);
moving.join().expect("concurrent cursor transport");
result
});
assert!(
verifies_target(&activated),
"active agent cursor must not invalidate exact activation: {}",
activated.raw
);
let after = observer.snapshot(target).expect("observe activated target");
assert_eq!(after.foreground, Some(u64::from(pid)));
assert_eq!(after.cursor_pos, before.cursor_pos, "real pointer moved");
Observation::delivered_with_fixture_state(vec![OracleKind::Focus, OracleKind::Cursor])
});
}
#[test]
#[ignore]
fn harness_appkit_exact_activation_ignores_competing_application_window() {
let mut case = native_foreground_case(
"appkit",
"exact_activation_competing_window",
Targeting::NotApplicable,
DriverRoute::WindowState,
);
case.oracles.push(OracleKind::Cursor);
run_case(case, |pid, wid, driver| {
let competitor = Harness::launch_with_options(None, None, true);
let (competing_wid, _) = driver
.find_window(competitor.pid as i64, "CuaTestHarness AppKit")
.expect("find competing ordinary window");
assert_ne!(competing_wid, wid);
let snapshot = snapshot_elements(driver, pid, wid);
assert!(!snapshot.is_error(), "target snapshot: {}", snapshot.text());
let observer = NativeObserver::new();
let target = TargetWindow {
pid,
native_id: wid,
};
let before = observer.snapshot(target).expect("observe competing window");
let front = await_front_layer_zero_window(driver, competing_wid);
let leader = front
.as_ref()
.map(FrontWindow::to_string)
.unwrap_or_else(|| "no on-screen layer-0 window".to_owned());
assert_eq!(
front.map(|window| window.window_id),
Some(competing_wid),
"competing window {competing_wid} must lead the global layer-0 order before \
bring_to_front; list_windows ranks {leader} first"
);
let response = driver.call(
"bring_to_front",
serde_json::json!({"pid": pid, "window_id": wid}),
);
assert!(
!response.is_error(),
"another application ordering its window front must not unverify activation: {}",
response.raw
);
assert_eq!(
response.structured()["code"],
"bring_to_front_exact_window_verified"
);
assert_eq!(response.structured()["activated"], true);
assert_eq!(response.structured()["process_activated"], true);
assert_eq!(
response.structured()["exact_window_effect"]["focused"],
true
);
assert_eq!(
response.structured()["exact_window_effect"]["front_in_process_on_display"],
true
);
assert_eq!(
response.structured()["observed"]["focused_window_id"].as_u64(),
Some(wid)
);
let after = observer.snapshot(target).expect("observe activated target");
assert_eq!(after.cursor_pos, before.cursor_pos, "real pointer moved");
Observation::delivered_with_fixture_state(vec![OracleKind::Cursor])
});
}
#[test]
#[ignore]
fn harness_appkit_foreground_single_click_has_one_ordered_native_pair() {
let case = native_foreground_case(
"appkit",
"single_click_native_pair",
Targeting::Px,
DriverRoute::MacosCgEventHid,
);
execute_case(case, |evidence| {
let mut driver =
McpDriver::spawn_macos_daemon_proxy_named("appkit-single-click-native-pair")
.expect("start macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let directory = tempfile::tempdir().expect("create native pointer journal directory");
let journal = directory.path().join("pointer.jsonl");
std::fs::write(&journal, "").expect("initialize native pointer journal");
let harness = Harness::launch_with_oracles(None, Some(&journal));
let (wid, _) = driver
.find_window(harness.pid as i64, "CuaTestHarness AppKit")
.expect("find native receiver window");
driver.start_behavior_recording();
let read_events = || -> Vec<serde_json::Value> {
std::fs::read_to_string(&journal)
.expect("read native pointer journal")
.lines()
.map(|line| serde_json::from_str(line).expect("parse native pointer event"))
.collect()
};
let initial = read_events();
assert_eq!(
initial.len(),
1,
"receiver must be idle before the request: {initial:?}"
);
assert_eq!(initial[0]["kind"], "ready");
assert_eq!(initial[0]["window_id"].as_u64(), Some(wid));
let snapshot = snapshot_elements(&mut driver, harness.pid, wid);
assert!(
!snapshot.is_error(),
"capture receiver: {}",
snapshot.text()
);
let width = snapshot.structured()["screenshot_width"]
.as_f64()
.expect("screenshot width");
let height = snapshot.structured()["screenshot_height"]
.as_f64()
.expect("screenshot height");
assert!(width > 0.0 && height > 0.0);
let response = driver.call(
"click",
serde_json::json!({
"pid": harness.pid,
"window_id": wid,
"x": width / 2.0,
"y": height / 2.0,
"count": 1,
"delivery_mode": "foreground"
}),
);
assert!(
!response.is_error(),
"single click request failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(750));
let events = read_events();
let received = &events[1..];
assert_eq!(
received.len(),
2,
"one request must deliver one native down/up pair: {received:?}; receiver={initial:?}; screenshot={width}x{height}"
);
assert_eq!(received[0]["kind"], "down");
assert_eq!(received[1]["kind"], "up");
let expected_x = initial[0]["width"].as_f64().unwrap() / 2.0;
let expected_y = initial[0]["height"].as_f64().unwrap() / 2.0;
for event in received {
assert_eq!(event["window_id"].as_u64(), Some(wid));
assert_eq!(event["click_count"], 1);
assert!(
(event["x"].as_f64().unwrap() - expected_x).abs() <= 1.0,
"wrong horizontal target: {event}"
);
assert!(
(event["y"].as_f64().unwrap() - expected_y).abs() <= 1.0,
"wrong vertical target: {event}"
);
}
assert!(
received[0]["timestamp"].as_f64().unwrap()
<= received[1]["timestamp"].as_f64().unwrap()
);
println!("native pointer events: {received:?}");
Observation::delivered_with_fixture_state(vec![])
});
}
#[test]
#[ignore]
fn harness_appkit_middle_click_px_background_reaches_exact_window() {
let case = native_background_case(
"appkit",
"middle_click",
Targeting::Px,
DriverRoute::MacosCgEventPid,
);
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named("appkit-middle-click")
.expect("start macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let directory = tempfile::tempdir().expect("create middle-click journal directory");
let journal = directory.path().join("pointer.jsonl");
std::fs::write(&journal, "").expect("initialize native pointer journal");
let harness = Harness::launch_with_oracles(None, Some(&journal));
let (wid, _) = driver
.find_window(harness.pid as i64, "CuaTestHarness AppKit")
.expect("find middle-click receiver window");
let read_events = || -> Vec<serde_json::Value> {
std::fs::read_to_string(&journal)
.expect("read native pointer journal")
.lines()
.map(|line| serde_json::from_str(line).expect("parse native pointer event"))
.collect()
};
let initial = read_events();
assert_eq!(initial.len(), 1, "receiver must be idle: {initial:?}");
assert_eq!(initial[0]["kind"], "ready");
assert_eq!(initial[0]["window_id"].as_u64(), Some(wid));
let snapshot = snapshot_elements(&mut driver, harness.pid, wid);
assert!(
!snapshot.is_error(),
"capture receiver: {}",
snapshot.text()
);
let width = snapshot.structured()["screenshot_width"]
.as_f64()
.expect("screenshot width");
let height = snapshot.structured()["screenshot_height"]
.as_f64()
.expect("screenshot height");
let (_, passed) = run_with_background_oracles(
&mut driver,
TargetWindow {
pid: harness.pid,
native_id: wid,
},
|driver| {
let response = driver.call(
"click",
serde_json::json!({
"pid": harness.pid, "window_id": wid,
"x": width / 2.0, "y": height / 2.0,
"button": "middle", "delivery_mode": "background"
}),
);
assert!(
!response.is_error(),
"middle-click request: {}",
response.text()
);
assert_eq!(response.action_delivery_mode(), Some("background"));
let deadline = Instant::now() + Duration::from_secs(3);
loop {
let events = read_events();
if events.iter().any(|event| event["kind"] == "middle_up") {
break;
}
assert!(
Instant::now() < deadline,
"middle-click did not arrive: {events:?}"
);
std::thread::sleep(Duration::from_millis(50));
}
std::thread::sleep(Duration::from_millis(750));
let events = read_events();
let received = &events[1..];
assert_eq!(
received.len(),
2,
"one request must deliver one native middle down/up pair: {received:?}"
);
assert_eq!(received[0]["kind"], "middle_down");
assert_eq!(received[1]["kind"], "middle_up");
let expected_x = initial[0]["width"].as_f64().unwrap() / 2.0;
let expected_y = initial[0]["height"].as_f64().unwrap() / 2.0;
for event in received {
assert_eq!(event["window_id"].as_u64(), Some(wid));
assert!((event["x"].as_f64().unwrap() - expected_x).abs() <= 1.0);
assert!((event["y"].as_f64().unwrap() - expected_y).abs() <= 1.0);
}
},
)
.expect("middle-click must preserve background desktop state");
Observation::delivered_with_fixture_state(passed)
});
}
#[test]
#[ignore]
fn harness_appkit_smoke() {
run_case(
native_readonly_case(
"appkit",
"ax_tree",
Targeting::Ax,
DriverRoute::AxRead,
vec![OracleKind::AxState],
),
|pid, wid, driver| {
let snap = snapshot_elements(driver, pid, wid);
assert!(
!looks_empty(snap.tree_text()),
"required AppKit AX tree is empty"
);
let text = snap.tree_text();
println!("snapshot:\n{text}");
// AppKit AX quirk (mirrors the WPF behavior documented in
// harness_wpf_test.rs::harness_wpf_smoke): NSTextField in label mode
// and other AXStaticText leaves do NOT propagate
// setAccessibilityIdentifier into the AX tree's identifier slot, so
// we don't assert on ids for labels. We assert on text-presence for
// those, and on AX ids only for actionable controls whose AppKit
// identifiers are actually propagated (Buttons and TextFields).
// NSMenuItem behaves like the static leaves here: its title is
// exposed, but setAccessibilityIdentifier is not.
for aid in [
"wnd-main", // NSWindow
"btn-increment",
"btn-reset", // NSButton
"txt-input", // editable NSTextField
"btn-exit",
] {
assert!(
has_id(snap.tree_text(), aid),
"missing AX identifier {aid} in AppKit snapshot"
);
}
// text_body marker carried by the visible string of the NSTextField
assert!(
text.contains("HARNESS_TEXT_MARKER_v1"),
"text_body marker not in AppKit snapshot"
);
// The two label-mode NSTextFields under click_target render as
// AXStaticText nodes — assert on their starting text instead of ids.
assert!(text.contains("counter=0"), "counter label missing");
assert!(text.contains("clicks=0"), "click_count label missing");
assert!(
text.contains("Harness Test Item"),
"AppKit menu item title missing"
);
assert!(
text.contains("last_action=none"),
"last_action label missing"
);
Observation::delivered(vec![OracleKind::AxState], Evidence::default())
},
);
}
/// AppKit registers a window with WindowServer when the app constructs it, but
/// the app answers accessibility only once it enters its run loop; a cold
/// launch can sit between the two for seconds. The first snapshot waits for
/// the launch within `timeout_ms`, and a launch that outlasts the budget is
/// reported as such instead of as an unexplained empty tree.
#[test]
#[ignore]
fn harness_appkit_first_snapshot_waits_for_a_launching_app() {
let case = native_readonly_case(
"appkit",
"launching_app_snapshot",
Targeting::Ax,
DriverRoute::AxRead,
vec![OracleKind::AxState],
);
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named("appkit-launching-app-snapshot")
.expect("start installed macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
driver.start_behavior_recording();
let snapshot = |driver: &mut McpDriver, pid: u32, wid: u64, timeout_ms: u64| {
driver.call(
"get_window_state",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"timeout_ms": timeout_ms,
"include_screenshot": false
}),
)
};
let launching_window = |driver: &mut McpDriver, harness: &Harness| {
let (wid, _) = driver
.find_window(harness.pid as i64, "CuaTestHarness AppKit")
.expect("a launching AppKit window is listed before it can answer AX");
assert!(
!cua_driver_testkit::observer::macos::application_presented(harness.pid),
"the harness must still be launching when the snapshot starts"
);
wid
};
let stalled = Harness::launch_slowly(Duration::from_secs(4));
let wid = launching_window(&mut driver, &stalled);
let early = snapshot(&mut driver, stalled.pid, wid, 300);
let state = early.structured();
assert!(
!early.is_error(),
"a launching app degrades; it does not error: {}",
early.text()
);
assert_eq!(state["truncated"], true, "{state}");
assert_eq!(state["truncation_reason"], "app_lookup_timeout", "{state}");
assert_eq!(state["degraded"], true, "{state}");
assert!(
state["degraded_reason"]
.as_str()
.is_some_and(|reason| reason.starts_with("ax_app_launching")),
"{state}"
);
assert_eq!(state["elements"], serde_json::json!([]), "{state}");
assert!(
state.get("snapshot_id").is_none(),
"an unresolved launch must not publish element tokens: {state}"
);
drop(stalled);
let slow = Harness::launch_slowly(Duration::from_millis(2500));
let wid = launching_window(&mut driver, &slow);
let started = Instant::now();
let first = snapshot(&mut driver, slow.pid, wid, 10_000);
let waited = started.elapsed();
let state = first.structured();
assert!(!first.is_error(), "first snapshot: {}", first.text());
assert!(state.get("degraded").is_none(), "{state}");
assert_eq!(state["truncated"], false, "{state}");
for aid in ["wnd-main", "btn-increment", "btn-clicktarget", "txt-input"] {
assert!(
has_id(first.tree_text(), aid),
"first snapshot of a launching app is missing {aid}: {}",
first.tree_text()
);
}
assert!(first.tree_text().contains("slider_value=0"));
println!("first snapshot of a launching app returned the whole window after {waited:?}");
Observation::delivered(vec![OracleKind::AxState], Evidence::default())
});
}
#[test]
#[ignore]
fn harness_appkit_query_projects_structured_elements() {
run_case(
native_readonly_case(
"appkit",
"query_projection",
Targeting::Ax,
DriverRoute::AxRead,
vec![OracleKind::AxState],
),
|pid, wid, driver| {
let response = driver.call(
"get_window_state",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"query": "btn-increment",
"include_screenshot": false
}),
);
assert!(
!response.is_error(),
"query snapshot failed: {}",
response.text()
);
let total = response.structured()["total_element_count"]
.as_u64()
.expect("total_element_count");
let returned = response.structured()["returned_element_count"]
.as_u64()
.expect("returned_element_count");
let elements = response.structured()["elements"]
.as_array()
.expect("projected elements");
assert_eq!(returned as usize, elements.len());
assert!(
returned < total,
"query did not compact {returned}/{total} elements"
);
assert!(has_id(response.tree_text(), "btn-increment"));
let _ = element_token_by_id(&response, "btn-increment");
Observation::delivered(vec![OracleKind::AxState], Evidence::default())
},
);
}
#[test]
#[ignore]
fn harness_appkit_stale_element_token_fails_closed() {
run_case(
native_readonly_case(
"appkit",
"stale_element_token",
Targeting::Ax,
DriverRoute::AxRead,
vec![OracleKind::AxState],
),
|pid, wid, driver| {
let first = snapshot_elements(driver, pid, wid);
assert!(first.tree_text().contains("counter=0"));
let token = element_token_by_id(&first, "btn-increment");
let index = element_index_by_id(first.tree_text(), "btn-increment").unwrap();
let newer = snapshot_elements(driver, pid, wid);
assert!(
!newer.is_error(),
"replacement read failed: {}",
newer.text()
);
assert_ne!(first.snapshot_id(), newer.snapshot_id());
let refused = driver.call(
"click",
serde_json::json!({"pid": pid as i64, "element_token": token}),
);
assert!(
refused.is_error(),
"stale token was accepted: {}",
refused.text()
);
assert_eq!(
refused.structured()["refusal"]["code"].as_str(),
Some("stale_element_token")
);
let refused_index = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": first.element_token(index)
}),
);
assert!(
refused_index.is_error(),
"stale snapshot/index was accepted"
);
assert_eq!(
refused_index.structured()["refusal"]["code"].as_str(),
Some("stale_element_token")
);
let post = snapshot_elements(driver, pid, wid);
assert!(
post.tree_text().contains("counter=0"),
"stale targeting mutated counter"
);
let fresh_token = element_token_by_id(&post, "btn-increment");
let delivered = driver.call(
"click",
serde_json::json!({"pid": pid as i64, "element_token": fresh_token}),
);
assert!(
!delivered.is_error(),
"fresh recovery failed: {}",
delivered.text()
);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
let recovered = snapshot_elements(driver, pid, wid);
if recovered.tree_text().contains("counter=1") {
break;
}
assert!(
std::time::Instant::now() < deadline,
"fresh recovery did not increment exactly once: {}",
recovered.tree_text()
);
std::thread::sleep(Duration::from_millis(50));
}
Observation::delivered(vec![OracleKind::AxState], Evidence::default())
},
);
}
#[test]
#[ignore]
fn harness_appkit_invoke_menu_live_path() {
run_case(
native_foreground_case(
"appkit",
"invoke_menu",
Targeting::Ax,
DriverRoute::MacosAxAction,
),
|pid, wid, driver| {
let refused = driver.call(
"invoke_menu",
serde_json::json!({
"pid": pid,
"window_id": wid,
"path": ["Window", "Arrange", "Missing"]
}),
);
assert!(refused.is_error(), "missing menu path was accepted");
// Only the missing leaf may refuse; a pid, window, or activation
// failure would share the code but name a different cause.
assert_eq!(
refused.structured()["refusal"]["code"],
"menu_path_unavailable",
"{}",
refused.raw
);
assert!(
refused.structured()["refusal"]["message"]
.as_str()
.is_some_and(
|message| message.contains("path segment 2 \"Missing\" was not found")
),
"{}",
refused.raw
);
assert!(snapshot_elements(driver, pid, wid)
.tree_text()
.contains("menu_action=none"));
// A second native process deliberately steals AppKit activation
// and key-window status. The target menu item validates against
// both, so an AXFocused-only implementation cannot pass this cell.
let _distractor = Harness::launch();
// invoke_menu does not activate a background app (#4955): with
// the distractor in front, the item stays disabled and the call
// refuses without touching the fixture.
let background = driver.call(
"invoke_menu",
serde_json::json!({
"pid": pid,
"window_id": wid,
"path": ["Window", "Arrange", "Left"]
}),
);
assert!(
background.is_error(),
"a disabled background menu item was invoked: {}",
background.raw
);
assert_eq!(
background.structured()["refusal"]["code"],
"background_unavailable",
"{}",
background.raw
);
assert!(snapshot_elements(driver, pid, wid)
.tree_text()
.contains("menu_action=none"));
// The foreground route the refusal names: bring the exact window
// to front, then invoke the menu.
let raised = driver.call(
"bring_to_front",
serde_json::json!({"pid": pid, "window_id": wid}),
);
assert!(!raised.is_error(), "bring_to_front failed: {}", raised.raw);
let invoked = driver.call(
"invoke_menu",
serde_json::json!({
"pid": pid,
"window_id": wid,
"path": ["Window", "Arrange", "Left"]
}),
);
assert!(
!invoked.is_error(),
"invoke_menu failed: {}",
invoked.text()
);
assert_eq!(invoked.action_effect(), Some("unverifiable"));
// Poll for the fixture's menu_action instead of sleeping a fixed
// 300 ms: a loaded runner delivers the action later.
let deadline = std::time::Instant::now() + Duration::from_secs(10);
loop {
let post = snapshot_elements(driver, pid, wid);
if post.tree_text().contains("menu_action=window_arrange_left") {
break;
}
assert!(
std::time::Instant::now() < deadline,
"menu action did not reach fixture: {}",
post.tree_text()
);
std::thread::sleep(Duration::from_millis(100));
}
Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
},
);
}
/// A path that fails after opening a menu closes it again: the next command
/// through the same menu, with no other activation in between, still runs.
#[test]
#[ignore]
fn harness_appkit_invoke_menu_failed_path_leaves_no_menu_open() {
run_case(
native_foreground_case(
"appkit",
"invoke_menu_failed_path",
Targeting::Ax,
DriverRoute::MacosAxAction,
),
|pid, wid, driver| {
let refused = driver.call(
"invoke_menu",
serde_json::json!({
"pid": pid,
"window_id": wid,
"path": ["Window", "Arrange", "Missing"]
}),
);
assert!(refused.is_error(), "missing menu path was accepted");
assert_eq!(
refused.structured()["refusal"]["code"],
"menu_path_unavailable",
"{}",
refused.raw
);
let invoked = driver.call(
"invoke_menu",
serde_json::json!({
"pid": pid,
"window_id": wid,
"path": ["Window", "Arrange", "Left"]
}),
);
assert!(
!invoked.is_error(),
"invoke_menu failed: {}",
invoked.text()
);
let deadline = std::time::Instant::now() + Duration::from_secs(3);
while !snapshot_elements(driver, pid, wid)
.tree_text()
.contains("menu_action=window_arrange_left")
{
assert!(
std::time::Instant::now() < deadline,
"menu command after a failed path did not reach fixture; refusal: {}; command: {}",
refused.raw,
invoked.raw
);
std::thread::sleep(Duration::from_millis(100));
}
assert!(
refused.structured()["refusal"]["message"]
.as_str()
.is_some_and(|message| message
.contains("path segment 2 \"Missing\" was not found")
&& message.contains("No menu window this call opened is still on screen")),
"{}",
refused.raw
);
Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
},
);
}
/// text_input: type_text into the NSTextField, verify the mirror label
/// shows the typed string. Exercises the AX type_text path
/// (AXSetAttribute on AXValue, or CGEvent fallback).
#[test]
#[ignore]
fn harness_appkit_text_input() {
run_background_case(
"set_value",
DriverRoute::MacosAxValue,
|pid, wid, driver| {
let snap_pre = snapshot_elements(driver, pid, wid);
assert!(
!looks_empty(snap_pre.tree_text()),
"required AppKit AX tree is empty"
);
let idx = element_index_by_id(snap_pre.tree_text(), "txt-input")
.expect("txt-input element_index not found");
// set_value via AX is the deterministic background path; type_text would
// also work but races with cursor focus on cold-launched windows.
let resp = driver.call(
"set_value",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": snap_pre.element_token(idx),
"value": "hello-cua"
}),
);
assert!(!resp.is_error(), "AppKit set_value failed: {}", resp.text());
println!("set_value resp: {}", resp.text());
std::thread::sleep(Duration::from_millis(250));
let snap_post = snapshot_elements(driver, pid, wid);
let post_text = snap_post.tree_text().to_owned();
assert!(
post_text.contains("hello-cua"),
"text_input value did not propagate to mirror; snapshot:\n{post_text}"
);
},
);
}
#[test]
#[ignore]
fn harness_appkit_element_foreground_press_key_commits_edit() {
run_case(
native_foreground_case(
"appkit",
"press_key_commit",
Targeting::Ax,
DriverRoute::MacosCgEventHid,
),
|pid, wid, driver| {
let first = snapshot_elements(driver, pid, wid);
let field = element_token_by_id(&first, "txt-input");
let set = driver.call(
"set_value",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": field,
"value": "inline-cua"
}),
);
assert!(!set.is_error(), "set_value failed: {}", set.text());
let second = snapshot_elements(driver, pid, wid);
assert!(
second.tree_text().contains("inline-cua"),
"transient edit value was not readable:\n{}",
second.tree_text()
);
assert!(
second.tree_text().contains("committed=none"),
"fixture reported a commit before Return:\n{}",
second.tree_text()
);
let field = element_token_by_id(&second, "txt-input");
let commit = driver.call(
"press_key",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": field,
"key": "return",
"delivery_mode": "foreground"
}),
);
assert!(
!commit.is_error(),
"foreground element press_key failed: {}",
commit.text()
);
assert_eq!(
commit.action_route(),
Some("global_input"),
"foreground press_key used the wrong public route: {}",
commit.raw
);
assert_eq!(
commit.action_delivery_mode(),
Some("foreground"),
"foreground press_key reported the wrong delivery: {}",
commit.raw
);
assert_eq!(
commit.action_effect(),
Some("unverifiable"),
"press_key claimed more truth than the tool itself observed: {}",
commit.raw
);
std::thread::sleep(Duration::from_millis(250));
let post = snapshot_elements(driver, pid, wid);
assert!(
post.tree_text().contains("committed=inline-cua"),
"Return did not commit the addressed edit:\n{}",
post.tree_text()
);
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
/// The fixture's accelerator fires only when control and shift are set on the
/// `k` keyDown itself, so a foreground chord that loses them leaves it at 0.
#[test]
#[ignore]
fn harness_appkit_foreground_press_key_chord_carries_its_modifiers() {
run_case(
native_foreground_case(
"appkit",
"press_key_chord",
Targeting::Ax,
DriverRoute::MacosCgEventHid,
),
|pid, wid, driver| {
let before = snapshot_elements(driver, pid, wid);
assert!(
before.tree_text().contains("accel_fired=0"),
"fixture did not start with an unfired accelerator:\n{}",
before.tree_text()
);
let chord = driver.call(
"press_key",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"key": "k",
"modifiers": ["ctrl", "shift"],
"delivery_mode": "foreground"
}),
);
assert!(
!chord.is_error(),
"foreground press_key chord failed: {}",
chord.text()
);
let deadline = std::time::Instant::now() + Duration::from_secs(2);
loop {
let after = snapshot_elements(driver, pid, wid);
if after.tree_text().contains("accel_fired=1") {
break;
}
assert!(
std::time::Instant::now() < deadline,
"ctrl+shift+k arrived without its modifiers:\n{}",
after.tree_text()
);
std::thread::sleep(Duration::from_millis(100));
}
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
#[test]
#[ignore]
fn harness_appkit_px_background_press_key_reports_honest_delivery_truth() {
let case = native_background_case(
"appkit",
"press_key_command",
Targeting::Px,
DriverRoute::MacosCgEventPid,
);
let cell_id = case.cell_id.clone();
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&cell_id)
.expect("start installed macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let oracle_dir = tempfile::tempdir().expect("create command oracle directory");
let oracle_path = oracle_dir.path().join("child-process-output.txt");
let harness = Harness::launch_with_command_oracle(Some(&oracle_path));
let (wid, _) = driver
.find_window(harness.pid as i64, "CuaTestHarness AppKit")
.expect("AppKit main window not found");
let (_, passed) = run_with_background_oracles(
&mut driver,
TargetWindow {
pid: harness.pid,
native_id: wid,
},
|driver| {
let first = snapshot_elements(driver, harness.pid, wid);
let field = element_token_by_id(&first, "txt-input");
let set = driver.call(
"set_value",
serde_json::json!({
"pid": harness.pid as i64,
"window_id": wid,
"element_token": field,
"value": "printf cua-press-key"
}),
);
assert!(!set.is_error(), "set command failed: {}", set.text());
let focused = snapshot_elements(driver, harness.pid, wid);
let (x, y, width, height) = element_pixel_frame(&focused, "txt-input");
let pressed = driver.call(
"press_key",
serde_json::json!({
"pid": harness.pid as i64,
"window_id": wid,
"x": x + width / 2.0,
"y": y + height / 2.0,
"key": "return",
"delivery_mode": "background"
}),
);
assert!(
!pressed.is_error(),
"background Return failed: {}",
pressed.text()
);
assert_eq!(pressed.action_route(), Some("synthetic_events"));
assert_eq!(pressed.action_delivery_mode(), Some("background"));
assert_eq!(pressed.action_effect(), Some("unverifiable"));
assert!(
pressed.structured()["escalation"].is_null(),
"accepted post without a positive oracle must not claim delivery_failed: {}",
pressed.raw
);
let deadline = std::time::Instant::now() + Duration::from_secs(3);
loop {
if std::fs::read_to_string(&oracle_path)
.is_ok_and(|value| value == "cua-press-key")
{
break;
}
assert!(
std::time::Instant::now() < deadline,
"background Return did not execute the controlled child process"
);
std::thread::sleep(Duration::from_millis(25));
}
let mut exited = Command::new("/usr/bin/true")
.spawn()
.expect("spawn posting-failure fixture");
let exited_pid = exited.id();
exited.wait().expect("wait for posting-failure fixture");
let failed = driver.call(
"press_key",
serde_json::json!({
"pid": exited_pid,
// An explicit target bypasses the PID-only window resolver so
// this negative oracle reaches the posting preflight. Without
// one, the earlier and equally truthful result is
// window_target_not_found because /usr/bin/true owns no window.
"window_id": wid,
"key": "return",
"delivery_mode": "background"
}),
);
assert!(failed.is_error(), "dead-pid post unexpectedly succeeded");
assert_eq!(failed.structured()["code"], "delivery_failed");
},
)
.unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));
Observation::delivered_with_fixture_state(passed)
});
}
#[test]
#[ignore]
fn harness_appkit_modified_click_preserves_selection() {
run_case(
native_foreground_case(
"appkit",
"modified_click_selection",
Targeting::Ax,
DriverRoute::MacosCgEventHid,
),
|pid, wid, driver| {
let first = snapshot_elements(driver, pid, wid);
let alpha = element_token_by_id(&first, "selection-alpha");
let select_alpha = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": alpha
}),
);
assert!(
!select_alpha.is_error(),
"select alpha failed: {}",
select_alpha.text()
);
std::thread::sleep(Duration::from_millis(200));
let second = snapshot_elements(driver, pid, wid);
assert!(
second.tree_text().contains("selection=alpha"),
"alpha was not selected:\n{}",
second.tree_text()
);
let beta = element_token_by_id(&second, "selection-beta");
let refused_background = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": beta,
"modifier": ["cmd"]
}),
);
assert!(
refused_background.is_error(),
"background modified click was not refused: {}",
refused_background.text()
);
assert_eq!(
refused_background.structured()["code"],
"background_unavailable",
"background modified click returned the wrong refusal: {}",
refused_background.structured()
);
std::thread::sleep(Duration::from_millis(300));
let after_refusal = snapshot_elements(driver, pid, wid);
assert!(
after_refusal.tree_text().contains("selection=alpha"),
"refused modified click changed the prior selection:\n{}",
after_refusal.tree_text()
);
let beta = element_token_by_id(&after_refusal, "selection-beta");
let add_beta = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": beta,
"modifier": ["cmd"],
"delivery_mode": "foreground"
}),
);
assert!(
!add_beta.is_error(),
"foreground modified click failed: {}",
add_beta.text()
);
assert_eq!(
add_beta.structured()["effect"],
"confirmed",
"modified click lacked settled selection proof: {}",
add_beta.structured()
);
std::thread::sleep(Duration::from_millis(250));
let post = snapshot_elements(driver, pid, wid);
assert!(
post.tree_text().contains("selection=alpha,beta"),
"modified click replaced or lost the prior selection:\n{}",
post.tree_text()
);
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
/// type_text: synthesize a keystroke into the NSTextField (CGEvent
/// path, distinct from set_value's AX path). Verifies the keyboard
/// dispatch chain reaches a backgrounded Cocoa text input.
#[test]
#[ignore]
fn harness_appkit_type_text_background() {
run_background_case(
"type_text",
DriverRoute::MacosAxValue,
|pid, wid, driver| {
let snap_pre = snapshot_elements(driver, pid, wid);
assert!(
!looks_empty(snap_pre.tree_text()),
"required AppKit AX tree is empty"
);
let idx = element_index_by_id(snap_pre.tree_text(), "txt-input")
.expect("txt-input element_index not found");
// Address the field through type_text itself. AXTextField does not
// advertise AXPress, so a preparatory click would test an invalid
// action and fail before the keyboard/value delivery path runs.
let resp = driver.call(
"type_text",
serde_json::json!({
"pid": pid as i64, "window_id": wid, "element_token": snap_pre.element_token(idx),
"text": "kbd-cua", "delivery_mode": "background"
}),
);
assert!(!resp.is_error(), "AppKit type_text failed: {}", resp.text());
println!("type_text resp: {}", resp.text());
std::thread::sleep(Duration::from_millis(250));
let snap_post = snapshot_elements(driver, pid, wid);
let post = snap_post.tree_text().to_owned();
assert!(
post.contains("kbd-cua"),
"type_text keystroke did not land in the text field; snapshot:\n{post}"
);
},
);
}
#[test]
#[ignore]
fn harness_appkit_scroll_foreground() {
run_case(
native_foreground_case(
"appkit",
"scroll",
Targeting::Ax,
DriverRoute::MacosAxAction,
),
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
assert!(pre.tree_text().contains("scroll_offset=0"));
let index = element_index_by_id(pre.tree_text(), "scroll-tall")
.or_else(|| element_index_containing(pre.tree_text(), "SCROLL_TOP_MARKER_v1"))
.unwrap_or_else(|| {
panic!("scroll-tall element_index not found:\n{}", pre.tree_text())
});
let response = driver.call(
"scroll",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": pre.element_token(index),
"direction": "down",
"amount": 5,
"delivery_mode": "foreground"
}),
);
assert!(
!response.is_error(),
"AppKit foreground scroll failed: {}; raw={}",
response.text(),
response.raw
);
std::thread::sleep(Duration::from_millis(300));
let post = snapshot_elements(driver, pid, wid);
assert!(
!post.tree_text().contains("scroll_offset=0"),
"AppKit foreground scroll did not move the NSScrollView; response={}; raw={}",
response.text(),
response.raw
);
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
#[test]
#[ignore]
fn harness_appkit_scroll_background() {
run_background_case("scroll", DriverRoute::MacosAxAction, |pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
assert!(pre.tree_text().contains("scroll_offset=0"));
let index = element_index_by_id(pre.tree_text(), "scroll-tall")
.or_else(|| element_index_containing(pre.tree_text(), "SCROLL_TOP_MARKER_v1"))
.unwrap_or_else(|| panic!("scroll-tall element_index not found:\n{}", pre.tree_text()));
let response = driver.call(
"scroll",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": pre.element_token(index),
"direction": "down",
"amount": 5,
"delivery_mode": "background"
}),
);
assert!(
!response.is_error(),
"AppKit background scroll failed: {}; raw={}",
response.text(),
response.raw
);
std::thread::sleep(Duration::from_millis(200));
assert!(
!snapshot_elements(driver, pid, wid)
.tree_text()
.contains("scroll_offset=0"),
"AppKit background AX scroll did not move the NSScrollView"
);
});
}
/// counter: click the increment button via element_index, verify the
/// counter label flips from 0 to 1.
#[test]
#[ignore]
fn harness_appkit_counter() {
run_background_case(
"left_click",
DriverRoute::MacosAxAction,
|pid, wid, driver| {
let snap_pre = snapshot_elements(driver, pid, wid);
assert!(
!looks_empty(snap_pre.tree_text()),
"required AppKit AX tree is empty"
);
let pre_text = snap_pre.tree_text().to_owned();
assert!(
pre_text.contains("counter=0"),
"counter not 0 pre-click; snapshot:\n{pre_text}"
);
let idx = element_index_by_id(snap_pre.tree_text(), "btn-increment")
.expect("btn-increment element_index not found");
let click_resp = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": snap_pre.element_token(idx),
"action": "press",
"delivery_mode": "background"
}),
);
assert!(
!click_resp.is_error(),
"AppKit counter click failed: {}",
click_resp.text()
);
println!("click resp: {}", click_resp.text());
// Let the AppKit run-loop process the press and refresh the label.
std::thread::sleep(Duration::from_millis(200));
let snap_post = snapshot_elements(driver, pid, wid);
let post_text = snap_post.tree_text().to_owned();
assert!(
post_text.contains("counter=1"),
"counter did not advance to 1 after press; post snapshot:\n{post_text}"
);
},
);
}
/// AppKit answers an accessibility press whose handler raises with an AX
/// error, as Finder's toolbar view switcher does after switching (#3835). A
/// checkbox that toggled before raising is reported as performed and
/// confirmed; one that changed nothing keeps the error.
#[test]
#[ignore]
fn harness_appkit_erroring_toggle_press_counts_only_when_its_value_moved() {
let case = native_background_case(
"appkit",
"toggle_press_error",
Targeting::Ax,
DriverRoute::MacosAxAction,
);
let cell_id = case.cell_id.clone();
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&cell_id)
.expect("start installed macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let harness = Harness::launch_with_erroring_toggles();
let pid = harness.pid;
let (wid, _) = driver
.find_window(pid as i64, "CuaTestHarness AppKit")
.expect("AppKit main window not found");
let (_, passed) = run_with_background_oracles(
&mut driver,
TargetWindow {
pid,
native_id: wid,
},
|driver| {
let press = |driver: &mut McpDriver, identifier: &str| {
let snapshot = snapshot_elements(driver, pid, wid);
driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": element_token_by_id(&snapshot, identifier),
"action": "press",
"delivery_mode": "background"
}),
)
};
let state = |driver: &mut McpDriver| {
snapshot_elements(driver, pid, wid).tree_text().to_owned()
};
assert!(
state(driver).contains("acts_then_errors=false errors_only=false"),
"erroring toggles did not start off"
);
let acted = press(driver, "chk-acts-then-errors");
assert!(
!acted.is_error(),
"a press whose value moved was reported as failed: {}",
acted.raw
);
assert_eq!(acted.action_effect(), Some("confirmed"), "{}", acted.raw);
assert!(
acted.text().contains("although the app returned AX error"),
"result does not name the AX error: {}",
acted.raw
);
let refused = press(driver, "chk-errors-only");
assert!(
refused.is_error(),
"a press that changed nothing was reported as performed: {}",
refused.raw
);
assert!(
refused
.text()
.contains("AXUIElementPerformAction(AXPress) returned"),
"{}",
refused.raw
);
std::thread::sleep(Duration::from_millis(200));
let after = state(driver);
assert!(
after.contains("acts_then_errors=true errors_only=false"),
"fixture state after the presses:\n{after}"
);
},
)
.unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));
Observation::delivered_with_fixture_state(passed)
});
}
/// A disabled control is published with `enabled: false` and its frame, and a
/// press on its token is refused without changing it (#3949).
#[test]
#[ignore]
fn harness_appkit_disabled_control_is_published_and_its_press_refused() {
let case = native_background_case(
"appkit",
"disabled_control_press",
Targeting::Ax,
DriverRoute::MacosAxAction,
);
let cell_id = case.cell_id.clone();
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&cell_id)
.expect("start installed macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let harness = Harness::launch_with_disabled_control();
let pid = harness.pid;
let (wid, _) = driver
.find_window(pid as i64, "CuaTestHarness AppKit")
.expect("AppKit main window not found");
let (_, passed) = run_with_background_oracles(
&mut driver,
TargetWindow {
pid,
native_id: wid,
},
|driver| {
let snapshot = snapshot_elements(driver, pid, wid);
assert!(
snapshot.tree_text().contains("disabled_checked=false"),
"disabled checkbox did not start off"
);
let index = element_index_by_id(snapshot.tree_text(), "chk-disabled")
.unwrap_or_else(|| {
panic!(
"the disabled checkbox has no element_index:\n{}",
snapshot.tree_text()
)
});
let element = snapshot.structured()["elements"]
.as_array()
.and_then(|elements| {
elements
.iter()
.find(|element| element["element_index"].as_u64() == Some(index))
})
.cloned()
.expect("the disabled checkbox is missing from elements");
assert_eq!(element["enabled"], false, "{element}");
assert!(
element["frame"]["w"].as_f64().unwrap_or(0.0) > 0.0,
"the disabled checkbox has no frame: {element}"
);
let refused = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": element["element_token"],
"action": "press",
"delivery_mode": "background"
}),
);
assert!(
refused.is_error(),
"a press on a disabled control was reported as performed: {}",
refused.raw
);
assert!(
refused.text().contains("AXEnabled=false"),
"{}",
refused.raw
);
assert_eq!(
refused.structured()["code"],
"element_disabled",
"{}",
refused.raw
);
// Every other token writer refuses the same control the same way.
let token = &element["element_token"];
let writers = [
("set_value", serde_json::json!({ "value": "1" })),
("right_click", serde_json::json!({})),
("double_click", serde_json::json!({})),
("click", serde_json::json!({ "button": "middle" })),
("type_text", serde_json::json!({ "text": "x" })),
];
for (tool, mut args) in writers {
args["pid"] = serde_json::json!(pid as i64);
args["window_id"] = serde_json::json!(wid);
args["element_token"] = token.clone();
let refused = driver.call(tool, args);
assert!(
refused.is_error() && refused.structured()["code"] == "element_disabled",
"{tool} on a disabled control was not refused as element_disabled: {}",
refused.raw
);
}
std::thread::sleep(Duration::from_millis(200));
let after = snapshot_elements(driver, pid, wid);
assert!(
after.tree_text().contains("disabled_checked=false"),
"a refused action changed the disabled checkbox:\n{}",
after.tree_text()
);
},
)
.unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));
Observation::delivered_with_fixture_state(passed)
});
}
/// A foreground call into a background app skips the early `AXEnabled` read so
/// activation can enable the control, and must read it again before input: a
/// control that is still disabled is refused, not double-clicked or typed into.
#[test]
#[ignore]
fn harness_appkit_disabled_control_is_refused_in_foreground_from_the_background() {
let case = native_foreground_case(
"appkit",
"disabled_control_foreground",
Targeting::Ax,
DriverRoute::MacosAxAction,
);
let cell_id = case.cell_id.clone();
execute_case(case, |evidence| {
let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&cell_id)
.expect("start installed macOS daemon proxy");
*evidence = recording_evidence(driver.recording_dir());
let harness = Harness::launch_with_disabled_control();
let pid = harness.pid;
let (wid, _) = driver
.find_window(pid as i64, "CuaTestHarness AppKit")
.expect("AppKit main window not found");
let target = TargetWindow {
pid,
native_id: wid,
};
let sentinel = ForegroundSentinel::launch(&mut driver);
driver.start_behavior_recording();
let writers = [
("double_click", serde_json::json!({})),
("click", serde_json::json!({ "button": "middle" })),
("type_text", serde_json::json!({ "text": "x" })),
];
for (tool, mut args) in writers {
// Each call starts with the harness behind another app, the case
// in which the early read is skipped.
sentinel
.prepare_background_observation(&mut driver, target)
.unwrap_or_else(|error| panic!("put the harness in the background: {error}"));
let snapshot = snapshot_elements(&mut driver, pid, wid);
args["pid"] = serde_json::json!(pid as i64);
args["window_id"] = serde_json::json!(wid);
args["element_token"] =
serde_json::json!(element_token_by_id(&snapshot, "chk-disabled"));
args["delivery_mode"] = serde_json::json!("foreground");
let refused = driver.call(tool, args);
assert!(
refused.is_error() && refused.structured()["code"] == "element_disabled",
"foreground {tool} on a disabled control in a background app was not \
refused as element_disabled: {}",
refused.raw
);
}
std::thread::sleep(Duration::from_millis(200));
let after = snapshot_elements(&mut driver, pid, wid);
assert!(
after.tree_text().contains("disabled_checked=false"),
"a refused foreground action changed the disabled checkbox:\n{}",
after.tree_text()
);
Observation::delivered_with_fixture_state(Vec::new())
});
}
/// Resolve the native AppKit button from a screenshot-space PX target, then
/// deliver through the background-safe AX hit-test bridge while another app
/// remains fully foreground.
#[test]
#[ignore]
fn harness_appkit_counter_px_background() {
run_background_case_targeting(
"left_click",
Targeting::Px,
DriverRoute::MacosAxAction,
|pid, wid, driver| {
let config = driver.call(
"set_config",
serde_json::json!({"max_image_dimension": 200}),
);
assert!(
!config.is_error(),
"small capture config: {}",
config.text()
);
let pre = snapshot_elements(driver, pid, wid);
let (x, y, width, height) = element_pixel_frame(&pre, "btn-increment");
let zoom = driver.call(
"zoom",
serde_json::json!({
"pid": pid as i64, "window_id": wid,
"x1": x, "y1": y, "x2": x + width, "y2": y + height
}),
);
assert!(
!zoom.is_error(),
"create owned zoom context: {}",
zoom.text()
);
let small_width = pre.structured()["screenshot_width"]
.as_u64()
.expect("small screenshot width");
let mut observer = driver
.spawn_peer_unrecorded()
.expect("start independent capture client on the same daemon");
let config = observer.call("set_config", serde_json::json!({"max_image_dimension": 0}));
assert!(
!config.is_error(),
"native capture config: {}",
config.text()
);
let other = snapshot_elements(&mut observer, pid, wid);
assert!(
other.structured()["screenshot_width"]
.as_u64()
.expect("native screenshot width")
> small_width
);
for (tool, args) in [
(
"double_click",
serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"delivery_mode":"foreground"}),
),
(
"right_click",
serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"delivery_mode":"foreground"}),
),
(
"scroll",
serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"direction":"down","amount":1,"delivery_mode":"foreground"}),
),
(
"drag",
serde_json::json!({"pid":pid as i64,"window_id":wid,"from_x":x,"from_y":y,"to_x":x+1.0,"to_y":y+1.0,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),
),
] {
let stale = driver.call(tool, args);
assert_eq!(
stale.structured()["code"],
"screenshot_context_missing",
"{tool} must refuse another client's screenshot transform"
);
}
for (tool, args) in [
(
"click",
serde_json::json!({"pid":pid as i64,"window_id":wid,"x":1.0,"y":1.0,"from_zoom":true,"delivery_mode":"foreground"}),
),
(
"drag",
serde_json::json!({"pid":pid as i64,"window_id":wid,"from_x":1.0,"from_y":1.0,"to_x":2.0,"to_y":2.0,"from_zoom":true,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),
),
] {
let stale = driver.call(tool, args);
assert_eq!(
stale.structured()["code"],
"zoom_context_missing",
"{tool} must refuse a zoom bound to the replaced snapshot"
);
}
let stale = driver.call(
"click",
serde_json::json!({
"pid": pid as i64, "window_id": wid,
"x": x + width / 2.0, "y": y + height / 2.0,
"delivery_mode": "background"
}),
);
assert_eq!(stale.structured()["code"], "screenshot_context_missing");
let refreshed = snapshot_elements(driver, pid, wid);
let (x, y, width, height) = element_pixel_frame(&refreshed, "btn-increment");
let response = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"x": x + width / 2.0,
"y": y + height / 2.0,
"delivery_mode": "background"
}),
);
assert!(
!response.is_error(),
"AppKit PX background click failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(200));
assert!(
snapshot_elements(driver, pid, wid)
.tree_text()
.contains("counter=1"),
"AppKit PX background click did not advance counter"
);
},
);
}
#[test]
#[ignore]
fn harness_appkit_right_click_px_foreground() {
run_case(
native_foreground_case(
"appkit",
"right_click",
Targeting::Px,
DriverRoute::MacosCgEventHid,
),
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
let (x, y, width, height) = element_pixel_frame(&pre, "btn-clicktarget");
let response = driver.call(
"right_click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"x": x + width / 2.0,
"y": y + height / 2.0,
"delivery_mode": "foreground"
}),
);
assert!(
!response.is_error(),
"AppKit right click failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(250));
assert!(
snapshot_elements(driver, pid, wid)
.tree_text()
.contains("last_action=right_click"),
"AppKit right-click handler did not fire"
);
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
#[test]
#[ignore]
fn harness_appkit_right_click_px_background() {
run_background_case_targeting(
"right_click",
Targeting::Px,
DriverRoute::MacosCgEventPid,
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
let (x, y, width, height) = element_pixel_frame(&pre, "btn-clicktarget");
let response = driver.call(
"right_click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"x": x + width / 2.0,
"y": y + height / 2.0,
"delivery_mode": "background"
}),
);
assert!(
!response.is_error(),
"AppKit right click failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(250));
assert!(
snapshot_elements(driver, pid, wid)
.tree_text()
.contains("last_action=right_click"),
"AppKit background right-click handler did not fire"
);
},
);
}
#[test]
#[ignore]
fn harness_appkit_double_click_px_foreground() {
run_case(
native_foreground_case(
"appkit",
"double_click",
Targeting::Px,
DriverRoute::MacosCgEventHid,
),
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
let (x, y, width, height) = element_pixel_frame(&pre, "btn-clicktarget");
let response = driver.call(
"double_click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"x": x + width / 2.0,
"y": y + height / 2.0,
"delivery_mode": "foreground"
}),
);
assert!(
!response.is_error(),
"AppKit double click failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(250));
assert!(
snapshot_elements(driver, pid, wid)
.tree_text()
.contains("last_action=double_click"),
"AppKit double-click handler did not fire"
);
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
#[test]
#[ignore]
fn harness_appkit_double_click_px_background() {
run_background_case_targeting(
"double_click",
Targeting::Px,
DriverRoute::MacosCgEventPid,
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
let (x, y, width, height) = element_pixel_frame(&pre, "btn-clicktarget");
let response = driver.call(
"double_click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"x": x + width / 2.0,
"y": y + height / 2.0,
"delivery_mode": "background"
}),
);
assert!(
!response.is_error(),
"AppKit double click failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(250));
let receiver_snapshot = snapshot_elements(driver, pid, wid);
let receiver = receiver_snapshot.tree_text();
assert!(
receiver.contains("last_action=double_click") && receiver.contains("clicks=2"),
"AppKit background double-click receiver did not record exactly two clicks"
);
},
);
}
#[test]
#[ignore]
fn harness_appkit_slider_drag_px_foreground() {
run_case(
native_foreground_case(
"appkit",
"slider_drag",
Targeting::Px,
DriverRoute::MacosCgEventHid,
),
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
assert!(pre.tree_text().contains("slider_value=0"));
let (x, y, width, height) = element_pixel_frame(&pre, "sld-value");
let response = driver.call(
"drag",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"from_x": x + width * 0.05,
"from_y": y + height / 2.0,
"to_x": x + width * 0.90,
"to_y": y + height / 2.0,
"duration_ms": 500,
"steps": 30,
"delivery_mode": "foreground"
}),
);
assert!(
!response.is_error(),
"AppKit slider drag failed: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(300));
assert!(
!snapshot_elements(driver, pid, wid)
.tree_text()
.contains("slider_value=0"),
"AppKit foreground drag did not move the slider"
);
Observation::delivered_with_fixture_state(Vec::new())
},
);
}
#[test]
#[ignore]
fn harness_appkit_slider_drag_px_background() {
let case = native_background_case(
"appkit",
"slider_drag",
Targeting::Px,
DriverRoute::MacosCgEventPid,
);
run_case(case, |pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
assert!(pre.tree_text().contains("slider_value=0"));
let (x, y, width, height) = element_pixel_frame(&pre, "sld-value");
// The background oracles fail the case if the drag moves the user's
// pointer, raises or activates the fixture, or takes key focus from
// the foreground sentinel.
let (response, mut passed) = run_with_background_oracles(
driver,
TargetWindow {
pid,
native_id: wid,
},
|driver| {
driver.call(
"drag",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"from_x": x + width * 0.05,
"from_y": y + height / 2.0,
"to_x": x + width * 0.90,
"to_y": y + height / 2.0,
"duration_ms": 500,
"steps": 30,
"delivery_mode": "background"
}),
)
},
)
.unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));
assert!(
!response.is_error(),
"AppKit background drag failed: {}",
response.text()
);
assert!(
response
.text()
.contains("background: routed to the window's pid"),
"AppKit background drag was not routed to the window's pid: {}",
response.text()
);
std::thread::sleep(Duration::from_millis(300));
assert!(
!snapshot_elements(driver, pid, wid)
.tree_text()
.contains("slider_value=0"),
"AppKit background drag did not move the slider"
);
passed.push(OracleKind::FixtureState);
Observation::delivered_with_fixture_state(passed)
});
}
/// popup_select: a background AXPress opens the NSPopUpButton's menu. The menu
/// steals key focus from the front app, so the background oracles (the
/// foreground sentinel must not blur) check that the driver hands it back.
/// The menu stays open and its item is chosen through accessibility.
#[test]
#[ignore]
fn harness_appkit_popup_click_keeps_front_key_focus_background() {
run_background_case(
"popup_click",
DriverRoute::MacosAxAction,
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
assert!(
pre.tree_text().contains("popup_value=Choose a team"),
"popup fixture missing:\n{}",
pre.tree_text()
);
let opened = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": element_token_by_id(&pre, "pop-team"),
"delivery_mode": "background"
}),
);
assert!(!opened.is_error(), "popup click failed: {}", opened.text());
let open = snapshot_elements(driver, pid, wid);
let item = element_index_containing(open.tree_text(), "AXMenuItem \"Research\"")
.unwrap_or_else(|| {
panic!("open popup lists no Research item:\n{}", open.tree_text())
});
let chosen = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": open.element_token(item),
"delivery_mode": "background"
}),
);
assert!(
!chosen.is_error(),
"menu item click failed: {}",
chosen.text()
);
let deadline = Instant::now() + Duration::from_secs(2);
loop {
if snapshot_elements(driver, pid, wid)
.tree_text()
.contains("popup_value=Research")
{
break;
}
assert!(Instant::now() < deadline, "popup selection did not land");
std::thread::sleep(Duration::from_millis(100));
}
},
);
}
/// popup_select through set_value: the driver opens the menu, presses the
/// matching item and closes it, while the front window keeps key status.
#[test]
#[ignore]
fn harness_appkit_popup_set_value_keeps_front_key_focus_background() {
run_background_case(
"popup_set_value",
DriverRoute::MacosAxValue,
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
let set = driver.call(
"set_value",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": element_token_by_id(&pre, "pop-team"),
"value": "Finance"
}),
);
assert!(!set.is_error(), "popup set_value failed: {}", set.text());
std::thread::sleep(Duration::from_millis(250));
assert!(
snapshot_elements(driver, pid, wid)
.tree_text()
.contains("popup_value=Finance"),
"popup set_value did not land"
);
},
);
}
/// context_menu through right_click (AXShowMenu) in the background: the menu
/// steals key focus like a popup does; the front window must keep it.
#[test]
#[ignore]
fn harness_appkit_context_menu_keeps_front_key_focus_background() {
run_background_case(
"context_menu",
DriverRoute::MacosAxAction,
|pid, wid, driver| {
let pre = snapshot_elements(driver, pid, wid);
let shown = driver.call(
"right_click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": element_token_by_id(&pre, "btn-context")
}),
);
assert!(!shown.is_error(), "context menu failed: {}", shown.text());
let open = snapshot_elements(driver, pid, wid);
let item = element_index_containing(open.tree_text(), "AXMenuItem \"Copy\"")
.unwrap_or_else(|| {
panic!(
"open context menu lists no Copy item:\n{}",
open.tree_text()
)
});
let chosen = driver.call(
"click",
serde_json::json!({
"pid": pid as i64,
"window_id": wid,
"element_token": open.element_token(item),
"delivery_mode": "background"
}),
);
assert!(
!chosen.is_error(),
"context item click failed: {}",
chosen.text()
);
std::thread::sleep(Duration::from_millis(250));
assert!(
snapshot_elements(driver, pid, wid)
.tree_text()
.contains("menu_action=Copy"),
"context menu item did not fire"
);
},
);
}
#[repr(C)]
#[derive(Clone, Copy)]
struct WarpPoint {
x: f64,
y: f64,
}
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGWarpMouseCursorPosition(point: WarpPoint) -> i32;
}
/// Regression for trycua/cua#5476. With the real pointer parked outside the
/// target window, a window screenshot came back the size of the window but
/// with the window drawn smaller (about 96.5%) and pushed down by ~31 px, so
/// pixel targets read off it missed by ~37 px. The window must fill its own
/// screenshot edge to edge, whatever the pointer is doing.
#[test]
#[ignore]
fn harness_appkit_window_capture_ignores_pointer_outside_window() {
run_case(
native_readonly_case(
"appkit",
"window_capture_ignores_pointer_outside_window",
Targeting::NotApplicable,
DriverRoute::WindowState,
vec![OracleKind::Pixels],
),
|pid, wid, driver| {
use base64::Engine as _;
// Offset the window from the screen origin and leave room above
// it. Keep its current size: the harness window is not resizable
// (no settable AXSize), and set_window_frame only writes AXSize
// when the size changes.
let listed = driver.call("list_windows", serde_json::json!({ "pid": pid as i64 }));
assert!(!listed.is_error(), "list_windows: {}", listed.text());
let current = listed.structured()["windows"]
.as_array()
.and_then(|windows| {
windows
.iter()
.find(|w| w["window_id"].as_u64() == Some(wid))
})
.map(|w| w["bounds"].clone())
.expect("AppKit harness window bounds");
let width = current["width"].as_f64().expect("window width");
let height = current["height"].as_f64().expect("window height");
let (x, y) = (180.0, 260.0);
let moved = driver.call(
"set_window_frame",
serde_json::json!({
"pid": pid as i64, "window_id": wid,
"x": x, "y": y, "width": width, "height": height
}),
);
assert!(!moved.is_error(), "set_window_frame: {}", moved.text());
// Park the real pointer just above the window, outside its frame
// but close enough for ScreenCaptureKit to fold it into the
// capture (a benchmark parked it 27 pt above a window's top edge).
// SAFETY: plain CoreGraphics call with a by-value point.
unsafe {
CGWarpMouseCursorPosition(WarpPoint {
x: x + width / 2.0,
y: y - 24.0,
})
};
std::thread::sleep(Duration::from_millis(300));
let snapshot = snapshot_elements(driver, pid, wid);
assert!(!snapshot.is_error(), "capture: {}", snapshot.text());
let structured = snapshot.structured();
assert_eq!(structured["screenshot_frame_valid"], true, "{structured}");
let scale = structured["screenshot_scale"]
.as_f64()
.expect("screenshot scale");
let bounds = &structured["window_bounds"];
let data = snapshot.raw["result"]["content"]
.as_array()
.and_then(|parts| parts.iter().find(|part| part["type"] == "image"))
.and_then(|part| part["data"].as_str())
.expect("window screenshot image part");
let png = base64::engine::general_purpose::STANDARD
.decode(data)
.expect("decode screenshot");
let image = image::load_from_memory(&png)
.expect("load screenshot")
.to_rgba8();
let (w, h) = image.dimensions();
assert_eq!(
(f64::from(w), f64::from(h)),
(
(bounds["width"].as_f64().unwrap() * scale).round(),
(bounds["height"].as_f64().unwrap() * scale).round()
),
"screenshot size must match the window bounds at the reported scale"
);
// The bug left a transparent band across the top and down the
// right side of the image. Sample just inside each edge, away
// from the rounded corners: every sample must be the window's own
// opaque pixels.
let inset = (4.0 * scale) as u32;
let samples = [
(w / 2, inset), // top centre (title bar)
(w / 4, inset), // top, left of centre
(3 * w / 4, inset), // top, right of centre
(w - 1 - inset, h / 2), // right edge
(w - 1 - inset, h / 4), // right edge, upper
(w / 2, h - 1 - inset), // bottom centre
];
for (sx, sy) in samples {
let alpha = image.get_pixel(sx, sy).0[3];
assert_eq!(
alpha, 255,
"pixel ({sx},{sy}) of a {w}x{h} window screenshot is transparent: \
the window does not fill its own capture"
);
}
Observation::delivered(vec![OracleKind::Pixels], Evidence::default())
},
);
}