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.

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

//! MCP tool implementations for macOS.

mod bring_to_front;
mod capture_binding;
mod click;
mod clipboard;
mod double_click;
mod drag;
mod get_window_state;
mod hotkey;
mod invoke_menu;
mod kill_app;
mod launch_app;
mod list_apps;
mod list_windows;
mod menu_equivalent;
mod press_key;
mod right_click;
mod scroll;
mod set_value;
mod set_window_frame;
mod type_text;
// `screenshot` / `screenshot_compat` modules removed in PR #1692 —
// `get_window_state` capture_mode:"vision" is the canonical screenshot
// path. The capture functions they wrapped (ScreenCaptureKit, CGWindow,
// etc.) live elsewhere under CuaDriverCore::Capture and are reached
// through GetWindowStateTool.
mod check_permissions;
mod cursor_tools;
mod desktop_pointer_guard;
mod get_accessibility_tree;
mod get_config;
mod get_cursor_position;
mod get_desktop_state;
pub(crate) mod get_screen_size;
mod health_report;
mod move_cursor;
mod page;
mod pixel_route;
pub(crate) mod px_frame;
mod set_config;
mod type_text_chars;
mod zoom;

use cua_driver_core::{
    tool::{Tool, ToolRegistry},
    window_target::{PidOnlyWindowTargetGuard, WindowTargetCandidate, WindowTargetCandidates},
};
use std::collections::HashMap;
use std::sync::Arc;

use crate::{ax::snapshot::Snapshots, cursor::state::CursorRegistry};

fn native_window_id(
    window_id: Option<u64>,
) -> Result<Option<u32>, cua_driver_core::protocol::ToolResult> {
    window_id.map(u32::try_from).transpose().map_err(|_| {
        cua_driver_core::protocol::ToolResult::error("window_id is out of range for macOS.")
    })
}

#[cfg(test)]
mod snapshot_window_id_tests {
    #[test]
    fn native_window_conversion_never_discards_high_bits() {
        assert_eq!(super::native_window_id(None).unwrap(), None);
        assert_eq!(
            super::native_window_id(Some(u32::MAX as u64)).unwrap(),
            Some(u32::MAX)
        );
        assert!(super::native_window_id(Some((1_u64 << 32) | 7)).is_err());
    }
}

fn pid_window_target_candidates(pid: i64) -> Vec<WindowTargetCandidate> {
    let Ok(pid) = i32::try_from(pid) else {
        return Vec::new();
    };
    let enumeration = crate::windows::all_windows_with_space_snapshot();
    let mut windows = enumeration.windows;
    windows.retain(|window| window.pid == pid);
    crate::windows::retain_ax_reachable(&mut windows, enumeration.current_space_id);
    window_target_candidates_for_pid(windows, pid)
}

/// Smallest edge, in points, of a window a pid-only action may mean. Below it
/// the window is a 0x0 or 1x1 helper surface, never a document or dialog.
const MIN_TARGET_EDGE_PT: f64 = 2.0;

/// Whether `window` is a window a pid-only action could mean: on screen and
/// of real size. LibreOffice's off-screen `VCL ImplGetDefaultWindow`, its
/// untitled off-screen helpers, and Chrome's closed omnibox popup are layer-0
/// windows WindowServer lists but no user can see, type into, or click.
fn is_visible_target(window: &crate::windows::WindowInfo) -> bool {
    window.is_on_screen
        && window.bounds.width >= MIN_TARGET_EDGE_PT
        && window.bounds.height >= MIN_TARGET_EDGE_PT
}

fn window_target_candidates_for_pid(
    windows: impl IntoIterator<Item = crate::windows::WindowInfo>,
    pid: i32,
) -> Vec<WindowTargetCandidate> {
    let mut windows: Vec<_> = windows
        .into_iter()
        .filter(|window| window.pid == pid)
        .collect();
    // Only visible windows compete. When none is visible (the app is hidden,
    // its only window is minimized or on another Space) keep them all, so a
    // single real window still resolves and several still refuse.
    if windows.iter().any(is_visible_target) {
        windows.retain(is_visible_target);
    }
    windows
        .into_iter()
        .map(|window| WindowTargetCandidate {
            window_id: u64::from(window.window_id),
            transient_for: None,
            title: window.title,
            app_name: Some(window.app_name),
            is_on_screen: window.is_on_screen,
        })
        .collect()
}

#[cfg(test)]
mod pid_window_target_tests {
    use super::*;
    use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};

    fn window(window_id: u32, pid: i32) -> crate::windows::WindowInfo {
        crate::windows::WindowInfo {
            window_id,
            pid,
            app_name: "Editor".into(),
            title: format!("Document {window_id}"),
            bounds: crate::windows::WindowBounds {
                x: 0.0,
                y: 0.0,
                width: 640.0,
                height: 480.0,
            },
            layer: 0,
            z_index: 1,
            is_on_screen: true,
            current_space_id: None,
            on_current_space: None,
            space_ids: None,
        }
    }

    #[test]
    fn same_pid_sibling_windows_are_ambiguous() {
        let candidates =
            window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);
        assert!(matches!(
            resolve_pid_window_target(candidates),
            PidWindowTargetResolution::Ambiguous(windows)
                if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]
        ));
    }

    fn off_screen(
        mut window: crate::windows::WindowInfo,
        title: &str,
    ) -> crate::windows::WindowInfo {
        window.is_on_screen = false;
        window.title = title.into();
        window
    }

    #[test]
    fn off_screen_helpers_do_not_make_a_document_ambiguous() {
        // LibreOffice: the document plus `VCL ImplGetDefaultWindow` and an
        // untitled helper, both off screen (bench CDB-G03, CDB-S02).
        let candidates = window_target_candidates_for_pid(
            [
                window(1680, 42),
                off_screen(window(1679, 42), "VCL ImplGetDefaultWindow"),
                off_screen(window(1678, 42), ""),
            ],
            42,
        );
        assert!(matches!(
            resolve_pid_window_target(candidates),
            PidWindowTargetResolution::Resolved(window) if window.window_id == 1680
        ));
    }

    #[test]
    fn zero_size_windows_do_not_compete() {
        let mut helper = window(9, 42);
        helper.bounds.width = 0.0;
        helper.bounds.height = 0.0;
        let candidates = window_target_candidates_for_pid([window(7, 42), helper], 42);
        assert!(matches!(
            resolve_pid_window_target(candidates),
            PidWindowTargetResolution::Resolved(window) if window.window_id == 7
        ));
    }

    #[test]
    fn two_visible_documents_stay_ambiguous_despite_helpers() {
        let candidates = window_target_candidates_for_pid(
            [
                window(7, 42),
                window(8, 42),
                off_screen(window(9, 42), "VCL ImplGetDefaultWindow"),
            ],
            42,
        );
        assert!(matches!(
            resolve_pid_window_target(candidates),
            PidWindowTargetResolution::Ambiguous(windows)
                if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]
        ));
    }

    #[test]
    fn an_app_with_no_visible_window_keeps_its_windows() {
        // A hidden app or a minimized single window still resolves.
        let candidates = window_target_candidates_for_pid([off_screen(window(7, 42), "Doc")], 42);
        assert!(matches!(
            resolve_pid_window_target(candidates),
            PidWindowTargetResolution::Resolved(window) if window.window_id == 7
        ));
    }
}

/// The window a pid-only keyboard action means when several visible windows
/// remain: the app's key window (`AXFocusedWindow`), which is where AppKit
/// sends process-scoped key events anyway. `None` leaves the call refused.
fn pid_focused_window(pid: i64) -> Option<u64> {
    let pid = i32::try_from(pid).ok()?;
    crate::ax::bindings::focused_window_id_of_pid(pid).map(|window| u64::from(window.root))
}

fn pid_window_guarded<T: Tool + 'static>(
    tool: T,
    candidates: &WindowTargetCandidates,
) -> Box<dyn Tool> {
    Box::new(PidOnlyWindowTargetGuard::new(
        Box::new(tool),
        candidates.clone(),
    ))
}

/// [`pid_window_guarded`] for keyboard tools: when several visible windows
/// remain, a pid-only key goes to the app's key window, as AppKit would route
/// it, and the result names that window. Without a key window it still refuses.
fn pid_keyboard_guarded<T: Tool + 'static>(
    tool: T,
    candidates: &WindowTargetCandidates,
) -> Box<dyn Tool> {
    Box::new(
        PidOnlyWindowTargetGuard::new(Box::new(tool), candidates.clone())
            .with_fallback_resolver(Arc::new(pid_focused_window)),
    )
}

pub use check_permissions::{
    request_from_launchservices_host as request_permissions_from_launchservices_host,
    PERMISSIONS_HOST_REQUEST_ARG,
};

pub use cua_driver_core::snapshot_store::ZoomContext;
pub(crate) use health_report::current_bundle_identifier as main_bundle_identifier;
pub(crate) use health_report::sw_vers_product_version as macos_product_version;

/// The shared per-call delivery mode; see [`cua_driver_core::delivery`].
///
/// On macOS, `Foreground` briefly fronts the target window, acts, then
/// restores the prior frontmost (see
/// [`crate::input::skylight::with_foreground_assist`]). It is the only way
/// `click` reaches a foreground rung and is orthogonal to addressing
/// (`element_index` vs `x/y`, which selects AX vs pixel).
pub use cua_driver_core::delivery::DeliveryMode;

/// Convert a pure background-input refusal into the structured refusal result
/// shape shared by exact-target tools: `code`, `effect: "refused"`, the
/// requested target, and the safe next route when one exists. No actuator ran.
pub(crate) fn background_refusal_result(
    pid: i32,
    window_id: u32,
    refusal: &cua_driver_core::background_input::BackgroundRefusal,
) -> cua_driver_core::protocol::ToolResult {
    let mut structured = serde_json::json!({
        "code": refusal.code,
        "effect": "refused",
        "pid": pid,
        "window_id": window_id,
        "reason": refusal.reason,
    });
    if let Some(advice) = refusal.advice {
        structured["escalation"] = serde_json::json!({
            "recommended": advice,
            "reason": refusal.reason,
        });
    }
    cua_driver_core::protocol::ToolResult::error(format!(
        "Background input refused ({}): {}",
        refusal.code, refusal.reason
    ))
    .with_structured(structured)
}

/// Structured `element_disabled` refusal: the control reported
/// `AXEnabled=false` immediately before dispatch and nothing was sent.
///
/// Some controls (menu and toolbar items) are disabled only while their app is
/// in the background, so a background call into an app that is not frontmost
/// gets a foreground escalation. Otherwise fronting cannot help.
pub(crate) fn element_disabled_result(
    pid: i32,
    window_id: u32,
    disabled: &crate::input::ax_actions::ElementDisabled,
    foreground: bool,
) -> cua_driver_core::protocol::ToolResult {
    let suggest_foreground = !foreground && crate::apps::frontmost_pid() != Some(pid);
    disabled_refusal(pid, window_id, disabled, suggest_foreground)
}

/// The `element_disabled` refusal for a dispatch error that is an
/// [`crate::input::ax_actions::ElementDisabled`], or `None` for any other error.
pub(crate) fn element_disabled_error(
    pid: i32,
    window_id: u32,
    error: &anyhow::Error,
    foreground: bool,
) -> Option<cua_driver_core::protocol::ToolResult> {
    let disabled = error.downcast_ref::<crate::input::ax_actions::ElementDisabled>()?;
    Some(element_disabled_result(
        pid, window_id, disabled, foreground,
    ))
}

fn disabled_refusal(
    pid: i32,
    window_id: u32,
    disabled: &crate::input::ax_actions::ElementDisabled,
    suggest_foreground: bool,
) -> cua_driver_core::protocol::ToolResult {
    let mut text = disabled.to_string();
    let mut structured = serde_json::json!({
        "code": crate::input::ax_actions::ElementDisabled::CODE,
        "effect": "refused",
        "pid": pid,
        "window_id": window_id,
        "action": disabled.action,
    });
    if suggest_foreground {
        let reason = "the app is in the background, which disables some controls";
        text.push_str(&format!(
            ". If {reason}, retry with delivery_mode:\"foreground\""
        ));
        structured["escalation"] =
            serde_json::json!({ "recommended": "foreground", "reason": reason });
    }
    cua_driver_core::protocol::ToolResult::error(text).with_structured(structured)
}

/// Re-read `AXEnabled` on a token target and refuse a disabled one before any
/// cursor or input work. The snapshot's `enabled` can be stale. A foreground
/// call into an app that is not frontmost skips the read: activation can
/// enable the control, so a read before activation would refuse a live target.
/// Such a caller must read it again after activation, immediately before input.
pub(crate) async fn refuse_if_disabled(
    pid: i32,
    window_id: u32,
    element: &crate::ax::snapshot::RetainedElement,
    action: &'static str,
    foreground: bool,
) -> Option<cua_driver_core::protocol::ToolResult> {
    if foreground && crate::apps::frontmost_pid() != Some(pid) {
        return None;
    }
    let element = element.clone();
    let checked = tokio::task::spawn_blocking(move || {
        crate::input::ax_actions::ensure_ax_action_enabled(element.as_ptr(), action)
    })
    .await
    .ok()?;
    let error = checked.err()?;
    let disabled = error.downcast_ref::<crate::input::ax_actions::ElementDisabled>()?;
    Some(element_disabled_result(
        pid, window_id, disabled, foreground,
    ))
}

/// Hint shown with every `windowserver_connection_invalid` refusal.
pub(crate) const WINDOWSERVER_INVALID_HINT: &str = "This daemon runs without its own app-bundle identity (a bare `cua-driver serve`), so macOS gives it no valid WindowServer connection and every no-raise focus step fails. Run the app-bundle daemon: `cua-driver permissions grant`.";

/// Structured refusal for a background action whose no-raise focus step got
/// `SLPSPostEventRecordTo` status 1002 (invalid connection). Nothing was sent
/// to the target.
pub(crate) fn windowserver_connection_refusal(
    pid: i32,
    window_id: Option<u32>,
) -> cua_driver_core::protocol::ToolResult {
    cua_driver_core::delivery::background_unavailable_result(
        format!(
            "Background input is not available for pid {pid}: the WindowServer connection is \
             invalid (SLPSPostEventRecordTo returned 1002). {WINDOWSERVER_INVALID_HINT}"
        ),
        "background_unavailable",
        "the daemon has no valid WindowServer connection, so no-raise focus cannot work; \
         run the app-bundle daemon, or retry with delivery_mode:\"foreground\".",
        serde_json::json!({
            "reason": "windowserver_connection_invalid",
            "status": crate::input::skylight::WINDOWSERVER_INVALID_CONNECTION,
            "effect": "refused",
            "pid": pid,
            "window_id": window_id,
            "hint": WINDOWSERVER_INVALID_HINT,
        }),
    )
}

/// Exclusive per-process ownership of one background mutation. Callers must
/// keep this value alive through actuator dispatch, focus restoration, and
/// target-bound verification.
/// The window a pid-only call means: the app's focused window, else its
/// frontmost on-screen window. Fills `window_id` for tools that need one
/// when the caller named only the app's pid.
pub(crate) fn default_window_for_pid(args: &mut serde_json::Value) {
    let Some(object) = args.as_object_mut() else {
        return;
    };
    if object
        .get("window_id")
        .is_some_and(|value| !value.is_null())
    {
        return;
    }
    let Some(pid) = object
        .get("pid")
        .and_then(serde_json::Value::as_i64)
        .and_then(|pid| i32::try_from(pid).ok())
    else {
        return;
    };
    let focused = crate::ax::bindings::focused_window_id_of_pid(pid).map(|window| window.root);
    let window_id = focused.or_else(|| {
        crate::windows::all_windows()
            .into_iter()
            .filter(|window| window.pid == pid && window.is_on_screen && window.layer == 0)
            .filter(|window| window.bounds.width >= 2.0 && window.bounds.height >= 2.0)
            .max_by_key(|window| window.z_index)
            .map(|window| window.window_id)
    });
    if let Some(window_id) = window_id {
        object.insert("window_id".into(), serde_json::json!(window_id));
    }
}

pub(crate) struct BackgroundMutationLease {
    pid: i32,
    _guard: tokio::sync::OwnedMutexGuard<()>,
}

impl BackgroundMutationLease {
    /// Revalidate another actuator class while retaining the same per-PID
    /// lease. This supports explicit ladders without deadlocking by attempting
    /// to reacquire the coordinator recursively.
    pub(crate) async fn gate_again(
        &self,
        window_id: u32,
        element_ptr: Option<usize>,
        action: cua_driver_core::background_input::BackgroundAction,
    ) -> Result<(), cua_driver_core::protocol::ToolResult> {
        decide_background_window_action(self.pid, window_id, element_ptr, action).await
    }
}

async fn decide_background_window_action(
    pid: i32,
    window_id: u32,
    element_ptr: Option<usize>,
    action: cua_driver_core::background_input::BackgroundAction,
) -> Result<(), cua_driver_core::protocol::ToolResult> {
    use cua_driver_core::background_input::{
        decide_background_input, BackgroundInputDecision, ExactWindowTarget,
    };
    let element_guard =
        element_ptr.map(|ptr| unsafe { crate::ax::snapshot::RetainedElement::retain(ptr) });
    let facts = match tokio::task::spawn_blocking(move || {
        let element_ptr = element_guard.as_ref().map(|guard| guard.as_ptr());
        crate::ax::exact_target::gather_background_facts(pid, window_id, element_ptr)
    })
    .await
    {
        Ok(facts) => facts,
        Err(error) => {
            return Err(cua_driver_core::protocol::ToolResult::error(format!(
                "Could not gather exact-target facts for pid {pid} window {window_id}: {error}"
            )));
        }
    };
    match decide_background_input(ExactWindowTarget { pid, window_id }, &facts, action) {
        BackgroundInputDecision::Execute { .. } => Ok(()),
        BackgroundInputDecision::Refuse(refusal) => {
            Err(background_refusal_result(pid, window_id, &refusal))
        }
    }
}

/// The keyboard action class for a window-addressed background key or text
/// request. When the focus-record transport exists the exact window is made
/// the app's key window for the duration of the post (see
/// [`post_keys_to_window`]), so a second same-pid window is not ambiguous.
/// Without it the caller's fail-closed `generic` class applies.
pub(crate) fn window_keyboard_action(
    generic: cua_driver_core::background_input::BackgroundAction,
) -> cua_driver_core::background_input::BackgroundAction {
    if crate::input::skylight::is_focus_without_raise_available() {
        cua_driver_core::background_input::BackgroundAction::ExactWindowKeys
    } else {
        generic
    }
}

/// Make `window_id` the app's key window, confirmed, for pid-routed keys.
/// `Ok(None)` when no window is addressed or the SPIs are missing (keys go
/// where they always did). `Err` carries the refusal text: no key may be
/// posted, it could reach a sibling window.
pub(crate) fn key_scope(
    pid: i32,
    window_id: Option<u32>,
) -> Result<Option<crate::input::skylight::WindowKeyScope>, String> {
    match window_id {
        Some(wid) if crate::input::skylight::is_focus_without_raise_available() => {
            crate::input::skylight::enter_exact_window_key(pid as libc::pid_t, wid).map(Some)
        }
        _ => Ok(None),
    }
}

/// [`key_scope`] for an async tool: runs the blocking prime off the runtime and
/// turns an unconfirmed key window into the structured `window_not_key`
/// refusal. Foreground requests and pid-only calls hold no scope.
pub(crate) async fn acquire_key_scope(
    pid: i32,
    window_id: Option<u32>,
    foreground: bool,
) -> Result<Option<crate::input::skylight::WindowKeyScope>, cua_driver_core::protocol::ToolResult> {
    let Some(wid) = window_id.filter(|_| !foreground) else {
        return Ok(None);
    };
    match tokio::task::spawn_blocking(move || key_scope(pid, Some(wid))).await {
        Ok(Ok(scope)) => Ok(scope),
        Ok(Err(_)) if crate::input::skylight::windowserver_connection_invalid() => {
            Err(windowserver_connection_refusal(pid, Some(wid)))
        }
        Ok(Err(reason)) => Err(background_refusal_result(
            pid,
            wid,
            &cua_driver_core::background_input::BackgroundRefusal {
                code: WINDOW_NOT_KEY,
                reason,
                advice: Some("foreground"),
            },
        )),
        Err(error) => Err(cua_driver_core::protocol::ToolResult::error(format!(
            "Could not prepare the key window for pid {pid}: {error}"
        ))),
    }
}

/// Refusal code when the addressed window cannot be confirmed as the app's
/// key window: no key is sent, none could be proven to reach it.
pub(crate) const WINDOW_NOT_KEY: &str = "window_not_key";

/// Acquire the per-PID mutation coordinator, gather fresh exact-target facts,
/// and ask the pure core for one background decision. `element_ptr` must stay
/// retained by the caller until the returned lease is dropped.
pub(crate) async fn gate_background_window_action(
    pid: i32,
    window_id: u32,
    element_ptr: Option<usize>,
    action: cua_driver_core::background_input::BackgroundAction,
) -> Result<BackgroundMutationLease, cua_driver_core::protocol::ToolResult> {
    let lease = acquire_background_mutation(pid).await;
    lease.gate_again(window_id, element_ptr, action).await?;
    Ok(lease)
}

pub(crate) async fn acquire_background_mutation(pid: i32) -> BackgroundMutationLease {
    BackgroundMutationLease {
        pid,
        _guard: crate::background_mutation::acquire(pid).await,
    }
}

/// Finish the post-action observation window and release the wildcard
/// focus-steal lease. The observation bound is a daemon-launch setting
/// (`CUA_DRIVER_WINDOW_CHANGE_TIMEOUT_MS` / `CUA_DRIVER_WINDOW_CHANGE_POLL_MS`),
/// never a per-call argument: every ingress strips `_`-prefixed arguments, so
/// a tool call cannot shorten focus protection for itself.
pub(crate) async fn finish_window_observation(
    snapshot: crate::window_change_detector::Snapshot,
) -> crate::window_change_detector::Changes {
    snapshot.detect_async().await
}

/// px-focus for the keyboard family (type_text / press_key / hotkey): focus the
/// element at (x,y) before a keystroke — the *element px action* form of a
/// keyboard tool. When the exact window's focused element already covers the
/// point, nothing is clicked, so a Cmd+A selection survives a follow-up
/// type_text or Cmd+V. Otherwise prefer non-destructive AX focus; the
/// foreground rung falls back to a real pixel click when needed.
/// Reuses ClickTool's exact coordinate translation and delivery mode.
/// `Ok(())` on success; `Err(ToolResult)` short-circuits the caller.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn focus_by_pixel(
    state: &Arc<ToolState>,
    pid: i32,
    window_id: Option<u32>,
    x: f64,
    y: f64,
    foreground: bool,
    session: Option<String>,
    session_id: Option<String>,
    from_zoom: bool,
    mutation_lease: Option<&BackgroundMutationLease>,
) -> Result<(), cua_driver_core::protocol::ToolResult> {
    use cua_driver_core::tool::Tool;
    let mut click_args = serde_json::json!({
        "pid": pid, "x": x, "y": y,
        "delivery_mode": "background",
        "action": "focus",
    });
    if let Some(wid) = window_id {
        click_args["window_id"] = serde_json::json!(wid);
        if let Some(lease) = mutation_lease {
            lease
                .gate_again(
                    wid,
                    None,
                    cua_driver_core::background_input::BackgroundAction::WindowPointer,
                )
                .await?;
        }
    }
    // The requested field may already hold keyboard focus, for example after
    // a pixel hotkey Cmd+A. Any focus action is then redundant, and the real
    // click fallback would be destructive: Chromium's omnibox hit-tests to an
    // enclosing AXGroup that rejects AXFocused, so the fallback click moved
    // the caret and dropped the selection (#4125).
    if focused_element_holds_point(pid, window_id, x, y, true).await {
        return Ok(());
    }
    if let Some(ref s) = session {
        click_args["session"] = serde_json::json!(s);
    }
    if let Some(ref s) = session_id {
        click_args["_session_id"] = serde_json::json!(s);
    }
    if from_zoom {
        click_args["from_zoom"] = serde_json::json!(true);
    }
    let click_tool = click::ClickTool::new(state.clone());
    let click = click_tool.invoke(click_args);
    let focus = if let Some(lease) = mutation_lease {
        crate::background_mutation::with_held_lease(lease.pid, click).await
    } else {
        click.await
    };
    if focus.is_error != Some(true) {
        // AXFocused is non-destructive: unlike a second real click, it keeps a
        // Cmd+A selection intact before a follow-up type_text or Cmd+V.
        tokio::time::sleep(std::time::Duration::from_millis(120)).await;
        // A background focus-click is `effect:"unverifiable"` by construction:
        // it cannot prove the renderer moved its first responder. Returning on
        // "it didn't error" therefore skipped the real-click fallback below
        // whenever the click was a silent no-op — advancing on transport
        // success alone, which is exactly what the ladder forbids. Confirm the
        // focus actually moved before claiming this rung worked.
        if !foreground || pixel_focus_landed(pid, window_id, x, y).await {
            return Ok(());
        }
    } else if !foreground {
        return Err(cua_driver_core::protocol::ToolResult::error(format!(
            "focus pixel-click at ({x:.0},{y:.0}) failed."
        )));
    }

    // Some renderer surfaces do not expose a usable AX focus action. The
    // explicit foreground rung retains its real-click fallback for them.
    let mut click_args = serde_json::json!({
        "pid": pid, "x": x, "y": y,
        "delivery_mode": "foreground",
        "action": "press",
    });
    if let Some(wid) = window_id {
        click_args["window_id"] = serde_json::json!(wid);
    }
    if let Some(ref s) = session {
        click_args["session"] = serde_json::json!(s);
    }
    if let Some(ref s) = session_id {
        click_args["_session_id"] = serde_json::json!(s);
    }
    if from_zoom {
        click_args["from_zoom"] = serde_json::json!(true);
    }
    let focus = click::ClickTool::new(state.clone())
        .invoke(click_args)
        .await;
    if focus.is_error == Some(true) {
        return Err(cua_driver_core::protocol::ToolResult::error(format!(
            "focus pixel-click at ({x:.0},{y:.0}) failed."
        )));
    }
    // Brief settle so the renderer registers focus before the keystrokes.
    tokio::time::sleep(std::time::Duration::from_millis(120)).await;
    Ok(())
}

/// Confirm that a focus pixel-click actually moved the application's focused
/// element onto the clicked point.
///
/// The background focus-click reports `effect:"unverifiable"`, so this is the
/// read-back that lets [`focus_by_pixel`] decide whether the cheap rung worked
/// or the real-click fallback is still required. It reuses the same
/// window-local-pixels → screen translation the click itself used, so the
/// comparison is in one coordinate space.
///
/// Returns `false` whenever the answer cannot be established (no window id,
/// untranslatable frame, unreadable focused element or rect). That is the
/// conservative direction: an unprovable focus escalates to the stronger rung
/// rather than being reported as success.
async fn pixel_focus_landed(pid: i32, window_id: Option<u32>, x: f64, y: f64) -> bool {
    focused_element_holds_point(pid, window_id, x, y, false).await
}

/// Whether the application's focused element covers the window-local pixel
/// `(x, y)` of `window_id`. With `require_window`, the focused element must
/// also belong to that exact window, so focus held by a same-process sibling
/// window that overlaps the point never counts as the requested target.
/// Unprovable answers are `false`.
async fn focused_element_holds_point(
    pid: i32,
    window_id: Option<u32>,
    x: f64,
    y: f64,
    require_window: bool,
) -> bool {
    let Some(wid) = window_id else {
        return false;
    };
    tokio::task::spawn_blocking(move || {
        let Ok(frame) = px_frame::resolve_window_px_frame(wid) else {
            return false;
        };
        let (screen_x, screen_y, _, _) = frame.to_screen(x, y);
        unsafe {
            let Some(focused) = crate::ax::bindings::focused_element_of_pid(pid) else {
                return false;
            };
            let rect = crate::ax::bindings::element_screen_rect(focused);
            let in_window = !require_window
                || crate::ax::exact_target::element_window_id(focused)
                    .is_some_and(|window| window.is(wid));
            core_foundation::base::CFRelease(focused as core_foundation::base::CFTypeRef);
            let Some(rect) = rect else {
                return false;
            };
            in_window && point_within_rect(rect, screen_x, screen_y)
        }
    })
    .await
    .unwrap_or(false)
}

/// Whether `[x, y, width, height]` (screen coordinates, top-left origin)
/// contains the point. A degenerate rect never contains anything, so an app
/// reporting a zero-sized focused element escalates rather than false-confirms.
fn point_within_rect([rx, ry, rw, rh]: [f64; 4], x: f64, y: f64) -> bool {
    rw > 0.0 && rh > 0.0 && x >= rx && x < rx + rw && y >= ry && y < ry + rh
}

/// Default long-edge cap for screenshots; see [`DriverConfig::max_image_dimension`].
pub const DEFAULT_MAX_IMAGE_DIMENSION: u32 = 1366;

/// Runtime-mutable driver configuration persisted across calls within a session.
pub struct DriverConfig {
    /// Max screenshot dimension (0 = no limit). Applied during screenshot/zoom:
    /// the long edge is downscaled to this before encoding.
    ///
    /// Default 1366. High-resolution Claude models read images up to 2576 px
    /// at ~w*h/750 tokens each, so a 1568x882 capture costs ~1.8k tokens and a
    /// 1366x768 one ~1.4k; Anthropic's computer-use guidance names 1366x768 as
    /// a lower-cost size with strong performance. Callers that need more
    /// detail use `zoom` or a per-call/session `max_image_dimension`.
    pub max_image_dimension: u32,
}

impl Default for DriverConfig {
    fn default() -> Self {
        Self {
            max_image_dimension: DEFAULT_MAX_IMAGE_DIMENSION,
        }
    }
}

/// Path to the persistent JSON config file shared by the CLI and MCP session.
pub fn config_file_path() -> std::path::PathBuf {
    let home = std::env::var("HOME").unwrap_or_default();
    std::path::PathBuf::from(format!("{home}/.cua-driver/config.json"))
}

/// Load `DriverConfig` from `~/.cua-driver/config.json`, falling back to
/// defaults for any missing or unrecognised keys.  Called at MCP startup so
/// that `cua-driver config set capture_mode vision` (CLI) carries over into
/// the next MCP session without requiring a per-call `set_config`.
pub fn load_driver_config() -> DriverConfig {
    let mut cfg = DriverConfig::default();
    let path = config_file_path();
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(_) => return cfg, // no file yet — use defaults
    };
    let json: serde_json::Value = match serde_json::from_str(&text) {
        Ok(v) => v,
        Err(_) => return cfg, // malformed file — use defaults
    };
    // `capture_mode` is per-call now; old on-disk `capture_mode` and
    // `capture_scope` keys are intentionally inert.
    if let Some(v) = json.get("max_image_dimension").and_then(|v| v.as_u64()) {
        if let Ok(v32) = u32::try_from(v) {
            cfg.max_image_dimension = v32;
        }
    }
    cfg
}

/// Convert native pixels from `get_desktop_state` into logical points.
pub fn desktop_screenshot_point(x: f64, y: f64) -> (f64, f64) {
    let ratio = get_screen_size::main_screen_size().map_or(1.0, |(_, _, s)| s);
    (x / ratio, y / ratio)
}

/// Persist a single key/value pair to `~/.cua-driver/config.json`.
/// Merges with any existing file contents so other keys are preserved.
/// Returns `Err` if the directory cannot be created or the file cannot be written.
pub fn write_driver_config_key(key: &str, value: &serde_json::Value) -> Result<(), String> {
    let path = config_file_path();
    let mut json: serde_json::Value = path
        .exists()
        .then(|| std::fs::read_to_string(&path).ok())
        .flatten()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or_else(|| serde_json::json!({}));
    json[key] = value.clone();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let body = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
    std::fs::write(&path, body).map_err(|e| e.to_string())?;
    Ok(())
}

/// Per-session config overrides layered over the global persisted `DriverConfig`.
///
/// The cua-driver daemon is one shared process: every `cua-driver mcp` proxy
/// connects to it and shares its `ToolState`. `DriverConfig` is therefore
/// multi-tenant AND persisted to disk — so without session scoping, session A's
/// `set_config capture_mode=vision` clobbers session B's value and flips the
/// on-disk default under everyone. These overrides fix that: a named MCP session
/// gets an in-memory, non-persisted override keyed by its `_session_id`; the
/// anonymous session (CLI / one-shot `call`) still writes the shared global +
/// disk. `None` fields mean "fall through to the global layer".
#[derive(Clone, Default)]
pub struct ConfigOverrides {
    pub max_image_dimension: Option<u32>,
}

/// Thread-safe map of `session_id` → `ConfigOverrides`, mirroring
/// `CursorRegistry`'s registry shape. Cleared per session on `session_end`.
pub struct SessionConfigRegistry {
    inner: std::sync::Mutex<HashMap<String, ConfigOverrides>>,
}

impl SessionConfigRegistry {
    pub fn new() -> Self {
        Self {
            inner: std::sync::Mutex::new(HashMap::new()),
        }
    }

    /// Merge `delta` into `session`'s overrides (only the `Some` fields of
    /// `delta` overwrite; existing overrides for unset fields are preserved).
    pub fn set(&self, session: &str, delta: ConfigOverrides) {
        // Write-boundary resurrection guard: keyed by session_id, so an
        // in-flight set_config that lands AFTER session_end (passed the dispatch
        // gate, then the proxy died and the reaper cleared this session's
        // overrides) must NOT re-create the entry — it would be invisible and
        // never reaped again. `fire_session_end` marks ENDED_SESSIONS *before*
        // running the config-clear hook, so this check is authoritative.
        if cua_driver_core::session::is_session_ended(session) {
            return;
        }
        let mut map = self.inner.lock().unwrap();
        let entry = map.entry(session.to_owned()).or_default();
        if delta.max_image_dimension.is_some() {
            entry.max_image_dimension = delta.max_image_dimension;
        }
    }

    /// Resolve the effective `max_image_dimension` for `session`, layering its
    /// override over the global `DriverConfig`. `session = None` (anonymous)
    /// returns the global value verbatim.
    pub fn effective_max_image_dimension(
        &self,
        session: Option<&str>,
        global: &DriverConfig,
    ) -> u32 {
        let ov = session.and_then(|s| self.inner.lock().unwrap().get(s).cloned());
        match ov {
            Some(ov) => ov.max_image_dimension.unwrap_or(global.max_image_dimension),
            None => global.max_image_dimension,
        }
    }

    /// Drop `session`'s overrides. No-op for an unknown id (so `session_end`
    /// for an anonymous / never-set session is harmless).
    pub fn clear(&self, session: &str) {
        self.inner.lock().unwrap().remove(session);
    }
}

impl Default for SessionConfigRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Shared state passed to all tools.
pub struct ToolState {
    pub snapshots: Arc<Snapshots>,
    pub cursor_registry: Arc<CursorRegistry>,
    pub(crate) capture_bindings: Arc<capture_binding::MacCaptureBindings>,
    /// Global, disk-persisted config — the base layer and the only one the
    /// anonymous session / CLI writes.
    pub config: Arc<std::sync::RwLock<DriverConfig>>,
    /// Per-MCP-session in-memory config overrides layered over `config`.
    pub session_config: Arc<SessionConfigRegistry>,
    /// Open CDP connections, one per port, reused across `insert_text` /
    /// `type_keystrokes` calls instead of reconnecting fresh every time —
    /// see `CdpSessionCache` for why (Chrome's "allow remote debugging"
    /// popup fires on every new connection, not once per session).
    pub cdp_sessions: Arc<crate::browser::CdpSessionCache>,
    /// Whether the runtime owner installed the AppKit main-thread cursor
    /// overlay facility. Imported SDK runtimes deliberately leave this false;
    /// explicit cursor-overlay methods must refuse instead of reporting a
    /// successful no-op.
    pub cursor_overlay_available: bool,
    /// Direct and embedded hosts own TCC request UX. Their runtime may inspect
    /// permission state but must not raise Cua-owned prompts.
    pub host_owns_permission_ux: bool,
    /// Advisory host identity for permission diagnostics only.
    pub host_bundle_id: Option<String>,
}

impl Default for ToolState {
    fn default() -> Self {
        Self::new(false, false, None)
    }
}

impl ToolState {
    fn new(
        cursor_overlay_available: bool,
        host_owns_permission_ux: bool,
        host_bundle_id: Option<String>,
    ) -> Self {
        Self::new_with_capture_service(
            Arc::new(cua_driver_core::capture_runtime::CaptureService::default()),
            cursor_overlay_available,
            host_owns_permission_ux,
            host_bundle_id,
        )
    }

    fn new_with_capture_service(
        capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,
        cursor_overlay_available: bool,
        host_owns_permission_ux: bool,
        host_bundle_id: Option<String>,
    ) -> Self {
        Self {
            snapshots: Arc::new(Snapshots::new()),
            cursor_registry: Arc::new(CursorRegistry::new()),
            capture_bindings: Arc::new(capture_binding::MacCaptureBindings::new(capture_service)),
            // Load persisted config from ~/.cua-driver/config.json so that
            // `cua-driver config set` changes carry over into MCP sessions.
            config: Arc::new(std::sync::RwLock::new(load_driver_config())),
            session_config: Arc::new(SessionConfigRegistry::new()),
            cdp_sessions: Arc::new(crate::browser::CdpSessionCache::new()),
            cursor_overlay_available,
            host_owns_permission_ux,
            host_bundle_id,
        }
    }
}

/// The target pid of an element-addressable call. An explicit `pid` wins; a
/// call that carries only an `element_token` takes the pid the token was
/// minted for, as the schemas promise ("the token carries it").
pub(super) fn target_pid(
    state: &ToolState,
    args: &serde_json::Value,
) -> Result<i32, cua_driver_core::protocol::ToolResult> {
    use cua_driver_core::tool_args::ArgsExt;
    if args.get("pid").is_some_and(|pid| !pid.is_null()) {
        return args.require_i32("pid");
    }
    if let Some(pid) = state.snapshots.pid_for_token(args) {
        return Ok(pid);
    }
    if args
        .get("element_token")
        .is_some_and(|token| !token.is_null())
    {
        // The token is gone, but a recently retired snapshot still says whose
        // it was, so the refusal can name what is current for that process.
        return Err(cua_driver_core::element_token::stale_token_without_pid(
            state.snapshots.token_owner(args),
        ));
    }
    Err(cua_driver_core::protocol::ToolResult::error(
        "Missing required integer field: pid. Pass pid, or pass an element_token from the \
         current get_window_state (a token names its own pid).",
    ))
}

pub(super) fn screenshot_scale(
    state: &ToolState,
    args: &serde_json::Value,
    pid: i32,
    window_id: Option<u32>,
) -> Result<f64, cua_driver_core::protocol::ToolResult> {
    state
        .snapshots
        .screenshot_scale(pid, window_id.map(u64::from), args)
}

pub(super) fn zoom_context(
    state: &ToolState,
    args: &serde_json::Value,
    pid: i32,
    window_id: Option<u32>,
) -> Result<ZoomContext, cua_driver_core::protocol::ToolResult> {
    state.snapshots.zoom(
        pid,
        window_id.map(u64::from),
        args.get("_session_id").and_then(serde_json::Value::as_str),
    )
}

pub(crate) fn cursor_overlay_unavailable() -> cua_driver_core::protocol::ToolResult {
    let message = "macOS agent cursor overlay is unavailable: this runtime owner has no certified \
                   AppKit main-thread host adapter or no Window Server graphic-session access; \
                   use a GUI private worker or standalone service for cursor-overlay controls";
    cua_driver_core::protocol::ToolResult::error(message).with_structured(serde_json::json!({
        "status": "refused",
        "refusal": {
            "code": "facility_unavailable",
            "facility": "macos_cursor_overlay",
            "message": message,
        }
    }))
}

/// Register all macOS tools into the registry. `compat` is retained for
/// launch compatibility but currently has no effect on the tool surface.
pub fn register_all(
    registry: &mut ToolRegistry,
    compat: bool,
    cursor_overlay_available: bool,
    host_owns_permission_ux: bool,
    host_bundle_id: Option<String>,
) {
    let state = Arc::new(ToolState::new_with_capture_service(
        registry.capture_service(),
        cursor_overlay_available,
        host_owns_permission_ux,
        host_bundle_id,
    ));
    let cursor_outcome_reader = {
        let cursor_registry = state.cursor_registry.clone();
        cua_driver_core::session::register_scoped_cursor_outcome_reader(std::sync::Arc::new(
            move |session_id| {
                let state = cursor_registry.get(session_id);
                let motion_customized = state.is_some()
                    && crate::cursor::overlay::current_motion(session_id)
                        != cursor_overlay::MotionConfig::default();
                let active_cursor_count = cursor_registry
                    .all_states()
                    .iter()
                    .filter(|state| state.config.cursor_id != "default")
                    .count()
                    .max(1);
                match state {
                    Some(state) => cua_driver_core::session::bounded_cursor_outcome(
                        true,
                        state.config.enabled,
                        crate::cursor::overlay::is_visible_for_session(session_id),
                        Some(state.config.theme_id.as_str()),
                        motion_customized,
                        active_cursor_count,
                    ),
                    None => cua_driver_core::session::bounded_cursor_outcome(
                        false,
                        false,
                        false,
                        None,
                        false,
                        active_cursor_count,
                    ),
                }
            },
        ))
    };
    registry.retain_cursor_outcome_reader(cursor_outcome_reader);
    if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {
        let prefix = format!("__cua_runtime_{runtime_scope}:");
        let cursor_registry = state.cursor_registry.clone();
        let capture_bindings = state.capture_bindings.clone();
        registry.retain_runtime_cleanup(move || {
            capture_bindings.retire_runtime();
            for cursor in cursor_registry
                .all_states()
                .into_iter()
                .filter(|cursor| cursor.config.cursor_id.starts_with(&prefix))
            {
                cursor_registry.remove(&cursor.config.cursor_id);
                crate::cursor::overlay::remove_cursor(cursor.config.cursor_id);
            }
        });
    }
    // Share the element cache with the recording-hook layer so it can
    // resolve element_index → window-local screenshot coords for click.png.
    cua_driver_core::snapshot_store::register_runtime_store(&state.snapshots);
    crate::recording_hooks::install();

    // Drop a disconnecting session's config overrides + owned cursor on
    // `session_end`. The daemon fans the session id out to this hook;
    // recording ownership is handled separately on the core RecordingSession.
    {
        let session_config = state.session_config.clone();
        let snapshots = state.snapshots.clone();
        let cursor_registry = state.cursor_registry.clone();
        let capture_bindings = state.capture_bindings.clone();
        let registration =
            cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {
                session_config.clear(session_id);
                snapshots.retire_session_screenshots(session_id);
                capture_bindings.retire_session(session_id);
                // Per-session agent cursor: the session_id is the cursor key when
                // the caller gave no explicit cursor_id, so dropping it here both
                // prunes the metadata registry and stops the overlay painting that
                // session's cursor. Both paths guard "default" so the anonymous /
                // one-shot cursor survives. Anonymous sessions that never created a
                // cursor are a harmless no-op.
                cursor_registry.remove(session_id);
                crate::cursor::overlay::remove_cursor(session_id.to_owned());
            });
        registry.retain_session_end_hook(registration);
        let revive_registration =
            cua_driver_core::session::register_scoped_session_revive_hook(move |session_id| {
                crate::cursor::overlay::revive_cursor(session_id.to_owned());
            });
        registry.retain_session_revive_hook(revive_registration);
    }

    registry.register(Box::new(list_apps::ListAppsTool));
    registry.register(Box::new(list_windows::ListWindowsTool));
    registry.register(Box::new(get_window_state::GetWindowStateTool::new(
        state.clone(),
    )));
    registry.register(Box::new(
        cua_driver_core::expectation::VerifyStateTool::new(Arc::new(
            cua_driver_core::expectation::ToolObservationProvider::new(
                Arc::new(list_windows::ListWindowsTool),
                Arc::new(get_window_state::GetWindowStateTool::new(state.clone())),
            ),
        )),
    ));
    registry.register(Box::new(launch_app::LaunchAppTool));
    registry.register(Box::new(kill_app::KillAppTool));
    let pid_window_candidates: WindowTargetCandidates = Arc::new(pid_window_target_candidates);
    registry.register(pid_window_guarded(
        bring_to_front::BringToFrontTool,
        &pid_window_candidates,
    ));
    registry.register(Box::new(set_window_frame::SetWindowFrameTool));
    registry.register(Box::new(invoke_menu::InvokeMenuTool));
    registry.register(pid_window_guarded(
        click::ClickTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_window_guarded(
        double_click::DoubleClickTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_window_guarded(
        right_click::RightClickTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_window_guarded(
        drag::DragTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_keyboard_guarded(
        type_text::TypeTextTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_keyboard_guarded(
        press_key::PressKeyTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_keyboard_guarded(
        hotkey::HotkeyTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_window_guarded(
        set_value::SetValueTool::new(state.clone()),
        &pid_window_candidates,
    ));
    registry.register(pid_window_guarded(
        scroll::ScrollTool::new(state.clone()),
        &pid_window_candidates,
    ));
    cua_driver_core::clipboard::register_clipboard_tools(
        registry,
        Arc::new(clipboard::MacosClipboard::new()),
    );
    // The standalone `screenshot` tool was removed in #1692. Window capture
    // now comes from `get_window_state` (tree plus screenshot by default), while
    // `get_desktop_state` handles explicit full-display capture. `capture_mode`
    // is deprecated and ignored. `compat` no longer gates a tool swap here.
    let _ = compat;
    registry.register(Box::new(get_screen_size::GetScreenSizeTool));
    registry.register(Box::new(get_desktop_state::GetDesktopStateTool::new(
        state.clone(),
    )));
    registry.register(Box::new(get_cursor_position::GetCursorPositionTool));
    registry.register(Box::new(move_cursor::MoveCursorTool::new(state.clone())));
    registry.register(Box::new(cursor_tools::SetAgentCursorEnabledTool::new(
        state.clone(),
    )));
    registry.register(Box::new(cursor_tools::SetAgentCursorMotionTool::new(
        state.clone(),
    )));
    registry.register(Box::new(cursor_tools::SetAgentCursorThemeTool::new(
        state.clone(),
    )));
    registry.register(Box::new(cursor_tools::GetAgentCursorStateTool::new(
        state.clone(),
    )));
    registry.register(Box::new(check_permissions::CheckPermissionsTool::new(
        state.clone(),
    )));
    // `health_report` — single-call end-to-end diagnostics. Stable
    // schema_version="1" contract aimed at downstream consumers who must
    // not have to know cua-driver internals. Provider is platform-specific; tool plumbing is in
    // `cua_driver_core::health_report`.
    registry.register(Box::new(
        cua_driver_core::health_report::HealthReportTool::new(Arc::new(
            health_report::MacosHealthProvider,
        )),
    ));
    registry.register(Box::new(get_config::GetConfigTool::new(state.clone())));
    registry.register(Box::new(set_config::SetConfigTool::new(state.clone())));
    registry.register(Box::new(
        get_accessibility_tree::GetAccessibilityTreeTool::new(state.clone()),
    ));
    registry.register(Box::new(zoom::ZoomTool {
        state: state.clone(),
    }));
    // `type_text_chars` is intentionally NOT registered — Swift treats it as
    // a deprecated alias for `type_text` resolved at invoke time in
    // mcp-server's `ToolRegistry::invoke`. Keeping it out of the registry
    // means it doesn't show up in `tools/list` either, matching Swift's
    // ToolRegistry.swift (`type_text_chars` not in `handlers`) and the
    // platform-windows::build_registry which uses the same convention.
    // Touch the struct so it stays in this crate for the alias resolver.
    let _: &type_text_chars::TypeTextCharsTool =
        &type_text_chars::TypeTextCharsTool::new(state.clone());
    // Cross-platform `page` tool definition lives in mcp-server; macOS plugs in
    // its Apple-Events / CDP / AX-tree backend here.
    registry.register(Box::new(cua_driver_core::page::PageTool::new(Arc::new(
        page::MacOsPageBackend::new(state.clone()),
    ))));
    let browser_engine = cua_driver_core::browser::BrowserEngine::new_with_runtime_services(
        Arc::new(crate::browser::MacOsBrowserPlatform::new(
            state.cursor_registry.clone(),
        )),
        registry.approval_broker(),
        registry.protected_resource_ownership(),
    );
    cua_driver_core::browser::register_browser_tools(&browser_engine, registry);
    // Recording / replay + session-lifecycle tools are platform-independent.
    registry.register_recording_tools();
    registry.register_session_tools();
}

#[cfg(test)]
mod registry_surface_tests {
    use super::*;

    fn names(compat: bool) -> Vec<String> {
        let mut registry = ToolRegistry::new();
        register_all(&mut registry, compat, false, false, None);
        registry.tool_names().map(str::to_owned).collect()
    }

    #[test]
    fn default_and_legacy_compat_surfaces_have_no_screenshot_tool() {
        let default = names(false);
        let compat = names(true);
        assert!(!default.iter().any(|name| name == "screenshot"));
        assert!(!compat.iter().any(|name| name == "screenshot"));
        assert_eq!(
            default, compat,
            "legacy compat flag must remain surface-neutral"
        );
    }
}

#[cfg(test)]
mod session_config_guard_tests {
    use super::*;
    use cua_driver_core::session::fire_session_end;

    fn overrides(max_dim: u32) -> ConfigOverrides {
        ConfigOverrides {
            max_image_dimension: Some(max_dim),
        }
    }

    #[test]
    fn ended_session_config_set_is_noop() {
        // THE FIX (config side): an ended session id keys the overrides map, so
        // an in-flight set_config after session_end must not re-create the entry
        // the reaper's clear hook removed. effective then falls back to global.
        let reg = SessionConfigRegistry::new();
        let global = DriverConfig::default();
        let sid = "wb-config-ended-Q9R8S7";
        fire_session_end(sid);
        assert!(cua_driver_core::session::is_session_ended(sid));

        reg.set(sid, overrides(800));
        let dim = reg.effective_max_image_dimension(Some(sid), &global);
        assert_eq!(
            dim, global.max_image_dimension,
            "ended session must not get an override entry"
        );
    }

    #[test]
    fn live_session_config_set_takes_effect() {
        let reg = SessionConfigRegistry::new();
        let global = DriverConfig::default();
        let sid = "wb-config-live-T1U2V3";
        assert!(!cua_driver_core::session::is_session_ended(sid));
        reg.set(sid, overrides(800));
        let dim = reg.effective_max_image_dimension(Some(sid), &global);
        assert_eq!(dim, 800, "live session override must apply");
    }
}

#[cfg(test)]
mod cursor_overlay_facility_tests {
    use super::*;
    use cua_driver_core::tool::Tool;

    fn assert_facility_unavailable(result: cua_driver_core::protocol::ToolResult) {
        assert_eq!(result.is_error, Some(true));
        let refusal = result
            .structured_content
            .and_then(|value| value.get("refusal").cloned())
            .expect("structured refusal");
        assert_eq!(refusal["code"], "facility_unavailable");
        assert_eq!(refusal["facility"], "macos_cursor_overlay");
    }

    #[tokio::test]
    async fn cursor_control_refuses_without_main_thread_host_facility() {
        let state = Arc::new(ToolState::new(false, true, None));
        let result = cursor_tools::SetAgentCursorEnabledTool::new(state)
            .invoke(serde_json::json!({"enabled": true, "session": "test"}))
            .await;
        assert_facility_unavailable(result);
    }

    #[tokio::test]
    async fn window_cursor_move_refuses_without_main_thread_host_facility() {
        let state = Arc::new(ToolState::new(false, true, None));
        let result = move_cursor::MoveCursorTool::new(state)
            .invoke(serde_json::json!({"x": 10, "y": 20, "session": "test"}))
            .await;
        assert_facility_unavailable(result);
    }
}

// RecordingSession lives in cua-driver-core, but its `start()` pulls in the
// macOS cursor sampler (CoreGraphics), so the start-guard test runs here in
// platform-macos where build.rs links the frameworks — the core crate's test
// binary has no CoreGraphics linkage.
#[cfg(test)]
mod pixel_focus_readback_tests {
    use super::point_within_rect;

    #[test]
    fn confirms_a_point_inside_the_focused_element() {
        let composer = [100.0, 800.0, 250.0, 24.0];
        assert!(point_within_rect(composer, 220.0, 812.0));
        assert!(
            point_within_rect(composer, 100.0, 800.0),
            "top-left is inside"
        );
    }

    #[test]
    fn rejects_a_point_outside_the_focused_element() {
        // The WhatsApp case: the click targeted the composer but focus stayed on
        // the transcript above it, so the clicked point is not inside the
        // focused element's rect and the caller must escalate.
        let transcript = [100.0, 100.0, 640.0, 690.0];
        assert!(!point_within_rect(transcript, 220.0, 812.0));
    }

    #[test]
    fn excludes_the_far_edges() {
        let rect = [0.0, 0.0, 10.0, 10.0];
        assert!(!point_within_rect(rect, 10.0, 5.0));
        assert!(!point_within_rect(rect, 5.0, 10.0));
    }

    #[test]
    fn a_degenerate_rect_never_confirms() {
        assert!(!point_within_rect([5.0, 5.0, 0.0, 0.0], 5.0, 5.0));
        assert!(!point_within_rect([5.0, 5.0, -3.0, 10.0], 5.0, 6.0));
    }
}

#[cfg(test)]
mod recording_start_guard_tests {
    use cua_driver_core::recording::{RecordingSession, StopBy};
    use cua_driver_core::session::fire_session_end;

    #[test]
    fn start_refuses_for_ended_session_owner() {
        // THE FIX (recording side): an in-flight start_recording owned by a
        // session that already ended would leak an ffmpeg/SCStream process owned
        // by a dead session that is never reaped. start() must refuse.
        let rec = RecordingSession::new();
        let sid = "wb-recording-ended-W4X5Y6";
        fire_session_end(sid);
        assert!(cua_driver_core::session::is_session_ended(sid));

        let dir = std::env::temp_dir().join("wb-rec-ended");
        let err = rec.start(dir.to_str().unwrap(), false, Some(sid));
        assert!(err.is_err(), "start for an ended session owner must error");
        assert!(
            !rec.current_state().enabled,
            "no recording may start for a dead session"
        );
    }

    #[test]
    fn start_succeeds_for_live_session_owner() {
        let rec = RecordingSession::new();
        let sid = "wb-recording-live-Z7A8B9";
        assert!(!cua_driver_core::session::is_session_ended(sid));
        let dir = std::env::temp_dir().join("wb-rec-live");
        // record_video=false avoids spawning ffmpeg in the test.
        let ok = rec.start(dir.to_str().unwrap(), false, Some(sid));
        assert!(ok.is_ok(), "start for a live session owner must succeed");
        assert!(rec.current_state().enabled);
        let _ = rec.stop(StopBy::Owner(sid));
    }

    #[test]
    fn start_succeeds_for_anonymous_owner() {
        // owner = None (CLI one-shot / legacy shim) is never gated.
        let rec = RecordingSession::new();
        let dir = std::env::temp_dir().join("wb-rec-anon");
        let ok = rec.start(dir.to_str().unwrap(), false, None);
        assert!(ok.is_ok(), "anonymous start must never be gated");
        assert!(rec.current_state().enabled);
        let _ = rec.stop(StopBy::Anyone);
    }
}

#[cfg(test)]
mod windowserver_refusal_tests {
    use super::*;

    #[test]
    fn refusal_names_the_reason_and_the_app_bundle_daemon() {
        let result = windowserver_connection_refusal(42, Some(7));
        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured");
        assert_eq!(structured["code"], "background_unavailable");
        assert_eq!(structured["reason"], "windowserver_connection_invalid");
        assert_eq!(structured["status"], 1002);
        assert_eq!(structured["window_id"], 7);
        assert!(structured["hint"]
            .as_str()
            .unwrap()
            .contains("cua-driver permissions grant"));
    }
}

#[cfg(test)]
mod element_disabled_tests {
    use super::*;
    use crate::input::ax_actions::ElementDisabled;

    fn disabled() -> ElementDisabled {
        ElementDisabled {
            action: "set_value".into(),
        }
    }

    #[test]
    fn background_app_refusal_is_coded_and_escalates_to_foreground() {
        let result = disabled_refusal(42, 7, &disabled(), true);
        assert_eq!(result.is_error, Some(true));
        let structured = result.structured_content.expect("structured");
        assert_eq!(structured["code"], "element_disabled");
        assert_eq!(structured["effect"], "refused");
        assert_eq!(structured["action"], "set_value");
        assert_eq!(structured["window_id"], 7);
        // run_steps' foreground_fallback keys off this field.
        assert_eq!(structured["escalation"]["recommended"], "foreground");
    }

    #[test]
    fn frontmost_app_refusal_does_not_suggest_fronting() {
        let result = disabled_refusal(42, 7, &disabled(), false);
        let structured = result.structured_content.expect("structured");
        assert_eq!(structured["code"], "element_disabled");
        assert!(structured.get("escalation").is_none(), "{structured}");
    }
}