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.

92.0 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.

//! Integration test against the CuaTestHarness.Wpf .NET 8 app.
//!
//! Pairs of test apps live under `libs/cua-driver/tests/fixtures/`. They
//! publish into `libs/cua-driver/rust/test-apps/harness-{wpf,winui3}/` and
//! get mapped into the sandbox by the legacy Windows Sandbox runner.
//!
//! Each scenario covers a Win32 hosting pattern the agent should handle:
//! - counter: UIA Invoke on a plain WPF button
//! - text_body: get_window_state extracts known marker text
//! - message_box: modal MessageBox enumeration
//! - bottom_strip: Save/Cancel buttons present in the UIA tree (regression
//!   guard for the GetClientRect-vs-GetWindowRect capture bug fixed in #1696)
//! - owned_popup: owned secondary window discovered via list_windows
//! - layered_popup: WS_EX_LAYERED window enumerated and captured
//! - child_hwnd: native Win32 BUTTON child HWND visible in tree
//!
//! Run via the sandbox runner:
//!   ..\tests\runners\windows-sandbox\run-tests-in-sandbox.ps1 harness_wpf
//!
//! Or locally (requires .NET 8 SDK + `tests/fixtures/build/windows.ps1`):
//!   cargo test --test harness_wpf_test -- --ignored --nocapture
//!
//! Tests are `#[ignore]` so they don't run in plain `cargo test`. The
//! sandbox runner unignores them explicitly via the `--ignored` arg.
//!
//! **Foreground-lock caveat:** a handful of these tests (`double_click`,
//! `right_click`, `type_text`) rely on `delivery_mode:"foreground"` to reach
//! WPF's input chain reliably. Windows' system-wide foreground-lock
//! kicks in after ~30s with no real user input — once that happens,
//! `SetForegroundWindow` is denied for non-UIAccess processes and the
//! tests fail. Run the WPF and WinUI3 suites as **separate** `cargo test`
//! invocations (`--test harness_wpf_test`, then `--test harness_winui3_test`)
//! rather than combined: each binary's first ~30s falls inside the
//! foreground-lock window and stays green. The sandbox runner does this
//! automatically.

#![cfg(target_os = "windows")]

use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use cua_driver_testkit::e2e::{
    execute_case, native_background_case, native_foreground_case, native_readonly_case,
    recording_evidence, CaseSpec, Delivery, DriverRoute, Evidence, Observation, OracleKind,
    RefusalCode, Scope, Targeting,
};
use cua_driver_testkit::observer::TargetWindow;
use cua_driver_testkit::sentinel::{run_with_background_oracles, ForegroundSentinel};
use cua_driver_testkit::{ax, harness_app, spawn_in_job, Driver, McpDriver, ToolResponse};
use windows::Win32::Foundation::{HWND, POINT, RECT};
use windows::Win32::UI::WindowsAndMessaging::{
    GetCursorPos, GetWindowLongPtrW, GetWindowRect, IsIconic, SetCursorPos, SetWindowPos,
    ShowWindow, GWL_EXSTYLE, HWND_TOPMOST, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SW_MINIMIZE,
    WS_EX_TOPMOST,
};

#[path = "support/foreground_text_oracle.rs"]
mod foreground_text_oracle;
use foreground_text_oracle::{ascii_escape, normalize_line_endings, stable_text};

// ── harness launcher ─────────────────────────────────────────────────────────

fn harness_exe() -> PathBuf {
    if let Ok(p) = std::env::var("HARNESS_WPF_EXE") {
        let pb = PathBuf::from(p);
        if pb.exists() {
            return pb;
        }
    }
    harness_app("harness-wpf", "CuaTestHarness.Wpf.exe")
}

/// Launch the WPF harness app, tying its lifetime to `driver`'s reaper (the
/// Windows kill-on-close Job Object) and returning its pid. Returns `None`
/// (with a skip message) if the harness isn't built. We spawn via
/// `spawn_in_job` and grab the pid before handing the child to the reaper so
/// every subsequent `list_windows`/`find_window` filters on the exact spawned
/// pid — defensive against the corner case where a previous test's harness
/// hasn't been fully reaped and there are briefly two CuaTestHarness.Wpf
/// windows on the desktop.
fn launch_harness(driver: &mut McpDriver) -> Option<u32> {
    launch_harness_with_state_file(driver, None)
}

fn launch_harness_with_state_file(
    driver: &mut McpDriver,
    state_path: Option<&std::path::Path>,
) -> Option<u32> {
    let exe = harness_exe();
    if !exe.exists() {
        eprintln!("harness exe not found at {exe:?} — run tests/fixtures/build/windows.ps1 first");
        return None;
    }
    let mut command = Command::new(&exe);
    command.stdout(Stdio::null()).stderr(Stdio::null());
    if let Some(path) = state_path {
        command.env("CUA_E2E_FIXTURE_STATE_PATH", path);
    }
    let app = spawn_in_job(&mut command).ok()?;
    let pid = app.id();
    driver.reaper().push(app);
    // Short fixed settle for cold-start (window-creation + initial
    // foreground hand-off after spawn) — the rest of the readiness
    // wait happens via polling in find_window. A 200ms-only
    // wait turned out to be too short for the harness to establish
    // foreground reliably under test-batch load, which caused
    // SetForegroundWindow-needing tests (delivery_mode:foreground) to
    // fail with a foreground-lock rejection.
    std::thread::sleep(Duration::from_millis(800));
    Some(pid)
}

// Get a UIA snapshot's flat element list — used to assert AutomationIds
// exist in the tree without depending on tree-walk order, and to read the
// harness's marker/status text.
fn snapshot(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"
        }),
    )
}

fn element_token_by_id(snapshot: &ToolResponse, identifier: &str) -> String {
    let index = ax::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 snapshot_lines_containing(text: &str, needles: &[&str]) -> String {
    let mut lines = Vec::new();
    for line in text.lines() {
        let lower = line.to_lowercase();
        if needles
            .iter()
            .any(|needle| lower.contains(&needle.to_lowercase()))
        {
            lines.push(line.trim().to_owned());
        }
    }
    if lines.is_empty() {
        text.lines().take(80).collect::<Vec<_>>().join(" / ")
    } else {
        lines.join(" / ")
    }
}

fn fixture_state_line<'a>(text: &'a str, marker: &str) -> &'a str {
    text.lines()
        .find(|line| line.contains(marker))
        .unwrap_or_else(|| panic!("fixture state marker {marker:?} missing from snapshot"))
}

fn window_bounds(driver: &mut McpDriver, pid: u32, wid: u64) -> (f64, f64, f64, f64) {
    let response = driver.call("list_windows", serde_json::json!({ "pid": pid as i64 }));
    let window = response.structured()["windows"]
        .as_array()
        .and_then(|windows| {
            windows
                .iter()
                .find(|window| window["window_id"].as_u64() == Some(wid))
        })
        .unwrap_or_else(|| {
            panic!(
                "WPF window {wid} is missing from list_windows: {}",
                response.text()
            )
        });
    let bounds = &window["bounds"];
    (
        bounds["x"].as_f64().expect("WPF window bounds need x"),
        bounds["y"].as_f64().expect("WPF window bounds need y"),
        bounds["width"]
            .as_f64()
            .expect("WPF window bounds need width"),
        bounds["height"]
            .as_f64()
            .expect("WPF window bounds need height"),
    )
}

fn pixel_center(state: &ToolResponse, target_id: &str, window: (f64, f64, f64, f64)) -> (f64, f64) {
    let (x, y, width, height) = pixel_frame(state, target_id, window);
    (x + width / 2.0, y + height / 2.0)
}

fn pixel_frame(
    state: &ToolResponse,
    target_id: &str,
    window: (f64, f64, f64, f64),
) -> (f64, f64, f64, f64) {
    let target_index = ax::element_index_by_id(state.text(), target_id)
        .unwrap_or_else(|| panic!("missing PX target {target_id:?}: {}", state.text()));
    let elements = state.structured()["elements"]
        .as_array()
        .expect("PX targeting requires structured elements");
    let target = elements
        .iter()
        .find(|element| element["element_index"].as_u64() == Some(target_index))
        .and_then(|element| element["frame"].as_object())
        .unwrap_or_else(|| panic!("element [{target_index}] has no structured frame"));
    let target_w = target["w"].as_f64().unwrap_or(0.0);
    let target_h = target["h"].as_f64().unwrap_or(0.0);
    let (window_x, window_y, window_w, window_h) = window;
    assert!(
        target_w > 0.0 && target_h > 0.0 && window_w > 0.0 && window_h > 0.0,
        "WPF PX target and window need positive geometry: target={target:?}, window={window:?}"
    );
    let screenshot_w = state.structured()["screenshot_width"]
        .as_f64()
        .expect("PX targeting requires screenshot_width");
    let screenshot_h = state.structured()["screenshot_height"]
        .as_f64()
        .expect("PX targeting requires screenshot_height");
    let scale_x = screenshot_w / window_w;
    let scale_y = screenshot_h / window_h;
    let x = (target["x"].as_f64().unwrap_or(0.0) + target_w / 2.0 - window_x) * scale_x;
    let y = (target["y"].as_f64().unwrap_or(0.0) + target_h / 2.0 - window_y) * scale_y;
    let width = target_w * scale_x;
    let height = target_h * scale_y;
    let x = x - width / 2.0;
    let y = y - height / 2.0;
    assert!(
        x >= 0.0 && x + width <= screenshot_w && y >= 0.0 && y + height <= screenshot_h,
        "WPF PX target frame ({x:.1}, {y:.1}, {width:.1}, {height:.1}) is outside the capture ({screenshot_w:.1}x{screenshot_h:.1})"
    );
    (x, y, width, height)
}

fn wait_for_fixture_file_text(path: &std::path::Path, id: &str, expected: &str) {
    let deadline = Instant::now() + Duration::from_secs(3);
    loop {
        if let Ok(body) = std::fs::read(path) {
            if let Ok(state) = serde_json::from_slice::<serde_json::Value>(&body) {
                if state[id]["text"].as_str() == Some(expected) {
                    return;
                }
            }
        }
        assert!(
            Instant::now() < deadline,
            "WPF fixture state {id:?} did not reach {expected:?}: {}",
            std::fs::read_to_string(path).unwrap_or_else(|_| "<missing>".to_owned())
        );
        std::thread::sleep(Duration::from_millis(50));
    }
}

// ── tests ────────────────────────────────────────────────────────────────────

#[test]
#[ignore]
fn harness_wpf_smoke() {
    run_case(
        native_readonly_case(
            "wpf",
            "ax_tree",
            Targeting::Ax,
            DriverRoute::AxRead,
            vec![OracleKind::AxState],
        ),
        |pid, wid, driver| {
            let snap = snapshot(driver, pid, wid);
            assert!(!snap.is_error(), "WPF AX snapshot failed: {}", snap.text());
            let text = snap.text();
            for aid in [
                "btn-increment",
                "btn-reset",
                "btn-open-msgbox",
                "btn-save",
                "btn-cancel",
                "btn-open-owned",
                "btn-open-layered",
                "btn-exit",
            ] {
                assert!(
                    ax::has_id(text, aid),
                    "missing AutomationId {aid} in WPF UIA snapshot"
                );
            }
            for marker in ["HARNESS_TEXT_MARKER_v1", "counter=0", "accel_fired=0"] {
                assert!(text.contains(marker), "missing WPF AX marker {marker}");
            }
            assert!(
                text.contains("\"Native Win32 Child\""),
                "native HWND child button not in snapshot"
            );
            Observation::delivered(vec![OracleKind::AxState], Evidence::default())
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_query_projects_structured_elements() {
    run_case(
        native_readonly_case(
            "wpf",
            "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_eq!(
                response.structured()["elements_complete"].as_bool(),
                Some(true),
                "query projection must preserve the complete underlying UIA snapshot"
            );
            let _ = element_token_by_id(&response, "btn-increment");

            let bounded = driver.call(
                "get_window_state",
                serde_json::json!({
                    "pid": pid as i64,
                    "window_id": wid,
                    "max_elements": 1,
                    "include_screenshot": false
                }),
            );
            assert!(
                !bounded.is_error(),
                "bounded snapshot failed: {}",
                bounded.text()
            );
            assert_eq!(
                bounded.structured()["elements_complete"].as_bool(),
                Some(false),
                "a bound that skips the WPF root's descendants must report an incomplete snapshot"
            );

            let shallow = driver.call(
                "get_window_state",
                serde_json::json!({
                    "pid": pid as i64,
                    "window_id": wid,
                    "max_depth": 1,
                    "include_screenshot": false
                }),
            );
            assert!(
                !shallow.is_error(),
                "depth-bounded snapshot failed: {}",
                shallow.text()
            );
            assert_eq!(
                shallow.structured()["elements_complete"].as_bool(),
                Some(false),
                "a depth bound that skips WPF descendants must report an incomplete snapshot"
            );

            let verified = driver.call(
                "verify_state",
                serde_json::json!({
                    "pid": pid as i64,
                    "window_id": wid,
                    "expect": [{"element": {
                        "selector": {"label_contains": "__cua_missing_completeness_probe__"},
                        "exists": true
                    }}],
                    "timeout_ms": 0,
                    "stable_samples": 1,
                    "include_screenshot": false
                }),
            );
            assert!(
                !verified.is_error(),
                "verification failed: {}",
                verified.text()
            );
            assert_eq!(
                verified.structured()["status"],
                "unknown",
                "a structured projection that omits display-only nodes cannot prove absence"
            );
            assert_eq!(
                verified.structured()["predicates"][0]["unknown_reason"],
                "observation_unavailable"
            );
            Observation::delivered(vec![OracleKind::AxState], Evidence::default())
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_stale_element_token_fails_closed() {
    run_case(
        native_readonly_case(
            "wpf",
            "stale_element_token",
            Targeting::Ax,
            DriverRoute::AxRead,
            vec![OracleKind::AxState],
        ),
        |pid, wid, driver| {
            let first = snapshot(driver, pid, wid);
            let token = element_token_by_id(&first, "btn-increment");
            let _newer = snapshot(driver, pid, wid);
            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")
            );
            assert!(snapshot(driver, pid, wid).tree_text().contains("counter=0"));
            Observation::delivered(vec![OracleKind::AxState], Evidence::default())
        },
    );
}

// ── shared driver session helper ─────────────────────────────────────────────

/// Spin up a fresh cua-driver + harness pair, run the closure, then tear
/// everything down (the harness app is reaped with the driver via the Job
/// Object). Returns whatever the closure returns. The closure receives the
/// harness pid, a pre-resolved main window_id, and the driver.
fn with_named_session<F, R>(label: &str, f: F) -> Option<R>
where
    F: FnOnce(u32, u64, &mut McpDriver) -> R,
{
    let mut driver = McpDriver::spawn_named(label)?;
    let pid = launch_harness(&mut driver)?;
    let (wid, _) = driver
        .find_window(pid as i64, "CuaTestHarness WPF")
        .expect("main window");
    Some(f(pid, wid, &mut driver))
}

fn run_case(case: CaseSpec, test: impl FnOnce(u32, u64, &mut McpDriver) -> Observation) {
    let cell_id = case.cell_id.clone();
    let delivery = case.delivery;
    execute_case(case, |evidence| {
        with_named_session(&cell_id, |pid, wid, driver| {
            *evidence = recording_evidence(driver.recording_dir());
            if delivery == Delivery::NotApplicable {
                driver.start_behavior_recording();
            }
            test(pid, wid, driver)
        })
        .expect("required WPF session did not start")
    });
}

fn run_foreground_case(
    action: &str,
    targeting: Targeting,
    route: DriverRoute,
    extra_oracles: Vec<OracleKind>,
    test: impl FnOnce(u32, u64, &mut McpDriver) -> Vec<OracleKind>,
) {
    let mut case = native_foreground_case("wpf", action, targeting, route);
    case.oracles.extend(extra_oracles);
    case.oracles.sort();
    case.oracles.dedup();
    run_case(case, |pid, wid, driver| {
        let mut passed = test(pid, wid, driver);
        passed.push(OracleKind::FixtureState);
        Observation::delivered(passed, Evidence::default())
    });
}

fn run_background_case(
    action: &str,
    route: DriverRoute,
    test: impl FnOnce(u32, u64, &mut McpDriver),
) {
    run_case(
        native_background_case("wpf", action, Targeting::Ax, 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)
        },
    );
}

fn observe_background<R>(
    driver: &mut McpDriver,
    pid: u32,
    wid: u64,
    action: impl FnOnce(&mut McpDriver) -> R,
) -> (R, Vec<OracleKind>) {
    let sentinel = ForegroundSentinel::launch(driver);
    sentinel
        .assert_background_posture(TargetWindow {
            pid,
            native_id: wid,
        })
        .expect("establish WPF background posture before recording");
    driver.start_behavior_recording();
    let (result, passed) = sentinel
        .observe_background(
            TargetWindow {
                pid,
                native_id: wid,
            },
            || action(driver),
        )
        .unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));
    for required in [
        OracleKind::Focus,
        OracleKind::ZOrder,
        OracleKind::Cursor,
        OracleKind::NoLeakedInput,
    ] {
        assert!(
            passed.contains(&required),
            "background observer omitted required {required:?} oracle"
        );
    }
    (result, passed)
}

fn background_case(action: &str, route: DriverRoute) -> CaseSpec {
    CaseSpec::delivered(
        format!("windows-wpf-{action}-ax-background").replace('_', "-"),
        "wpf",
        "wpf",
        action,
        Targeting::Ax,
        Delivery::Background,
        Scope::Window,
        route,
        vec![
            OracleKind::FixtureState,
            OracleKind::Focus,
            OracleKind::ZOrder,
            OracleKind::Cursor,
            OracleKind::NoLeakedInput,
        ],
    )
}

fn delivered_with_fixture_state(mut passed: Vec<OracleKind>) -> Observation {
    passed.push(OracleKind::FixtureState);
    passed.sort();
    passed.dedup();
    Observation::delivered(passed, Evidence::default())
}

#[test]
#[ignore]
fn harness_wpf_counter_invoke() {
    execute_case(
        background_case("left_click", DriverRoute::UiaInvoke),
        |evidence| {
            let mut driver = McpDriver::spawn_named("windows-wpf-left-click-ax-background")
                .expect("required source-built driver did not start");
            *evidence = recording_evidence(driver.recording_dir());
            let pid = launch_harness(&mut driver).expect("required WPF harness did not launch");
            let (wid, _) = driver
                .find_window(pid as i64, "CuaTestHarness WPF")
                .expect("main window");
            let pre = snapshot(&mut driver, pid, wid);
            let idx = ax::element_index_by_id(pre.text(), "btn-increment")
                .expect("btn-increment not in pre-snapshot");
            let (click, passed) = observe_background(&mut driver, pid, wid, |driver| {
                driver.call(
                    "click",
                    serde_json::json!({
                        "pid": pid as i64, "window_id": wid, "element_token": pre.element_token(idx),
                        "delivery_mode": "background"
                    }),
                )
            });
            assert!(!click.is_error(), "counter click failed: {}", click.text());
            std::thread::sleep(Duration::from_millis(300));
            let post = snapshot(&mut driver, pid, wid);
            assert!(
                post.text().contains("counter=1"),
                "counter label did not advance after click: {}",
                post.text().chars().take(400).collect::<String>()
            );
            delivered_with_fixture_state(passed)
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_minimized_element_click_refuses_without_side_effects() {
    let case = CaseSpec::delivered(
        "windows-wpf-minimized-element-click-refusal",
        "wpf",
        "wpf",
        "left_click",
        Targeting::Ax,
        Delivery::Background,
        Scope::Window,
        DriverRoute::Composite,
        vec![
            OracleKind::FixtureState,
            OracleKind::Focus,
            OracleKind::ZOrder,
            OracleKind::Cursor,
            OracleKind::NoLeakedInput,
            OracleKind::Protocol,
        ],
    )
    .expecting_refusal(vec![RefusalCode::WindowMinimized]);

    execute_case(case, |evidence| {
        let mut driver = McpDriver::spawn_named("windows-wpf-minimized-element-click-refusal")
            .expect("required source-built driver did not start");
        *evidence = recording_evidence(driver.recording_dir());
        let state_dir = tempfile::tempdir().expect("create WPF fixture state directory");
        let state_path = state_dir.path().join("state.json");
        let pid = launch_harness_with_state_file(&mut driver, Some(&state_path))
            .expect("required WPF harness did not launch");
        let (wid, _) = driver
            .find_window(pid as i64, "CuaTestHarness WPF")
            .expect("main window");
        wait_for_fixture_file_text(&state_path, "lbl-counter", "counter=0");
        let ready = snapshot(&mut driver, pid, wid);
        let idx = ax::element_index_by_id(ready.text(), "btn-increment")
            .expect("btn-increment not in pre-minimize snapshot");

        let sentinel = ForegroundSentinel::launch(&mut driver);
        let hwnd = HWND(wid as *mut _);
        let _ = unsafe { ShowWindow(hwnd, SW_MINIMIZE) };
        let deadline = Instant::now() + Duration::from_secs(2);
        while !unsafe { IsIconic(hwnd) }.as_bool() {
            assert!(Instant::now() < deadline, "WPF target did not minimize");
            std::thread::sleep(Duration::from_millis(25));
        }
        driver.start_behavior_recording();

        let (response, mut passed) = sentinel
            .observe_desktop(|| {
                driver.call(
                    "click",
                    serde_json::json!({
                        "pid": pid as i64,
                        "window_id": wid,
                        "element_token": ready.element_token(idx),
                        "delivery_mode": "background"
                    }),
                )
            })
            .unwrap_or_else(|error| panic!("minimized refusal leaked desktop state: {error}"));
        assert!(
            response.is_error(),
            "minimized click reported success: {}",
            response.text()
        );
        assert_eq!(response.structured()["status"], "refused");
        assert_eq!(response.structured()["refusal"]["code"], "window_minimized");
        assert!(
            unsafe { IsIconic(hwnd) }.as_bool(),
            "refused click restored or otherwise changed the minimized target"
        );
        std::thread::sleep(Duration::from_millis(300));
        wait_for_fixture_file_text(&state_path, "lbl-counter", "counter=0");

        passed.extend([OracleKind::FixtureState, OracleKind::Protocol]);
        passed.sort();
        passed.dedup();
        Observation::refused(
            RefusalCode::WindowMinimized,
            passed,
            response.text(),
            Evidence::default(),
        )
    });
}

#[test]
#[ignore]
fn harness_wpf_left_click_px_background() {
    let case = native_background_case("wpf", "left_click", Targeting::Px, DriverRoute::UiaInvoke);
    execute_case(case, |evidence| {
        let mut driver = McpDriver::spawn_named("windows-wpf-left-click-px-background")
            .expect("required source-built driver did not start");
        *evidence = recording_evidence(driver.recording_dir());
        let state_dir = tempfile::tempdir().expect("create WPF fixture state directory");
        let state_path = state_dir.path().join("state.json");
        let pid = launch_harness_with_state_file(&mut driver, Some(&state_path))
            .expect("required WPF harness did not launch");
        let (wid, _) = driver
            .find_window(pid as i64, "CuaTestHarness WPF")
            .expect("main window");
        wait_for_fixture_file_text(&state_path, "lbl-click-count", "clicks=0");

        let config = driver.call(
            "set_config",
            serde_json::json!({"max_image_dimension": 200}),
        );
        assert!(
            !config.is_error(),
            "small capture config: {}",
            config.text()
        );
        let bounds = window_bounds(&mut driver, pid, wid);
        let ready_state = snapshot(&mut driver, pid, wid);
        let (x, y) = pixel_center(&ready_state, "border-click-target", bounds);
        let zoom = driver.call(
            "zoom",
            serde_json::json!({
                "pid": pid as i64, "window_id": wid,
                "x1": x - 5.0, "y1": y - 5.0, "x2": x + 5.0, "y2": y + 5.0
            }),
        );
        assert!(
            !zoom.is_error(),
            "create owned zoom context: {}",
            zoom.text()
        );
        let small_width = ready_state.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(&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"}),
            ),
            (
                "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");
        }
        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");
        }
        let stale = driver.call(
            "click",
            serde_json::json!({
                "pid": pid as i64, "window_id": wid,
                "x": x, "y": y, "delivery_mode": "foreground"
            }),
        );
        assert_eq!(stale.structured()["code"], "screenshot_context_missing");

        let ready_state = snapshot(&mut driver, pid, wid);
        let (x, y) = pixel_center(&ready_state, "border-click-target", bounds);
        let geometry_probe = driver.call(
            "click",
            serde_json::json!({
                "pid": pid as i64,
                "window_id": wid,
                "x": x,
                "y": y,
                "delivery_mode": "foreground"
            }),
        );
        assert!(
            !geometry_probe.is_error(),
            "WPF foreground PX geometry probe failed: {}",
            geometry_probe.text()
        );
        wait_for_fixture_file_text(&state_path, "lbl-click-count", "clicks=1");

        let (click, passed) = observe_background(&mut driver, pid, wid, |driver| {
            driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64,
                    "window_id": wid,
                    "x": x,
                    "y": y,
                    "delivery_mode": "background"
                }),
            )
        });
        assert!(
            !click.is_error(),
            "WPF PX background click failed: {}",
            click.text()
        );
        assert_eq!(
            click.action_route(),
            Some("accessibility"),
            "WPF PX background click used an unexpected driver route: {}",
            click.text()
        );
        wait_for_fixture_file_text(&state_path, "lbl-click-count", "clicks=2");
        wait_for_fixture_file_text(&state_path, "lbl-last-action", "last_action=left_click");
        delivered_with_fixture_state(passed)
    });
}

#[test]
#[ignore]
fn harness_wpf_type_text() {
    run_foreground_case(
        "type_text",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "txt-input")
                .expect("txt-input not in snapshot");
            driver.start_behavior_recording();

            // The fixture deliberately starts with txt-deferred-input focused.
            // A single indexed type_text call must atomically activate the WPF
            // window, focus txt-input, confirm that focus, and only then inject.
            let resp = driver.call(
                "type_text",
                serde_json::json!({
                    "pid": pid as i64,
                    "window_id": wid,
                    "element_token": snap.element_token(idx),
                    "text": "harness-typed",
                    "delivery_mode": "foreground"
                }),
            );
            println!("type_text: {}", resp.text());
            assert!(!resp.is_error(), "type_text failed: {}", resp.text());
            std::thread::sleep(Duration::from_millis(700));

            let post = snapshot(driver, pid, wid);
            let text = post.text();
            let mirror_lines: Vec<&str> = text
                .lines()
                .filter(|l| l.contains("mirror=") || l.contains("txt-input"))
                .collect();
            assert!(
                text.contains("mirror=harness-typed"),
                "TextBox mirror did not reflect typed text. Mirror/input lines: {:?}",
                mirror_lines
            );
            let decoy_idx = ax::element_index_by_id(text, "txt-deferred-input")
                .expect("txt-deferred-input not in post-action snapshot");
            let decoy = post.structured()["elements"]
                .as_array()
                .and_then(|elements| {
                    elements
                        .iter()
                        .find(|element| element["element_index"].as_u64() == Some(decoy_idx))
                })
                .expect("txt-deferred-input missing from structured elements");
            assert!(
                decoy["value"].as_str().unwrap_or_default().is_empty(),
                "foreground type_text leaked into the pre-focused decoy: {decoy}"
            );
            println!("✅ harness_wpf_type_text: TextBox mirror advanced to 'harness-typed'");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_type_text_foreground_single_line_application_state() {
    const TEXT: &str = "FOREGROUND-SINGLE-19 \u{4e2d}\u{6587} 12345 \u{1f642}";

    let mut case = native_foreground_case(
        "wpf",
        "type_text",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
    );
    case.cell_id.push_str("-single-line-state");
    let cell_id = case.cell_id.clone();

    execute_case(case, |evidence| {
        let state_dir = tempfile::tempdir().expect("create isolated WPF state directory");
        let state_path = state_dir.path().join("fixture-state.json");
        let mut driver = McpDriver::spawn_named(&cell_id)
            .expect("required source-built Windows driver did not start");
        *evidence = recording_evidence(driver.recording_dir());

        let pid = launch_harness_with_state_file(&mut driver, Some(&state_path))
            .expect("required WPF harness did not launch");
        let (wid, _) = driver
            .find_window(pid as i64, "CuaTestHarness WPF")
            .expect("WPF main window not found");
        assert_eq!(stable_text(&state_path, "txt-input"), "");

        let snap = snapshot(&mut driver, pid, wid);
        let idx = ax::element_index_by_id(snap.tree_text(), "txt-input")
            .expect("txt-input not in WPF snapshot");
        driver.start_behavior_recording();
        let response = driver.call(
            "type_text",
            serde_json::json!({
                "pid": pid as i64,
                "window_id": wid,
                "element_token": snap.element_token(idx),
                "text": TEXT,
                "delivery_mode": "foreground"
            }),
        );
        assert!(
            !response.is_error(),
            "foreground type_text failed: {}",
            response.text()
        );
        assert_eq!(response.structured()["route"], "global_input");
        assert_eq!(stable_text(&state_path, "txt-input"), TEXT);
        assert_eq!(stable_text(&state_path, "txt-deferred-input"), "");

        drop(driver);
        Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
    });
}

#[test]
#[ignore]
fn harness_wpf_type_text_multiline_application_state() {
    const TEXT: &str = concat!(
        "\n",
        "CUA-MULTILINE-START\n",
        "ASCII-LF-A-31\nASCII-LF-B-47\n",
        "ASCII-CRLF-A-52\r\nASCII-CRLF-B-68\n",
        "ASCII-CR-A-13\rASCII-CR-B-24\n",
        "\u{8f66}\u{6b21} G7391\r\n",
        "\u{4e2d}\u{6587} 12345\n",
        "EMPTY-A-17\n\n\nEMPTY-B-29\n",
        "EMOJI-A \u{1f642} 123\r\n",
        "EMOJI-B \u{1f680} 456\n",
        "CUA-MULTILINE-END\n"
    );

    let mut case = native_foreground_case(
        "wpf",
        "type_text",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
    );
    case.cell_id.push_str("-multiline");
    let cell_id = case.cell_id.clone();

    execute_case(case, |evidence| {
        let state_dir = tempfile::tempdir().expect("create isolated WPF state directory");
        let state_path = state_dir.path().join("fixture-state.json");
        let mut driver = McpDriver::spawn_named(&cell_id)
            .expect("required source-built Windows driver did not start");
        *evidence = recording_evidence(driver.recording_dir());

        let pid = launch_harness_with_state_file(&mut driver, Some(&state_path))
            .expect("required WPF harness did not launch");
        let (wid, _) = driver
            .find_window(pid as i64, "CuaTestHarness WPF")
            .expect("WPF main window not found");
        assert_eq!(
            stable_text(&state_path, "txt-multiline-input"),
            "",
            "multiline fixture must start blank"
        );

        let snap = snapshot(&mut driver, pid, wid);
        let idx = ax::element_index_by_id(snap.tree_text(), "txt-multiline-input")
            .expect("txt-multiline-input not in WPF snapshot");
        driver.start_behavior_recording();
        let response = driver.call(
            "type_text",
            serde_json::json!({
                "pid": pid as i64,
                "window_id": wid,
                "element_token": snap.element_token(idx),
                "text": TEXT,
                "delivery_mode": "foreground"
            }),
        );
        assert!(
            !response.is_error(),
            "WPF foreground multiline type_text failed: {}",
            response.text()
        );
        assert_eq!(
            response.structured()["route"],
            "global_input",
            "foreground multiline input must use SendInput: {}",
            response.structured()
        );

        let actual = stable_text(&state_path, "txt-multiline-input");
        assert_eq!(
            normalize_line_endings(&actual),
            normalize_line_endings(TEXT),
            "WPF app-owned multiline state differs; actual={} expected={}",
            ascii_escape(&actual),
            ascii_escape(TEXT)
        );
        assert_eq!(
            stable_text(&state_path, "txt-deferred-input"),
            "",
            "foreground multiline input leaked to the startup-focused decoy"
        );

        drop(driver);
        Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
    });
}

#[test]
#[ignore]
fn harness_wpf_set_value() {
    execute_case(
        background_case("set_value", DriverRoute::UiaValue),
        |evidence| {
            with_named_session("windows-wpf-set-value-ax-background", |pid, wid, driver| {
                *evidence = recording_evidence(driver.recording_dir());
                let snap = snapshot(driver, pid, wid);
                let idx = ax::element_index_by_id(snap.text(), "txt-input")
                    .expect("txt-input not in snapshot");
                let (response, passed) = observe_background(driver, pid, wid, |driver| {
                    driver.call(
                        "set_value",
                        serde_json::json!({
                            "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                            "value": "via-uia-setvalue"
                        }),
                    )
                });
                assert!(
                    !response.is_error(),
                    "set_value failed: {}",
                    response.text()
                );
                std::thread::sleep(Duration::from_millis(400));
                let post = snapshot(driver, pid, wid);
                assert!(
                    post.text().contains("mirror=via-uia-setvalue"),
                    "set_value did not update TextBox: {}",
                    post.text().chars().take(500).collect::<String>()
                );
                delivered_with_fixture_state(passed)
            })
            .expect("required WPF session did not start")
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_deferred_type_text_requires_fresh_snapshot_before_retry() {
    execute_case(
        background_case("deferred-type-text", DriverRoute::UiaValue),
        |evidence| {
            with_named_session(
                "windows-wpf-deferred-type-text-ax-background",
                |pid, wid, driver| {
                    *evidence = recording_evidence(driver.recording_dir());
                    let snap = snapshot(driver, pid, wid);
                    let idx = ax::element_index_by_id(snap.text(), "txt-deferred-input")
                        .expect("txt-deferred-input not in snapshot");
                    let (response, passed) = observe_background(driver, pid, wid, |driver| {
                        driver.call(
                            "type_text",
                            serde_json::json!({
                                "pid": pid as i64,
                                "window_id": wid,
                                "element_token": snap.element_token(idx),
                                "text": "deferred-once",
                                "delivery_mode": "background"
                            }),
                        )
                    });
                    assert!(
                        !response.is_error(),
                        "type_text failed: {}",
                        response.text()
                    );
                    assert_eq!(response.action_effect(), Some("unverifiable"));
                    assert_eq!(response.action_route(), Some("accessibility"));
                    assert!(
                        response.structured().get("escalation").is_none(),
                        "deferred publication must not recommend an immediate retry: {}",
                        response.structured()
                    );

                    std::thread::sleep(Duration::from_millis(700));
                    let post = snapshot(driver, pid, wid);
                    assert!(
                        post.text().contains("deferred_mirror=deferred-once"),
                        "fresh snapshot did not observe exactly one deferred write: {}",
                        post.text().chars().take(700).collect::<String>()
                    );
                    delivered_with_fixture_state(passed)
                },
            )
            .expect("required WPF session did not start")
        },
    );
}

// In test-batch mode (many harnesses launched/killed in sequence) the WPF
// window's input pump occasionally misses background PostMessage events —
// reproducibly passes in isolation, intermittently fails in batch.
// `bring_to_front` pays the foreground swap once so the click test
// exercises the click-event-handling path itself, not the
// background-delivery path (which the counter_invoke test already
// covers via UIA Invoke).
fn focus_harness(driver: &mut McpDriver, pid: u32, wid: u64) {
    let _ = driver.call(
        "bring_to_front",
        serde_json::json!({
            "pid": pid as i64, "window_id": wid
        }),
    );
    std::thread::sleep(Duration::from_millis(300));
    driver.start_behavior_recording();
}

#[test]
#[ignore]
fn harness_wpf_right_click() {
    run_foreground_case(
        "right_click",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = driver.call(
                "get_window_state",
                serde_json::json!({"pid": pid, "window_id": wid, "full_output": true}),
            );
            let idx = ax::element_index_by_id(snap.text(), "border-click-target")
                .expect("border-click-target not in snapshot");
            let frame = &snap.structured()["elements"]
                .as_array()
                .expect("structured elements")
                .iter()
                .find(|element| element["element_index"].as_u64() == Some(idx))
                .expect("right-click target frame")["frame"];
            let click_x = frame["x"].as_f64().unwrap() + frame["w"].as_f64().unwrap() / 2.0;
            let click_y = frame["y"].as_f64().unwrap() + frame["h"].as_f64().unwrap() / 2.0;
            let mut window_rect = RECT::default();
            unsafe {
                GetWindowRect(HWND(wid as *mut _), &mut window_rect).expect("read harness bounds");
                SetCursorPos(window_rect.left + 10, window_rect.top + 10)
                    .expect("place cursor away from right-click target");
            }
            // Same delivery_mode:foreground rationale as type_text — PostMessage
            // WM_RBUTTONDOWN doesn't always reach WPF's MouseRightButtonDown
            // routed-event chain (intermittent in batch runs).
            let mut cursor_before = POINT::default();
            unsafe { GetCursorPos(&mut cursor_before) }.expect("read cursor before click");
            assert!(
                (cursor_before.x as f64 - click_x).abs() > 2.0
                    || (cursor_before.y as f64 - click_y).abs() > 2.0,
                "cursor must start away from the injected point"
            );
            let resp = driver.call(
                "right_click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            let mut cursor_after = POINT::default();
            unsafe { GetCursorPos(&mut cursor_after) }.expect("read cursor after click");
            assert_eq!(
                (cursor_after.x, cursor_after.y),
                (cursor_before.x, cursor_before.y),
                "foreground right click left the real cursor at the target"
            );
            println!("right_click: {}", resp.text());
            std::thread::sleep(Duration::from_millis(400));

            let post = snapshot(driver, pid, wid);
            let text = post.text();
            let action_lines: Vec<&str> = text
                .lines()
                .filter(|l| l.contains("last_action=") || l.contains("clicks="))
                .collect();
            assert!(
                text.contains("last_action=right_click"),
                "right_click handler did not fire. Action/click lines: {:?}",
                action_lines
            );
            println!("✅ harness_wpf_right_click: last_action=right_click");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_double_click() {
    run_foreground_case(
        "double_click",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "border-click-target")
                .expect("border-click-target not in snapshot");
            // delivery_mode:foreground for the same reason as right_click —
            // PostMessage WM_LBUTTONDOWN ×2 doesn't always reach WPF's
            // MouseDoubleClick / ClickCount=2 path under test-batch load.
            let resp = driver.call(
                "double_click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            println!("double_click: {}", resp.text());
            std::thread::sleep(Duration::from_millis(400));

            let post = snapshot(driver, pid, wid);
            let text = post.text();
            let action_lines: Vec<&str> = text
                .lines()
                .filter(|l| l.contains("last_action=") || l.contains("clicks="))
                .collect();
            assert!(
                text.contains("last_action=double_click"),
                "double_click handler did not register a 2nd click. \
             Action/click lines: {:?}",
                action_lines
            );
            println!("✅ harness_wpf_double_click: last_action=double_click");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_press_key_accelerator() {
    // WPF's InputManager ignores posted key messages while another native
    // window owns foreground, even for an unmodified F5 binding. The driver
    // must refuse before posting instead of returning an unverifiable success.
    execute_case(
        background_case("keyboard", DriverRoute::PostMessage)
            .expecting_refusal(vec![RefusalCode::BackgroundUnavailable]),
        |evidence| {
            with_named_session("windows-wpf-keyboard-ax-background", |pid, wid, driver| {
                *evidence = recording_evidence(driver.recording_dir());
                let (response, mut passed) = observe_background(driver, pid, wid, |driver| {
                    driver.call(
                        "press_key",
                        serde_json::json!({
                            "pid": pid as i64, "window_id": wid, "key": "f5",
                            "delivery_mode": "background"
                        }),
                    )
                });
                assert!(
                    response.is_error(),
                    "WPF background press_key unexpectedly reported delivery: {}",
                    response.text()
                );
                let code = response.structured()["code"]
                    .as_str()
                    .and_then(RefusalCode::from_driver_code)
                    .expect("WPF background key refusal needs a structured code");
                let post = snapshot(driver, pid, wid);
                assert!(
                    post.text().contains("accel_fired=0"),
                    "refused WPF key mutated fixture state: {}",
                    post.text().chars().take(500).collect::<String>()
                );
                passed.push(OracleKind::FixtureState);
                Observation::refused(code, passed, response.text(), Evidence::default())
            })
            .expect("required WPF session did not start")
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_press_key_letter_accelerator() {
    run_foreground_case(
        "press_key",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let response = driver.call(
                "press_key",
                serde_json::json!({
                    "pid": pid as i64,
                    "window_id": wid,
                    "key": "h",
                    "modifiers": ["ctrl", "shift"],
                    "delivery_mode": "foreground"
                }),
            );
            assert!(
                !response.is_error(),
                "WPF foreground letter press_key failed: {}",
                response.text()
            );
            std::thread::sleep(Duration::from_millis(300));
            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("accel_fired=1"),
                "WPF letter press_key did not fire Ctrl+Shift+H: {}",
                snapshot_lines_containing(post.text(), &["accel_fired"])
            );
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_scroll() {
    execute_case(
        background_case("scroll", DriverRoute::UiaScroll),
        |evidence| {
            with_named_session("windows-wpf-scroll-ax-background", |pid, wid, driver| {
                *evidence = recording_evidence(driver.recording_dir());
                // Pre-snapshot to populate the cache + read initial offset.
                let pre = snapshot(driver, pid, wid);
                let pre_text = pre.text();
                assert!(
                    pre_text.contains("scroll_offset=0"),
                    "expected initial scroll_offset=0, got: {}",
                    pre_text
                        .lines()
                        .filter(|l| l.contains("scroll_offset"))
                        .collect::<Vec<_>>()
                        .join(" / ")
                );

                // Click into the ScrollViewer so it gets focus / its descendants
                // become the WM_VSCROLL target.
                let idx = ax::element_index_by_id(pre.text(), "scroll-tall")
                    .expect("scroll-tall not in snapshot");
                let _ = driver.call(
                    "click",
                    serde_json::json!({
                        "pid": pid as i64,
                        "window_id": wid,
                        "element_token": pre.element_token(idx),
                        "delivery_mode": "foreground"
                    }),
                );
                std::thread::sleep(Duration::from_millis(200));

                // Scroll down 5 lines. Keep this on the default background rung: the
                // WPF harness translates the driver's WM_VSCROLL messages into the
                // ScrollViewer movement we assert below.
                let (resp, passed) = observe_background(driver, pid, wid, |driver| {
                    driver.call(
                        "scroll",
                        serde_json::json!({
                            "pid": pid as i64, "window_id": wid,
                            "direction": "down", "by": "line", "amount": 5,
                            "delivery_mode": "background"
                        }),
                    )
                });
                assert!(!resp.is_error(), "scroll failed: {}", resp.text());
                println!("scroll down: {}", resp.text());
                std::thread::sleep(Duration::from_millis(400));

                let post = snapshot(driver, pid, wid);
                let text = post.text();
                let advanced = text
                    .lines()
                    .any(|l| l.contains("scroll_offset=") && !l.contains("scroll_offset=0\""));
                assert!(
                    advanced,
                    "scroll offset did not advance after WM_VSCROLL. Lines: {}",
                    text.lines()
                        .filter(|l| l.contains("scroll_offset"))
                        .collect::<Vec<_>>()
                        .join(" / ")
                );
                delivered_with_fixture_state(passed)
            })
            .expect("required WPF session did not start")
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_modal_messagebox() {
    run_foreground_case(
        "modal_messagebox",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        vec![OracleKind::AxState],
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "btn-open-msgbox")
                .expect("btn-open-msgbox not in snapshot");
            let open = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            assert!(!open.is_error(), "open message box failed: {}", open.text());
            std::thread::sleep(Duration::from_millis(600));

            // List windows — the modal MessageBox should be a new top-level window
            // owned by the same pid.
            let resp = driver.call(
                "list_windows",
                serde_json::json!({
                    "pid": pid as i64
                }),
            );
            let windows = resp.structured()["windows"]
                .as_array()
                .expect("windows array");
            let modal = windows
                .iter()
                .find(|w| {
                    w["title"]
                        .as_str()
                        .map(|t| t.contains("Harness MessageBox"))
                        .unwrap_or(false)
                })
                .expect("Harness MessageBox modal window not found");
            let modal_wid = modal["window_id"].as_u64().unwrap();
            println!("modal window_id={}", modal_wid);

            // Walk the modal's UIA tree — expect OK and Cancel buttons.
            let modal_snap = driver.call(
                "get_window_state",
                serde_json::json!({
                    "pid": pid as i64, "window_id": modal_wid, "capture_mode": "ax"
                }),
            );
            let modal_text = modal_snap.text();
            assert!(
                modal_text.contains("\"OK\""),
                "MessageBox UIA tree missing OK button. Tree: {}",
                modal_text.chars().take(800).collect::<String>()
            );
            assert!(
                modal_text.contains("\"Cancel\""),
                "MessageBox UIA tree missing Cancel button"
            );

            // Dismiss by clicking Cancel in the modal.
            let cancel_idx = modal_text
                .lines()
                .find(|l| l.contains("\"Cancel\"") && l.contains('['))
                .and_then(|l| {
                    let s = l.find('[')? + 1;
                    let e = l[s..].find(']')? + s;
                    l[s..e].trim().parse::<u64>().ok()
                })
                .expect("Cancel button element_index not parseable");
            let dismiss = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": modal_wid, "element_token": modal_snap.element_token(cancel_idx),
                    "delivery_mode": "foreground"
                }),
            );
            assert!(
                !dismiss.is_error(),
                "dismiss message box failed: {}",
                dismiss.text()
            );
            std::thread::sleep(Duration::from_millis(400));
            println!("✅ harness_wpf_modal_messagebox: opened + parsed + dismissed");
            vec![OracleKind::AxState]
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_owned_popup() {
    run_foreground_case(
        "owned_popup",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        vec![OracleKind::AxState],
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "btn-open-owned")
                .expect("btn-open-owned not in snapshot");
            let open = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            assert!(!open.is_error(), "open owned popup failed: {}", open.text());
            std::thread::sleep(Duration::from_millis(500));

            let resp = driver.call(
                "list_windows",
                serde_json::json!({
                    "pid": pid as i64
                }),
            );
            let windows = resp.structured()["windows"].as_array().unwrap();
            let owned = windows
                .iter()
                .find(|w| {
                    w["title"]
                        .as_str()
                        .map(|t| t.contains("Harness Owned Popup"))
                        .unwrap_or(false)
                })
                .expect("Harness Owned Popup window not found in list_windows");
            let owned_wid = owned["window_id"].as_u64().unwrap();

            let owned_snap = driver.call(
                "get_window_state",
                serde_json::json!({
                    "pid": pid as i64, "window_id": owned_wid, "capture_mode": "ax"
                }),
            );
            let owned_text = owned_snap.text();
            assert!(
                owned_text.contains("OWNED_POPUP_MARKER_v1"),
                "owned popup body marker missing. Tree: {}",
                owned_text.chars().take(600).collect::<String>()
            );
            println!("✅ harness_wpf_owned_popup: opened + parsed");
            vec![OracleKind::AxState]
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_layered_popup_capture() {
    run_foreground_case(
        "layered_popup_capture",
        Targeting::Ax,
        DriverRoute::Composite,
        vec![OracleKind::Pixels],
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "btn-open-layered")
                .expect("btn-open-layered not in snapshot");
            let open = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            assert!(
                !open.is_error(),
                "open layered popup failed: {}",
                open.text()
            );
            std::thread::sleep(Duration::from_millis(600));

            let resp = driver.call(
                "list_windows",
                serde_json::json!({
                    "pid": pid as i64
                }),
            );
            let windows = resp.structured()["windows"].as_array().unwrap();
            let layered = windows
                .iter()
                .find(|w| {
                    w["title"]
                        .as_str()
                        .map(|t| t.contains("Harness Layered Popup"))
                        .unwrap_or(false)
                })
                .expect("Harness Layered Popup window not found");
            let layered_wid = layered["window_id"].as_u64().unwrap();

            // Capture-only path — assert the screenshot is not all-black, which
            // is the failure mode for PrintWindow against layered windows
            // without the WGC fallback.
            let cap = driver.call(
                "get_window_state",
                serde_json::json!({
                    "pid": pid as i64, "window_id": layered_wid, "capture_mode": "vision"
                }),
            );
            let img_b64 = cap.raw["result"]["content"]
                .as_array()
                .and_then(|arr| {
                    arr.iter().find_map(|c| {
                        if c["type"] == "image" {
                            c["data"].as_str()
                        } else {
                            None
                        }
                    })
                })
                .expect("layered window capture returned no image");
            // Decode the PNG and look for any non-black pixel.
            let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, img_b64)
                .expect("base64");
            let img = image::load_from_memory(&bytes).expect("png decode");
            let rgb = img.to_rgb8();
            let any_color = rgb
                .pixels()
                .any(|p| p.0[0] > 12 || p.0[1] > 12 || p.0[2] > 12);
            assert!(
            any_color,
            "layered window capture is all-black ({}x{}). PrintWindow likely needs WGC fallback.",
            rgb.width(),
            rgb.height()
        );
            println!(
                "✅ harness_wpf_layered_popup_capture: capture has non-black pixels ({}x{})",
                rgb.width(),
                rgb.height()
            );
            vec![OracleKind::Pixels]
        },
    );
}

// ── slider / checkable / combo / list / menu coverage ────────────────────────

#[test]
#[ignore]
fn harness_wpf_slider_drag() {
    // Regression guard for the SendInput drag path. PostMessage drag
    // doesn't update GetKeyState, so WPF's Thumb-drag handler (which
    // polls Mouse.LeftButton via GetKeyState) never sees the button
    // held — the thumb stays put. delivery_mode:"foreground" routes through
    // send_drag_synthesized which goes via the system input queue and
    // DOES update GetKeyState, so the thumb actually tracks.
    //
    // Foreground-lock caveat: SetForegroundWindow can be rejected from
    // non-UIAccess processes during the daemon-process foreground swap.
    // bring_to_front first to make the harness foreground (via
    // AttachThreadInput), then SendInput's own SetForegroundWindow is a
    // no-op success.
    run_foreground_case(
        "slider_drag",
        Targeting::Px,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let pre = snapshot(driver, pid, wid);
            assert!(
                pre.text().contains("slider_value=0"),
                "initial slider_value=0 missing"
            );
            let (x, y, width, height) =
                pixel_frame(&pre, "sld-value", window_bounds(driver, pid, wid));

            let resp = driver.call(
                "drag",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid,
                    // Resolve the live UIA frame so fixture reordering and DPI
                    // scaling cannot silently move this drag onto another control.
                    "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": 700, "steps": 40,
                    "delivery_mode": "foreground"
                }),
            );
            let msg = resp.text();
            println!("drag slider (foreground): {msg}");
            assert!(
                msg.starts_with("✅"),
                "drag tool returned non-success: {msg}"
            );
            std::thread::sleep(Duration::from_millis(500));

            let post = snapshot(driver, pid, wid);
            let text = post.text();
            let advanced = text
                .lines()
                .any(|l| l.contains("slider_value=") && !l.contains("slider_value=0\""));
            assert!(
                advanced,
                "Slider value did not advance via SendInput drag. Lines: {}",
                text.lines()
                    .filter(|l| l.contains("slider_value"))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            println!("✅ harness_wpf_slider_drag: thumb tracked via SendInput drag");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_slider_drag_holds_modifier() {
    // A foreground drag holds `modifier` keys through SendInput from press to
    // release. The fixture records WPF's Keyboard.Modifiers (live GetKeyState)
    // on each thumb move, and a plain F5 afterwards still matches its
    // unmodified binding, so Ctrl was released rather than latched. The drag
    // grabs the thumb itself, which at value 0 spans from the slider's left
    // edge to the IncreaseLarge track button; a press on the track would only
    // step the value.
    run_foreground_case(
        "slider_drag_modifier",
        Targeting::Px,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let pre = snapshot(driver, pid, wid);
            assert!(
                pre.text().contains("slider_value=0") && pre.text().contains("accel_fired=0"),
                "fixture did not start at slider_value=0 and accel_fired=0"
            );
            let bounds = window_bounds(driver, pid, wid);
            let (x, y, width, height) = pixel_frame(&pre, "sld-value", bounds);
            let (track_x, ..) = pixel_frame(&pre, "IncreaseLarge", bounds);

            let drag = driver.call(
                "drag",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid,
                    "from_x": (x + track_x) / 2.0, "from_y": y + height / 2.0,
                    "to_x": x + width * 0.75, "to_y": y + height / 2.0,
                    "duration_ms": 700, "steps": 40,
                    "modifier": ["ctrl"],
                    "delivery_mode": "foreground"
                }),
            );
            assert!(
                !drag.is_error(),
                "modified foreground drag failed: {}",
                drag.text()
            );
            let deadline = Instant::now() + Duration::from_secs(3);
            loop {
                let post = snapshot(driver, pid, wid);
                let line = fixture_state_line(post.text(), "slider_value=");
                // The suffix appears only once the thumb moves; a value past
                // the first steps shows the thumb followed the pointer.
                let value = line
                    .split("slider_value=")
                    .nth(1)
                    .and_then(|rest| rest.split(' ').next())
                    .and_then(|value| value.parse::<u32>().ok())
                    .unwrap_or(0);
                if value >= 50 && line.contains("modifiers=Control") {
                    println!("drag with ctrl observed: {}", line.trim());
                    break;
                }
                assert!(
                    Instant::now() < deadline,
                    "WPF did not observe a thumb drag with Ctrl: {line}; tool said: {}",
                    drag.text()
                );
                std::thread::sleep(Duration::from_millis(50));
            }

            let key = driver.call(
                "press_key",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "key": "f5",
                    "delivery_mode": "foreground"
                }),
            );
            assert!(!key.is_error(), "post-drag plain F5 failed: {}", key.text());
            std::thread::sleep(Duration::from_millis(300));
            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("accel_fired=1"),
                "plain F5 did not match after the modified drag; Ctrl may be latched: {}",
                snapshot_lines_containing(post.text(), &["accel_fired"])
            );
            println!("✅ harness_wpf_slider_drag_holds_modifier: Ctrl held, then released");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_slider_drag_background_refusal() {
    let case = native_background_case(
        "wpf",
        "slider_drag",
        Targeting::Px,
        DriverRoute::WindowsTargetedInjection,
    )
    .expecting_refusal(vec![RefusalCode::BackgroundUnavailable]);
    run_case(case, |pid, wid, driver| {
        let before = snapshot(driver, pid, wid);
        let before_value = fixture_state_line(before.text(), "slider_value=");
        let (response, mut passed) = observe_background(driver, pid, wid, |driver| {
            driver.call(
                "drag",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid,
                    "from_x": 44.0, "from_y": 304.0,
                    "to_x": 330.0, "to_y": 304.0,
                    "duration_ms": 700, "steps": 40,
                    "delivery_mode": "background"
                }),
            )
        });
        assert!(
            response.is_error(),
            "WPF background drag unexpectedly reported delivery: {}",
            response.text()
        );
        assert_eq!(
            response.structured()["code"].as_str(),
            Some("background_unavailable"),
            "WPF background drag returned the wrong refusal: {}",
            response.text()
        );
        std::thread::sleep(Duration::from_millis(200));
        let after = snapshot(driver, pid, wid);
        assert_eq!(
            fixture_state_line(after.text(), "slider_value="),
            before_value,
            "refused WPF background drag changed the slider value"
        );
        passed.push(OracleKind::FixtureState);
        Observation::refused(
            RefusalCode::BackgroundUnavailable,
            passed,
            response.text(),
            Evidence::default(),
        )
    });
}

#[test]
#[ignore]
fn harness_wpf_slider_drag_foreground_under_topmost_cover_refuses_without_leak() {
    // A foreground drag is coordinate-routed SendInput, so Windows delivers it
    // to whatever window owns the start point. Cover the harness with an
    // always-on-top sentinel: activating the harness cannot bring it above
    // that cover, so the drag must refuse with foreground_unavailable before
    // the button goes down. Previously the z-order-only raise could fail and
    // the whole stroke landed in the cover while the tool reported "Sent drag".
    let mut case = native_foreground_case(
        "wpf",
        "slider_drag_topmost_cover",
        Targeting::Px,
        DriverRoute::WindowsSendInput,
    )
    .expecting_refusal(vec![RefusalCode::ForegroundUnavailable]);
    case.oracles.push(OracleKind::NoLeakedInput);
    case.oracles.sort();
    case.oracles.dedup();
    run_case(case, |pid, wid, driver| {
        let before = snapshot(driver, pid, wid);
        let before_value = fixture_state_line(before.text(), "slider_value=").to_owned();
        let (x, y, width, height) =
            pixel_frame(&before, "sld-value", window_bounds(driver, pid, wid));

        let sentinel = ForegroundSentinel::launch(driver);
        // The sentinel's setup goes through bring_to_front, which leaves it
        // non-topmost. Pin it above every normal window so activation of the
        // harness cannot uncover the slider, and prove the pin took effect.
        let cover = HWND(sentinel.target().native_id as usize as *mut _);
        unsafe {
            SetWindowPos(
                cover,
                Some(HWND_TOPMOST),
                0,
                0,
                0,
                0,
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
            )
            .expect("pin the sentinel above normal windows");
            assert_ne!(
                GetWindowLongPtrW(cover, GWL_EXSTYLE) as u32 & WS_EX_TOPMOST.0,
                0,
                "the sentinel did not become topmost"
            );
        }
        sentinel
            .assert_background_posture(TargetWindow {
                pid,
                native_id: wid,
            })
            .expect("the sentinel must cover the harness before the drag");
        driver.start_behavior_recording();
        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": 700, "steps": 40,
                "delivery_mode": "foreground"
            }),
        );
        // Activating the harness may take focus from the sentinel; that is part
        // of a foreground attempt, so only the leaked-input oracle applies. A
        // silent journal proves nothing unless the sentinel was still alive.
        let (sentinel_passed, violations) = sentinel.observe();
        assert!(
            !violations
                .iter()
                .any(|violation| violation.contains("heartbeat stopped")),
            "the sentinel stopped journaling, so its leak oracle is void: {violations:?}"
        );
        let leaked = violations
            .iter()
            .filter(|violation| violation.contains("received input events"))
            .collect::<Vec<_>>();
        assert!(
            leaked.is_empty(),
            "foreground drag leaked into the covering window: {leaked:?}; tool said: {}",
            response.text()
        );
        assert!(
            response.is_error(),
            "foreground drag under a topmost cover reported delivery: {}",
            response.text()
        );
        assert_eq!(
            response.structured()["code"].as_str(),
            Some("foreground_unavailable"),
            "foreground drag under a topmost cover returned the wrong refusal: {}",
            response.text()
        );

        std::thread::sleep(Duration::from_millis(200));
        let after = snapshot(driver, pid, wid);
        assert_eq!(
            fixture_state_line(after.text(), "slider_value="),
            before_value,
            "refused foreground drag changed the slider value"
        );
        let mut passed = vec![OracleKind::FixtureState];
        if sentinel_passed.contains(&OracleKind::NoLeakedInput) {
            passed.push(OracleKind::NoLeakedInput);
        }
        Observation::refused(
            RefusalCode::ForegroundUnavailable,
            passed,
            response.text(),
            Evidence::default(),
        )
    });
}

#[test]
#[ignore]
fn harness_wpf_slider_increase_large() {
    // Companion to slider_drag — exercises UIA Invoke on the Slider's
    // internal IncreaseLarge "page-up" button. Doesn't depend on screen
    // coords, so it's the more robust slider integration test.
    run_background_case(
        "slider_increase_large",
        DriverRoute::UiaInvoke,
        |pid, wid, driver| {
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "IncreaseLarge")
                .expect("slider IncreaseLarge button not in snapshot");
            for i in 0..3 {
                let resp = driver.call(
                    "click",
                    serde_json::json!({
                        "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx)
                    }),
                );
                println!("invoke IncreaseLarge #{i}: {}", resp.text());
                assert!(
                    !resp.is_error(),
                    "IncreaseLarge invoke failed: {}",
                    resp.text()
                );
                std::thread::sleep(Duration::from_millis(150));
            }
            std::thread::sleep(Duration::from_millis(300));
            let post = snapshot(driver, pid, wid);
            let text = post.text();
            let advanced = text
                .lines()
                .any(|l| l.contains("slider_value=") && !l.contains("slider_value=0\""));
            assert!(
                advanced,
                "slider IncreaseLarge invokes did not advance value. Lines: {}",
                text.lines()
                    .filter(|l| l.contains("slider_value"))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            println!("✅ harness_wpf_slider_increase_large: advanced via UIA Invoke");
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_checkbox_toggle() {
    run_foreground_case(
        "checkbox_toggle",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx =
                ax::element_index_by_id(snap.text(), "chk-agreed").expect("chk-agreed missing");
            // CheckBox exposes UIA TogglePattern (actions=[toggle]), not Invoke.
            // cua-driver's click tool tries UIA Invoke first; for elements that
            // don't support it the PostMessage fallback path runs. Use
            // delivery_mode:"foreground" to land a SendInput click that WPF
            // recognises as a real user click and processes through Toggle.
            let resp = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            println!("click chk-agreed: {}", resp.text());
            std::thread::sleep(Duration::from_millis(400));
            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("agreed=True"),
                "checkbox didn't toggle: {}",
                post.text()
                    .lines()
                    .filter(|l| l.contains("agreed="))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            println!("✅ harness_wpf_checkbox_toggle: agreed=True");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_radio_select() {
    run_foreground_case(
        "radio_select",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx = ax::element_index_by_id(snap.text(), "rdo-high").expect("rdo-high missing");
            // RadioButton exposes SelectionItem pattern (actions=[select]).
            // Same delivery_mode:foreground rationale as the checkbox test.
            let response = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            assert!(
                !response.is_error(),
                "radio select failed: {}",
                response.text()
            );
            std::thread::sleep(Duration::from_millis(400));
            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("prio=High"),
                "radio didn't switch to High"
            );
            println!("✅ harness_wpf_radio_select: prio=High");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_combo_select() {
    run_background_case(
        "combo_select",
        DriverRoute::Composite,
        |pid, wid, driver| {
            let snap = snapshot(driver, pid, wid);
            let combo_idx =
                ax::element_index_by_id(snap.text(), "cbo-color").expect("cbo-color missing");
            // WPF ComboBox UIA peer surfaces ExpandCollapsePattern (actions=[expand])
            // but not ValuePattern — set_value at the parent is a no-op. Standard
            // recipe: invoke the combo to expand the dropdown, re-snapshot so the
            // item AIDs land in the element cache, then click the target item.
            let expand = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(combo_idx),
                    "action": "expand", "delivery_mode": "background"
                }),
            );
            assert!(!expand.is_error(), "combo expand failed: {}", expand.text());
            std::thread::sleep(Duration::from_millis(500));

            let snap2 = snapshot(driver, pid, wid);
            let item_idx = ax::element_index_by_id(snap2.text(), "cbo-item-orange")
                .expect("cbo-item-orange missing after expand");
            let select = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap2.element_token(item_idx),
                    "delivery_mode": "background"
                }),
            );
            assert!(!select.is_error(), "combo select failed: {}", select.text());
            std::thread::sleep(Duration::from_millis(500));

            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("color=orange"),
                "combo didn't switch to orange: {}",
                post.text()
                    .lines()
                    .filter(|l| l.contains("color="))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            println!("✅ harness_wpf_combo_select: color=orange");
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_listbox_select() {
    run_foreground_case(
        "listbox_select",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let snap = snapshot(driver, pid, wid);
            let idx =
                ax::element_index_by_id(snap.text(), "lst-cherry").expect("lst-cherry missing");
            let response = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": snap.element_token(idx),
                    "delivery_mode": "foreground"
                }),
            );
            assert!(
                !response.is_error(),
                "listbox select failed: {}",
                response.text()
            );
            std::thread::sleep(Duration::from_millis(400));
            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("selected=cherry"),
                "list didn't select cherry: {}",
                post.text()
                    .lines()
                    .filter(|l| l.contains("selected="))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            println!("✅ harness_wpf_listbox_select: selected=cherry");
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_modified_click_preserves_selection() {
    run_foreground_case(
        "modified_click_selection",
        Targeting::Ax,
        DriverRoute::WindowsSendInput,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            let first = snapshot(driver, pid, wid);
            let apple =
                ax::element_index_by_id(first.text(), "lst-apple").expect("lst-apple missing");
            let select_apple = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": first.element_token(apple), "delivery_mode": "foreground"
                }),
            );
            assert!(
                !select_apple.is_error(),
                "select apple failed: {}",
                select_apple.text()
            );
            std::thread::sleep(Duration::from_millis(250));

            let second = snapshot(driver, pid, wid);
            let banana =
                ax::element_index_by_id(second.text(), "lst-banana").expect("lst-banana missing");
            let refused_background = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": second.element_token(banana), "modifier": ["ctrl"]
                }),
            );
            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(250));
            let after_refusal = snapshot(driver, pid, wid);
            assert!(
                after_refusal.text().contains("selected=apple"),
                "refused modified click changed the prior selection: {}",
                after_refusal.text()
            );
            let banana = ax::element_index_by_id(after_refusal.text(), "lst-banana")
                .expect("lst-banana missing after refusal");
            let add_banana = driver.call(
                "click",
                serde_json::json!({
                    "pid": pid as i64, "window_id": wid, "element_token": after_refusal.element_token(banana), "delivery_mode": "foreground",
                    "modifier": ["ctrl"]
                }),
            );
            assert!(
                !add_banana.is_error(),
                "modified click failed: {}",
                add_banana.text()
            );
            std::thread::sleep(Duration::from_millis(300));
            let post = snapshot(driver, pid, wid);
            assert!(
                post.text().contains("selected=apple,banana"),
                "modified click replaced or lost the prior selection: {}",
                post.text()
                    .lines()
                    .filter(|line| line.contains("selected="))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            Vec::new()
        },
    );
}

#[test]
#[ignore]
fn harness_wpf_invoke_menu_live_path() {
    run_foreground_case(
        "invoke_menu",
        Targeting::Ax,
        DriverRoute::UiaExpandCollapse,
        Vec::new(),
        |pid, wid, driver| {
            focus_harness(driver, pid, wid);
            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 was not found")),
                "{}",
                refused.raw
            );
            assert!(snapshot(driver, pid, wid)
                .tree_text()
                .contains("menu_action=none"));

            let invoke = driver.call(
                "invoke_menu",
                serde_json::json!({
                    "pid": pid, "window_id": wid,
                    "path": ["Window", "Arrange", "Left"]
                }),
            );
            assert!(
                !invoke.is_error(),
                "Window > Arrange > Left invoke failed: {}",
                invoke.text()
            );
            assert_eq!(invoke.action_effect(), Some("unverifiable"));
            std::thread::sleep(Duration::from_millis(500));

            let post = snapshot(driver, pid, wid);
            assert!(
                post.tree_text().contains("menu_action=window_arrange_left"),
                "Window>Arrange>Left didn't invoke: {}",
                post.tree_text()
                    .lines()
                    .filter(|l| l.contains("menu_action="))
                    .collect::<Vec<_>>()
                    .join(" / ")
            );
            println!("✅ harness_wpf_invoke_menu_live_path: menu_action=window_arrange_left");
            Vec::new()
        },
    );
}