Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(computer-use): identify a window by id, not by its shape

vastsa0de385f064e5
diff --git a/crates/host-core/src/computer/backend.rs b/crates/host-core/src/computer/backend.rs
index 114c6b589..2a208460c 100644
--- a/crates/host-core/src/computer/backend.rs
+++ b/crates/host-core/src/computer/backend.rs
@@ -105,6 +105,17 @@ pub trait Desktop: Send + Sync {
fn inspect(&self, target: &TargetRef, max_nodes: usize) -> Result<RawInspection, DesktopError>;
+ /// Whether this target's tree can be opened at all.
+ ///
+ /// The window server enumerates surfaces that no accessibility client can
+ /// reach — Stage Manager's strip, overlay helpers — and they look exactly
+ /// like application windows in `list_targets`. Binding one is not a
+ /// security problem, it is a wasted turn, so the automatic grant asks this
+ /// before choosing. A one-node probe is the cheapest honest answer.
+ fn can_open(&self, target: &TargetRef) -> bool {
+ self.inspect(target, 1).is_ok()
+ }
+
/// Whether the OS reports a secure input state right now. A backend that
/// cannot tell must answer `true`: refusing is the safe default, since the
/// alternative is typing into a password field.
diff --git a/crates/host-core/src/computer/macos/ffi.rs b/crates/host-core/src/computer/macos/ffi.rs
index 68009189a..849a29417 100644
--- a/crates/host-core/src/computer/macos/ffi.rs
+++ b/crates/host-core/src/computer/macos/ffi.rs
@@ -47,6 +47,15 @@ pub(super) struct CGSize {
pub(super) height: f64,
}
+pub(super) const RTLD_LAZY: i32 = 0x1;
+
+// libSystem, not a framework: used only to resolve the one AX symbol that has
+// no public declaration (see `ax_window_id`).
+extern "C" {
+ pub(super) fn dlopen(path: *const i8, mode: i32) -> *mut c_void;
+ pub(super) fn dlsym(handle: *mut c_void, symbol: *const i8) -> *mut c_void;
+}
+
#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
pub(super) fn CFRelease(cf: CFTypeRef);
@@ -220,6 +229,49 @@ pub(super) fn cf_string_value(value: CFTypeRef) -> Option<String> {
}
}
+/// `_AXUIElementGetWindow(AXUIElementRef, CGWindowID*) -> AXError`.
+type AxGetWindowFn = unsafe extern "C" fn(AXUIElementRef, *mut u32) -> AXError;
+
+/// The real `CGWindowID` behind an accessibility window element, when this
+/// system exposes it.
+///
+/// Accessibility publishes no supported way to read a window's id, so joining
+/// the `CGWindowList` entry to its AX element has to go through
+/// `_AXUIElementGetWindow` — undocumented, present since 10.5, and what every
+/// window manager on the platform uses. It is resolved with `dlsym` rather than
+/// linked, so a release that drops it degrades to the geometry join in
+/// `window_matches` instead of failing to launch.
+pub(super) fn ax_window_id(element: AXUIElementRef) -> Option<u32> {
+ use std::sync::OnceLock;
+ static RESOLVED: OnceLock<Option<AxGetWindowFn>> = OnceLock::new();
+ let resolved = RESOLVED.get_or_init(|| {
+ // SAFETY: a null path asks for the global symbol scope, and the symbol
+ // is transmuted to the signature declared above or discarded.
+ unsafe {
+ let handle = dlopen(std::ptr::null(), RTLD_LAZY);
+ if handle.is_null() {
+ return None;
+ }
+ let symbol = dlsym(handle, c"_AXUIElementGetWindow".as_ptr());
+ if symbol.is_null() {
+ None
+ } else {
+ Some(std::mem::transmute::<*mut c_void, AxGetWindowFn>(symbol))
+ }
+ }
+ });
+ let function = (*resolved)?;
+ let mut window: u32 = 0;
+ // SAFETY: `element` is a live AX element and the out pointer is sized.
+ let status = unsafe { function(element, &mut window) };
+ // Window id 0 is `kCGNullWindowID`: an answer that identifies nothing.
+ if status == kAXErrorSuccess && window != 0 {
+ Some(window)
+ } else {
+ None
+ }
+}
+
pub(super) fn cf_number_f64(value: CFTypeRef) -> Option<f64> {
if value.is_null() {
return None;
diff --git a/crates/host-core/src/computer/macos/mod.rs b/crates/host-core/src/computer/macos/mod.rs
index a3e7d0a5a..eaea03ed9 100644
--- a/crates/host-core/src/computer/macos/mod.rs
+++ b/crates/host-core/src/computer/macos/mod.rs
@@ -111,9 +111,18 @@ impl MacDesktop {
}
fn window_matches(&self, window: AXUIElementRef, target: &TargetRef) -> bool {
- // The window id is encoded in `target_id` as `<pid>:<window>`, and the
- // AX side cannot read it, so geometry is the join key. `measure` is the
- // authority on whether the grant still describes this window.
+ // The window id is the join key when the system exposes it: it is the
+ // same number `CGWindowList` gave us, so a match is an identity and a
+ // mismatch is definitive rather than a reason to guess by shape.
+ if let Some(id) = ax_window_id(window) {
+ return u64::from(id) == target.window;
+ }
+ // Fallback for a system without `_AXUIElementGetWindow`: geometry, the
+ // other thing both sides report. It is unreliable when the window
+ // server and accessibility disagree about a window's frame — Stage
+ // Manager reports a thumbnail to `CGWindowList` while accessibility
+ // reports the real frame — so an off-stage window is refused here
+ // rather than confused with another one.
let Some(position) = attribute_point(window, "AXPosition") else {
return false;
};
@@ -131,6 +140,21 @@ impl MacDesktop {
.unwrap_or(false)
}
+ /// The window's frame as accessibility reports it, which is the frame every
+ /// element position is relative to. `None` when the window cannot be
+ /// opened — including before the Accessibility grant exists.
+ fn ax_bounds(&self, target: &TargetRef) -> Option<Rect> {
+ let window = self.window_element(target).ok()?;
+ let position = attribute_point(window.as_ref(), "AXPosition")?;
+ let size = attribute_size(window.as_ref(), "AXSize")?;
+ Some(Rect {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ })
+ }
+
/// Window geometry straight from `CGWindowList`, which does not need the
/// Accessibility grant and is therefore also the pre-permission answer.
fn cg_bounds(&self, target: &TargetRef) -> Option<Rect> {
@@ -499,8 +523,15 @@ impl Desktop for MacDesktop {
.into_iter()
.find(|item| item.target.window == target.window && item.target.pid == target.pid)
.ok_or(DesktopError::TargetGone)?;
+ // Identity comes from the window server, geometry from accessibility.
+ // The two disagree whenever the window server is showing something
+ // other than the window itself — Stage Manager reports a thumbnail —
+ // and every coordinate this grant will produce (element bounds, the
+ // clamp, the drawn cursor, the capture crop) is in accessibility's
+ // frame, so that is the frame the grant must carry.
+ let bounds = self.ax_bounds(target).unwrap_or(found.bounds);
Ok(Measured {
- bounds: found.bounds,
+ bounds,
app_key: found.target.app_key,
title: found.title,
})
diff --git a/crates/host-core/src/computer/policy.rs b/crates/host-core/src/computer/policy.rs
index 31b4f7db4..1d2974a69 100644
--- a/crates/host-core/src/computer/policy.rs
+++ b/crates/host-core/src/computer/policy.rs
@@ -180,8 +180,19 @@ fn frontmost_usable(
denylist: &Denylist,
) -> ComputerResult<RawTarget> {
let raw = desktop.list_targets().map_err(Refusal::from)?;
- raw.into_iter()
- .find(|item| refusal_for_target(item, self_pids, denylist).is_none())
+ let allowed = raw
+ .into_iter()
+ .filter(|item| refusal_for_target(item, self_pids, denylist).is_none())
+ .collect::<Vec<_>>();
+ // Prefer a window whose tree can actually be read, so the agent does not
+ // start bound to a window-server surface it can only switch away from.
+ // A desktop where nothing opens still binds the frontmost allowed window:
+ // the refusal then comes from the read, where it can be attributed.
+ allowed
+ .iter()
+ .find(|item| desktop.can_open(&item.target))
+ .cloned()
+ .or_else(|| allowed.into_iter().next())
.ok_or(Refusal::ScopeViolation)
}
@@ -405,6 +416,45 @@ pub fn inspect(
})
}
+/// Bind a window if one was named, then inspect whatever is bound.
+///
+/// A failed inspection leaves the grant describing the window it already had:
+/// the caller's request did not succeed, so the grant must not quietly end up
+/// on a window nobody could read — the next `act` would then be aimed at a
+/// window the caller never saw. The revision keeps the bump either way, so
+/// nothing the caller is holding validates after a move it did not observe.
+pub fn inspect_bound(
+ desktop: &dyn Desktop,
+ grant: &mut Grant,
+ denylist: &Denylist,
+ target_id: Option<&str>,
+ expected_revision: Option<u32>,
+ now: Instant,
+) -> ComputerResult<Inspection> {
+ let restore = target_id.map(|_| {
+ (
+ grant.target.clone(),
+ grant.target_label.clone(),
+ grant.bounds,
+ )
+ });
+ if let Some(target_id) = target_id {
+ // A refused bind mutates nothing, so there is nothing to put back.
+ bind_target(desktop, grant, denylist, target_id)?;
+ }
+ match inspect(desktop, grant, denylist, expected_revision, now) {
+ Ok(inspection) => Ok(inspection),
+ Err(refusal) => {
+ if let Some((target, label, bounds)) = restore {
+ grant.target = target;
+ grant.target_label = label;
+ grant.bounds = bounds;
+ }
+ Err(refusal)
+ }
+ }
+}
+
/// Labels come from windows the user does not control, so they are bounded
/// here rather than trusted from a backend.
fn bound_nodes(nodes: Vec<Node>) -> Vec<Node> {
diff --git a/crates/host-core/src/computer/tests.rs b/crates/host-core/src/computer/tests.rs
index 79d7dfd1f..0c1e36697 100644
--- a/crates/host-core/src/computer/tests.rs
+++ b/crates/host-core/src/computer/tests.rs
@@ -46,6 +46,9 @@ struct FakeDesktop {
secure_input: Mutex<bool>,
perform_result: Mutex<Result<Dispatched, DesktopError>>,
performed: Mutex<Vec<(Option<String>, ActionKind)>>,
+ /// Set when the platform can enumerate a window but not read its tree —
+ /// the real macOS case when the window is off-stage.
+ inspect_error: Mutex<Option<DesktopError>>,
}
impl FakeDesktop {
@@ -68,9 +71,14 @@ impl FakeDesktop {
secure_input: Mutex::new(false),
perform_result: Mutex::new(Ok(Dispatched::AccessibilityAction)),
performed: Mutex::new(Vec::new()),
+ inspect_error: Mutex::new(None),
}
}
+ fn set_inspect_error(&self, error: Option<DesktopError>) {
+ *self.inspect_error.lock().unwrap() = error;
+ }
+
fn set_measured(&self, measured: Option<Measured>) {
*self.measured.lock().unwrap() = measured;
}
@@ -119,6 +127,9 @@ impl Desktop for FakeDesktop {
_target: &TargetRef,
_max_nodes: usize,
) -> Result<RawInspection, DesktopError> {
+ if let Some(error) = self.inspect_error.lock().unwrap().clone() {
+ return Err(error);
+ }
Ok(RawInspection {
nodes: vec![node("0.1", "AXButton", vec![ActionKind::Click])],
truncated: false,
@@ -695,6 +706,72 @@ fn a_desktop_grant_binds_the_frontmost_usable_window() {
assert_eq!(grant.view(Instant::now()).scope, super::GrantScope::Desktop);
}
+#[test]
+fn an_automatic_grant_skips_a_window_whose_tree_cannot_be_opened() {
+ // The device case: the window server lists Stage Manager's own surfaces in
+ // front of the user's windows, and nothing can read them.
+ struct OnlySecondOpens(FakeDesktop);
+ impl Desktop for OnlySecondOpens {
+ fn capabilities(&self) -> Capabilities {
+ self.0.capabilities()
+ }
+ fn list_targets(&self) -> Result<Vec<RawTarget>, DesktopError> {
+ self.0.list_targets()
+ }
+ fn measure(&self, target: &TargetRef) -> Result<Measured, DesktopError> {
+ self.0.measure(target)
+ }
+ fn inspect(
+ &self,
+ target: &TargetRef,
+ max_nodes: usize,
+ ) -> Result<RawInspection, DesktopError> {
+ if target.target_id == "overlay" {
+ return Err(DesktopError::TargetGone);
+ }
+ self.0.inspect(target, max_nodes)
+ }
+ fn secure_input_active(&self) -> bool {
+ self.0.secure_input_active()
+ }
+ fn perform(
+ &self,
+ target: &TargetRef,
+ uid: Option<&str>,
+ action: &Action,
+ ) -> Result<Dispatched, DesktopError> {
+ self.0.perform(target, uid, action)
+ }
+ fn self_pids(&self) -> Vec<i32> {
+ self.0.self_pids()
+ }
+ }
+
+ let desktop = OnlySecondOpens(FakeDesktop::new(vec![
+ target(404, "windowmanager", "WindowManager", "overlay"),
+ target(5, "com.example.app", "Example", "w1"),
+ ]));
+ let grant = policy::create_grant(
+ &desktop,
+ None,
+ &Denylist::default(),
+ GrantRequest {
+ target_id: None,
+ session_id: "s".into(),
+ input_policy: InputPolicy::AutonomousInScope,
+ capture: CaptureMode::A11yOnly,
+ action_budget: 3,
+ idle_expiry: Duration::from_secs(600),
+ },
+ Instant::now(),
+ )
+ .expect("grant");
+ assert_eq!(
+ grant.target.target_id, "w1",
+ "the unreadable surface is skipped"
+ );
+}
+
#[test]
fn a_desktop_grant_refuses_when_every_window_is_refused() {
let desktop = FakeDesktop::new(vec![
@@ -750,6 +827,51 @@ fn binding_another_window_moves_the_revision() {
assert_eq!(desktop.performed_count(), 0);
}
+#[test]
+fn a_window_that_cannot_be_read_does_not_become_the_bound_one() {
+ // The macOS case this came from: `CGWindowList` enumerates an off-stage
+ // window that the accessibility client cannot open. The bind is allowed,
+ // the read fails, and the grant must stay where the caller last saw it.
+ let desktop = FakeDesktop::new(vec![
+ target(5, "com.example.app", "Example", "w1"),
+ target(6, "com.other.app", "Other", "w2"),
+ ]);
+ let mut grant = desktop_grant(&desktop, &Denylist::default());
+ assert_eq!(grant.target.target_id, "w1");
+ let revision_before = grant.revision;
+ desktop.set_inspect_error(Some(DesktopError::TargetGone));
+
+ let error = policy::inspect_bound(
+ &desktop,
+ &mut grant,
+ &Denylist::default(),
+ Some("w2"),
+ None,
+ Instant::now(),
+ )
+ .expect_err("the unreadable window must refuse");
+ assert_eq!(error, Refusal::ScopeViolation);
+ assert_eq!(grant.target.target_id, "w1", "the grant stays where it was");
+ assert_eq!(grant.target_label, "Example — Document");
+ assert!(
+ grant.revision > revision_before,
+ "the attempted move still invalidates held ids"
+ );
+
+ // And the window it stayed on is still readable.
+ desktop.set_inspect_error(None);
+ let inspection = policy::inspect_bound(
+ &desktop,
+ &mut grant,
+ &Denylist::default(),
+ None,
+ None,
+ Instant::now(),
+ )
+ .expect("the original window still inspects");
+ assert_eq!(inspection.nodes.len(), 1);
+}
+
#[test]
fn a_rebind_re_applies_every_refusal() {
let desktop = FakeDesktop::new(vec![
diff --git a/crates/host-core/src/rpc/computer_rpc.rs b/crates/host-core/src/rpc/computer_rpc.rs
index ff613701a..adb6c9afb 100644
--- a/crates/host-core/src/rpc/computer_rpc.rs
+++ b/crates/host-core/src/rpc/computer_rpc.rs
@@ -285,13 +285,15 @@ pub(crate) async fn handle(
)
.map_err(refusal_err)?;
let before = grant.target.target_id.clone();
- if let Some(target_id) = target_id.as_deref() {
- policy::bind_target(desktop.as_ref(), grant, &denylist, target_id)
- .map_err(refusal_err)?;
- }
- let inspection =
- policy::inspect(desktop.as_ref(), grant, &denylist, expected_revision, now)
- .map_err(refusal_err)?;
+ let inspection = policy::inspect_bound(
+ desktop.as_ref(),
+ grant,
+ &denylist,
+ target_id.as_deref(),
+ expected_revision,
+ now,
+ )
+ .map_err(refusal_err)?;
// Covers both a named rebind and the fallback inside `refresh`:
// which application the grant moved to is exactly the identity the
// audit trail is for, and no window text goes with it.
diff --git a/docs/implementation/computer-use-evidence.md b/docs/implementation/computer-use-evidence.md
index ab6dcbebe..c42b265d8 100644
--- a/docs/implementation/computer-use-evidence.md
+++ b/docs/implementation/computer-use-evidence.md
@@ -34,31 +34,75 @@ no captured pixels, and no credentials.
| `pnpm --filter @pi-desktop/desktop typecheck` | Clean |
| `pnpm docs:check` / `check-locales` | Clean on this branch except the pre-existing duplicate ADR 0339, fixed separately |
+## What ran on a device
+
+macOS 15 (Darwin 24.6), Accessibility granted to the probing process, Stage
+Manager active, Screen Recording **not** granted. Driven by
+`PI_DESKTOP_COMPUTER_USE_DEVICE=1 node scripts/e2e-computer-use-device.mjs`
+against the real host binary and a throwaway data dir, with
+`--act-app`/`--deny` for the input and denylist checks. 15 / 15 checks passed.
+
+| Checked against real windows | Result |
+|---|---|
+| Backend identity and Accessibility trust | `macos-ax`, `granted` |
+| Window enumeration, with our own window listed and refused | our window was frontmost and refused `self` |
+| The automatic desktop grant binds the frontmost *usable* window | bound the first window that was neither ours nor unreadable |
+| Real accessibility tree | 15–400 nodes across six applications, `fidelity: full` |
+| No element value ever leaves the host | no node carried a value field |
+| Rebind to another application's window | revision moved; the pre-rebind revision then refused an action |
+| Self-target, denylist, and unknown-window binds | `COMPUTER_SELF_TARGET_REFUSED`, `COMPUTER_TARGET_DENYLISTED`, `COMPUTER_SCOPE_VIOLATION` |
+| One real action | `set_value` through the platform accessibility action; the document's text changed and the budget went 40 → 39 |
+| Stop cooldown | an agent mint refused `COMPUTER_STOPPED_BY_USER`; a user mint cleared it |
+
+The run found two defects, both now fixed:
+
+- **The accessibility window could not be matched to the window-server
+ window.** `window_matches` joined the two by geometry, and under Stage
+ Manager `CGWindowList` reports an off-stage window's *thumbnail* frame while
+ accessibility reports its real frame — measured on the device as `37,607
+ 121x137` against `219,44 1568x1125` for the same window. Every window except
+ the one on stage was therefore refused `COMPUTER_SCOPE_VIOLATION`, which made
+ the capability unusable in practice. The join is now the window id from
+ `_AXUIElementGetWindow`, resolved with `dlsym` so a system without it falls
+ back to the geometry match. The same wrong geometry reached `measure`, so a
+ grant's bounds — and with them coordinate clamping, the `basis`, the drawn
+ cursor, and the capture crop — now come from accessibility's frame.
+- **A failed read left the grant on the window it could not read.** The bind
+ succeeded, the inspection failed, and the grant stayed moved, so a later
+ action was aimed at a window the caller had never seen. `inspect_bound`
+ restores the previous binding on failure and keeps the revision bump.
+
## What did not run, and what that means
-- **No real application was ever driven.** No `AXUIElement` action, no
- `CGEventPostToPid` key, no `desktopCapturer` frame, and no macOS
- Accessibility prompt was triggered on this machine. The macOS backend is
- compiled and its pure parts (element id round-trip, chord table, action
- mapping) are unit-tested; everything that touches a live window is unproven.
+- **The Electron half is unproven on a device.** The automatic mint through the
+ `Computer` tool, the indicator, Stop aborting the owning turn, the drawn
+ cursor overlay, and the bounded loop against a real model all need the app
+ running with a configured provider; none of that was exercised. The device
+ probe talks to host-core directly.
+- **No pixels were captured.** Screen Recording is not granted on the probing
+ machine, so `a11y-and-pixels` grants, the scope-cropped capture, and the
+ tool-image path remain unverified.
+- **Secure input was not forced.** The refusal is unit-covered, but no password
+ field was focused during a device run.
+- **`CGEventPostToPid` never ran.** The one device action took the accessibility
+ path, which is the preferred one; the window-targeted event fallback (and the
+ chord table behind `press_keys`) is still fixture-only.
- **Windows and Linux have no backend yet.** They compile to the unsupported
backend, so every operation there answers
`COMPUTER_PLATFORM_UNSUPPORTED` rather than failing oddly. Stage 2 adds UIA
and AT-SPI with their own dependency review and device matrix.
- **No UI test covers the indicator, its Stop, or the drawn cursor.**
- Repository policy reserves `verify:ui:*` for an explicit request, and the
- `E2E-COMPUTER-USE-*` scenarios are `NOT RUN`. In particular, Stop aborting
- the owning turn has only been reasoned about, not clicked.
+ Repository policy reserves `verify:ui:*` for an explicit request. In
+ particular, Stop aborting the owning turn has only been reasoned about, not
+ clicked.
- **`confirm-each` has no approval card and never did.** It stays in the
settings contract, is no longer offered in Settings, and selecting it through
a settings write narrows nothing today. ADR 0342 described a per-step card
that stage 1 did not build; ADR 0344 names the gap instead of implying it is
closed.
-- **The automatic grant and window switching are fixture-covered only.** The
- frontmost-usable bind, every rebind refusal, the closed-window fallback, and
- the Stop cooldown are unit tests against the fake backend. Whether the real
- macOS enumeration is actually ordered front-to-back — which is what "the
- frontmost usable window" relies on — is unverified on a device.
+- **The closed-window fallback is fixture-only.** Binding, the refusals, and
+ the Stop cooldown now have device evidence; deliberately closing the bound
+ window mid-action does not.
- **No provider call was made.** The loop's model request is covered by
injected, scripted answers only; no computer-use model was configured and no
token was spent.
@@ -72,18 +116,24 @@ The dangerous surface is the macOS backend, because it is the only code here
that can move another application. Its refusals are enforced one layer above it
in `policy.rs`, which *is* covered: self-target, secure input, stale basis,
stale revision, coordinate clamping, budget, expiry, single-grant exclusivity,
-rebind refusals, and the credential denylist all have tests that fail closed.
-What remains unproven is whether the backend can actually drive a real window —
-a bug there shows up as "nothing happens", not as a lost refusal.
+rebind refusals, and the credential denylist all have tests that fail closed —
+and the device run above exercised the self-target, denylist, unknown-window,
+stale-revision, and cooldown refusals against real windows.
ADR 0344 raises the stakes on exactly that layer. With no picker in front of
the capability, the refusals are the only thing standing between an enabled
feature and arbitrary windows, and they now run on every bind rather than once.
-They are unit-covered against a fake backend; they are not device-verified.
-
-A device run on macOS is the next gate: enable the feature, bind a model, let
-the agent take the desktop grant, and confirm the bound window is the frontmost
-non-PI-Desktop one, the drawn cursor, one accessibility press, a window switch,
-the audit lines (`created`, `rebound`, `act`), Stop aborting the turn, and the
-cooldown refusing the agent's immediate retry. Until that happens, treat this
-as implemented and unverified.
+
+What the device run also showed is where the risk actually lives: not in a lost
+refusal, but in the platform join. Both defects it found were "the host cannot
+tell which window this is", and the second one let the grant sit on a window
+nobody had read. The window-id join removes the ambiguity, but it rests on an
+undocumented symbol (`_AXUIElementGetWindow`, D683): if a future macOS drops
+it, the geometry fallback returns the product to the state this run found —
+usable only for the window on stage. That is the thing to re-run the probe for
+after every macOS upgrade.
+
+Still open before this can be called verified end to end: the Electron half
+(automatic mint through the tool, indicator, Stop aborting the turn, drawn
+cursor, the loop against a real model), capture under a Screen Recording grant,
+secure input on a device, and the `press_keys` / window-event fallback path.
diff --git a/docs/spec/03-runtime/computer-use.md b/docs/spec/03-runtime/computer-use.md
index c35de6c33..31e70171e 100644
--- a/docs/spec/03-runtime/computer-use.md
+++ b/docs/spec/03-runtime/computer-use.md
@@ -265,7 +265,7 @@ measured — so only inspection and input are platform work.
| Platform | Inspection and input | Stage | Notes |
|---|---|---|---|
-| macOS | `AXUIElement` actions behind the Accessibility TCC grant; `CGEventPostToPid` for keys into the granted app | 1 | Hand-declared framework FFI, no new crates; secure input refuses both capture and input |
+| macOS | `AXUIElement` actions behind the Accessibility TCC grant; `CGEventPostToPid` for keys into the granted app | 1 | Hand-declared framework FFI, no new crates; secure input refuses both capture and input. The accessibility window is joined to the `CGWindowList` entry by window id through `_AXUIElementGetWindow`, resolved with `dlsym` and falling back to a geometry match (D683) — the window server and accessibility disagree about a window's frame whenever Stage Manager shows a thumbnail, so geometry alone refuses every off-stage window. A grant's geometry is accessibility's frame, because element bounds, the coordinate clamp, the drawn cursor, and the capture crop are all in it |
| Windows | UI Automation patterns, with window-targeted messages as the fallback | 2 | A window owned by a higher-integrity process is refused, never silently dropped |
| Linux / X11 | AT-SPI actions, best effort | 2 | Requires an accessibility bus; absent toolkit support is reported, not guessed |
| Linux / Wayland | Input refused | — | No portable synthetic input exists; capture stays available through the portal |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 2b22dcde8..6e6842d74 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -19725,9 +19725,14 @@ their separate platform acceptance.
## Computer use (ADR 0342, ADR 0344)
Native-control scenarios remain landing gates for
-[03-runtime/computer-use](../03-runtime/computer-use.md). Their underlying
-refusals are unit-covered, but driving real applications remains `NOT RUN`.
-The permission-request UI below has isolated fixture automation.
+[03-runtime/computer-use](../03-runtime/computer-use.md). The host half now has
+device evidence on macOS through
+`PI_DESKTOP_COMPUTER_USE_DEVICE=1 node scripts/e2e-computer-use-device.mjs`
+(opt-in: it reads the operator's screen, and with `--act-app` types into one of
+their windows). The Electron half — the automatic mint through the tool, the
+indicator, Stop aborting the turn, the drawn cursor, and the loop against a real
+model — is still `NOT RUN`, and so is anything needing Screen Recording. The
+permission-request UI below has isolated fixture automation.
### E2E-COMPUTER-USE-request-accessibility-from-settings
@@ -19788,8 +19793,14 @@ The permission-request UI below has isolated fixture automation.
`an_idle_grant_expires_and_stays_expired`, and
`the_budget_closes_the_grant_and_refuses_the_next_action` in host-core;
`apps/desktop/test/computer-use-service.test.mjs` covers the automatic mint,
- the Stop refusal, and the wrong-session refusal the agent would hit.
-- **Status**: NOT RUN — needs a real window and a real turn to abort.
+ the Stop refusal, and the wrong-session refusal the agent would hit. Device:
+ `scripts/e2e-computer-use-device.mjs`.
+- **Status**: PARTIAL — the device probe confirmed the automatic desktop grant
+ binding the frontmost usable window (with our own window refused in front of
+ it), the settings defaults reaching the grant, the real tree, and the Stop
+ cooldown on macOS 15 with Stage Manager active. The indicator, Stop aborting
+ the owning turn, budget and idle closure in a running app, and the restart
+ case are NOT RUN.
### E2E-COMPUTER-USE-window-switching-stays-inside-the-refusals
@@ -19818,7 +19829,15 @@ The permission-request UI below has isolated fixture automation.
host-core; `packages/computer-use` loop tests cover the switch step, the
refused-switch recovery, and the terminal-grant case;
`apps/desktop/test/computer-use-service.test.mjs` pins the host call shape.
-- **Status**: NOT RUN — needs real windows to switch between.
+ Device: `scripts/e2e-computer-use-device.mjs`.
+- **Status**: PARTIAL — on device, switching between six real applications
+ worked, the revision moved on every bind, a pre-switch revision was refused,
+ and the self-target, denylist and unknown-window binds were refused by code.
+ Two defects were found and fixed there: the accessibility window could not be
+ matched to the window-server window under Stage Manager (now joined by window
+ id, D683), and a failed read left the grant on the unreadable window. The
+ closed-window fallback, the cursor re-frame, and the audit read-back are
+ NOT RUN.
### E2E-COMPUTER-USE-self-target-and-secure-input-refused
@@ -19840,8 +19859,13 @@ The permission-request UI below has isolated fixture automation.
- **Automation**: `computer::tests::our_own_windows_are_never_targetable`,
`a_renamed_self_process_is_still_refused`,
`built_in_credential_surfaces_cannot_be_allowlisted`, and
- `secure_input_refuses_both_inspection_and_action` in host-core.
-- **Status**: NOT RUN — needs a real approval card and a real password field.
+ `secure_input_refuses_both_inspection_and_action` in host-core. Device:
+ `scripts/e2e-computer-use-device.mjs`.
+- **Status**: PARTIAL — on device, a PI-Desktop window sat in front of every
+ other window and was refused `COMPUTER_SELF_TARGET_REFUSED` both as the
+ automatic grant's choice and as an explicit bind, and a denylisted window was
+ refused `COMPUTER_TARGET_DENYLISTED`. The approval card specifically, and the
+ secure-input and password-field refusals, are NOT RUN.
### E2E-COMPUTER-USE-stale-basis-and-revision-fail-closed
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index fb16d96a2..664f1b292 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -8310,3 +8310,42 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
test, and `apps/desktop/test/computer-use-service.test.mjs` (automatic mint,
Stop refusal, switch call shape). Still device-unverified: the
`E2E-COMPUTER-USE-*` gates remain `NOT RUN`.
+
+## 2026-11-05 — The accessibility window is joined by window id, not geometry (D683)
+
+- D683 records a device finding and the private symbol that fixes it. The first
+ real-device run of computer use (macOS 15, Stage Manager active) refused every
+ window except the one on stage: `window_matches` joined the `CGWindowList`
+ entry to its `AXUIElement` by geometry, and the window server reports an
+ off-stage window at its Stage Manager *thumbnail* frame while accessibility
+ reports the real one — measured as `37,607 121x137` against
+ `219,44 1568x1125` for the same window. Geometry is therefore not an identity
+ on this platform, and the capability was unusable in practice.
+- The join is now the window id from `_AXUIElementGetWindow`, which is the same
+ number `CGWindowList` supplies. It is undocumented, has existed since 10.5,
+ and is what every window manager on the platform uses. It is resolved through
+ `dlsym` rather than linked, so a release that drops it degrades to the
+ geometry match instead of failing to launch; a readable id that disagrees is
+ definitive and refuses. No new crate, and the rest of the FFI surface is
+ unchanged.
+- A grant now carries accessibility's window frame rather than the window
+ server's, because element bounds, the coordinate clamp, the `basis`, the drawn
+ cursor, and the capture crop are all in that frame. `measure` keeps taking
+ identity (`appKey`, title) from `CGWindowList` and falls back to its geometry
+ when the window cannot be opened.
+- Two smaller consequences of the same run: the automatic grant now prefers a
+ window whose tree can actually be opened (`Desktop::can_open`, a one-node
+ probe), because the window server lists Stage Manager surfaces in front of
+ the user's windows and binding one wastes a turn; and a failed read no longer
+ leaves the grant on the window it could not read (`policy::inspect_bound`
+ restores the previous binding and keeps the revision bump).
+- The probe itself is `scripts/e2e-computer-use-device.mjs`, opt-in behind
+ `PI_DESKTOP_COMPUTER_USE_DEVICE=1` because it reads the operator's screen and
+ can type into one of their windows. Window titles are withheld unless
+ `--titles` is passed. Re-run it after a macOS upgrade: if `_AXUIElementGetWindow`
+ ever disappears, this is the check that notices.
+- Covered by `computer::tests::an_automatic_grant_skips_a_window_whose_tree_cannot_be_opened`
+ and `a_window_that_cannot_be_read_does_not_become_the_bound_one`; the join
+ itself is platform code and is covered only by the device probe. See
+ `docs/implementation/computer-use-evidence.md` for what the run proved and
+ what it did not.
diff --git a/docs/zh-CN/spec/03-runtime/computer-use.md b/docs/zh-CN/spec/03-runtime/computer-use.md
index 740f1c4f1..8bb44dc8d 100644
--- a/docs/zh-CN/spec/03-runtime/computer-use.md
+++ b/docs/zh-CN/spec/03-runtime/computer-use.md
@@ -140,7 +140,7 @@ Agent 以一条自然语言 `instruction` 加可选 `maxSteps` 调用它;`obse
| 平台 | 检查与输入 | 阶段 | 说明 |
|---|---|---|---|
-| macOS | `AXUIElement` 动作,需 Accessibility TCC 授权;按键用 `CGEventPostToPid` 投向被授权应用 | 1 | 手写 framework FFI,不引入新 crate;安全输入会同时拒绝截取与输入 |
+| macOS | `AXUIElement` 动作,需 Accessibility TCC 授权;按键用 `CGEventPostToPid` 投向被授权应用 | 1 | 手写 framework FFI,不引入新 crate;安全输入会同时拒绝截取与输入。无障碍窗口与 `CGWindowList` 条目通过 `_AXUIElementGetWindow` 返回的窗口 id 对应(用 `dlsym` 取,取不到则退回几何匹配,D683)——台前调度显示缩略图时,窗口服务器与无障碍对同一窗口的几何说法不同,只靠几何会拒绝所有不在台前的窗口。授权的几何取无障碍的窗口框,因为元素 bounds、坐标夹取、绘制光标与截取裁剪都在这个坐标系里 |
| Windows | UI Automation 模式,回退到面向窗口的消息 | 2 | 由更高完整性级别进程拥有的窗口被拒绝,绝不静默丢弃 |
| Linux / X11 | AT-SPI 动作,尽力而为 | 2 | 需要无障碍总线;工具包不支持时如实上报,不做猜测 |
| Linux / Wayland | 拒绝输入 | — | 不存在可移植的合成输入;截取仍通过门户可用 |
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index ac169c9eb..e2158e488 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -10163,8 +10163,11 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
## 电脑操作(ADR 0342、ADR 0344)
原生应用操作仍以 [03-runtime/computer-use](/zh-CN/spec/03-runtime/computer-use)
-为落地闸门;拒绝逻辑有单测覆盖,真实应用操作仍为 `NOT RUN`。
-下述权限申请界面已有隔离 fixture 自动化。
+为落地闸门。宿主一侧现已有 macOS 真机证据,来自
+`PI_DESKTOP_COMPUTER_USE_DEVICE=1 node scripts/e2e-computer-use-device.mjs`
+(需显式开启:它会读取操作者的屏幕,带 `--act-app` 时还会往其中一个窗口里输入)。
+Electron 一侧——工具自动签发、指示器、"停止"中止轮次、绘制光标、对真实模型的回路——
+仍为 `NOT RUN`,需要屏幕录制权限的部分同样未跑。下述权限申请界面已有隔离 fixture 自动化。
### E2E-COMPUTER-USE-request-accessibility-from-settings
@@ -10192,7 +10195,12 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
且没有授权能活过重启。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[03-tools-and-permissions](/zh-CN/spec/03-runtime/03-tools-and-permissions)。
-- **状态**:NOT RUN —— 需要真实窗口与一个可中止的真实轮次。
+- **自动化**:host-core 的 `computer::` 测试、
+ `apps/desktop/test/computer-use-service.test.mjs`;真机用
+ `scripts/e2e-computer-use-device.mjs`。
+- **状态**:PARTIAL —— 真机(macOS 15,台前调度开启)已确认:自动桌面授权绑定最前
+ 可用窗口(我们自己的窗口就在它前面且被拒绝)、设置默认值进入授权、真实无障碍树、
+ 以及"停止"冷却。指示器、"停止"中止轮次、运行中的预算与空闲关闭、重启场景仍 NOT RUN。
### E2E-COMPUTER-USE-window-switching-stays-inside-the-refusals
@@ -10210,7 +10218,13 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
记录一条仅含应用身份的 `computer.grant.rebound`。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[05-security/01-security](/zh-CN/spec/05-security/01-security) §13。
-- **状态**:NOT RUN —— 需要可供切换的真实窗口。
+- **自动化**:host-core 的 `computer::` 改绑测试、`packages/computer-use` 的切换测试;
+ 真机用 `scripts/e2e-computer-use-device.mjs`。
+- **状态**:PARTIAL —— 真机上在六个真实应用之间切换成功,每次绑定都推进 revision,
+ 切换前的 revision 被拒绝,自我目标/拒绝名单/未知窗口三种绑定均被按码拒绝。真机还
+ 发现并修掉两个缺陷:台前调度下无障碍窗口无法与窗口服务器窗口对应(改为按窗口 id
+ 对应,D683),以及读取失败时授权会留在读不了的窗口上。关闭绑定窗口的回落、光标重新
+ 框住、审计回读仍 NOT RUN。
### E2E-COMPUTER-USE-self-target-and-secure-input-refused
@@ -10226,7 +10240,9 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
工具结果或日志中。内置拒绝名单条目无法移除。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[05-security/01-security](/zh-CN/spec/05-security/01-security) §13。
-- **状态**:NOT RUN —— 需要真机运行。
+- **状态**:PARTIAL —— 真机上一个 PI-Desktop 窗口位于所有窗口最前,无论作为自动授权
+ 的候选还是显式绑定,都以 `COMPUTER_SELF_TARGET_REFUSED` 被拒;拒绝名单窗口以
+ `COMPUTER_TARGET_DENYLISTED` 被拒。审批卡片本身、安全输入与密码字段拒绝仍 NOT RUN。
### E2E-COMPUTER-USE-stale-basis-and-revision-fail-closed
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index fdc11e1ed..6f16854ad 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -5810,3 +5810,29 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
测试、shared 默认值测试,以及 `apps/desktop/test/computer-use-service.test.mjs`
(自动签发、停止拒绝、切换调用形状)。仍未经真机验证:`E2E-COMPUTER-USE-*` 闸门
依旧是 `NOT RUN`。
+
+## 2026-11-05 —— 无障碍窗口按窗口 id 对应,而不是按几何(D683)
+
+- D683 记录一次真机发现以及修它所用的私有符号。电脑操作的首次真机运行(macOS 15,
+ 台前调度开启)除了台前那个窗口以外,其他窗口全部被拒:`window_matches` 用几何把
+ `CGWindowList` 条目和 `AXUIElement` 对起来,而窗口服务器对不在台前的窗口报的是
+ 台前调度的**缩略图**几何,无障碍报的是真实几何——同一个窗口实测为 `37,607 121x137`
+ 对 `219,44 1568x1125`。所以在这个平台上几何不构成身份,该能力实际上不可用。
+- 现在的连接键是 `_AXUIElementGetWindow` 返回的窗口 id,与 `CGWindowList` 给出的是
+ 同一个数字。它未公开、自 10.5 起存在,平台上所有窗口管理工具都在用。它通过
+ `dlsym` 动态解析而不是链接,所以未来系统移除它只会退化为几何匹配,而不会导致启动
+ 失败;能读到但不相等的 id 是确定性的否定,直接拒绝。不引入新 crate,其余 FFI 面不变。
+- 授权现在携带无障碍的窗口框,而不是窗口服务器的,因为元素 bounds、坐标夹取、
+ `basis`、绘制光标与截取裁剪都在这个坐标系里。`measure` 仍从 `CGWindowList` 取身份
+ (`appKey`、标题),窗口打不开时回退到它的几何。
+- 同一次运行带出的两个小结论:自动授权现在优先选择**树确实能打开**的窗口
+ (`Desktop::can_open`,一次单节点探测),因为窗口服务器会把台前调度的表面列在用户
+ 窗口之前,绑上去只是白费一轮;读取失败也不再让授权留在读不了的窗口上
+ (`policy::inspect_bound` 回退绑定并保留 revision 推进)。
+- 探针本身是 `scripts/e2e-computer-use-device.mjs`,需 `PI_DESKTOP_COMPUTER_USE_DEVICE=1`
+ 显式开启,因为它会读取操作者的屏幕、也可能往其中一个窗口输入;不加 `--titles` 时
+ 不打印窗口标题。macOS 升级后重跑它:`_AXUIElementGetWindow` 哪天消失,就靠这个发现。
+- 覆盖:`computer::tests::an_automatic_grant_skips_a_window_whose_tree_cannot_be_opened`
+ 与 `a_window_that_cannot_be_read_does_not_become_the_bound_one`;对应逻辑本身是平台
+ 代码,只有真机探针覆盖。这次跑到与没跑到的部分见
+ `docs/implementation/computer-use-evidence.md`。
diff --git a/scripts/README.md b/scripts/README.md
index e3089b178..1ace2bb2b 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -58,6 +58,7 @@ The scenarios are specified in
| `e2e-transcript-cache.mjs` | `pnpm test:e2e:transcript-cache` | Isolated Host RPC regression for large transcript cache creation, append plus middle Task rewrite, legacy cache recovery, paging, message navigation, invalid UTF-8 recovery, and process restart |
| `e2e-plan-ui.mjs` | `pnpm test:e2e:plan-ui` | Plan approval through the rendered UI |
| `e2e-electron-boot.mjs` | `pnpm test:e2e:boot` | Electron boot probe |
+| `e2e-computer-use-device.mjs` | `PI_DESKTOP_COMPUTER_USE_DEVICE=1 node scripts/e2e-computer-use-device.mjs` | Real-device computer-use acceptance against host-core: capabilities, window enumeration and its order, the automatic desktop grant, a real accessibility inspection, a rebind, the self-target/denylist/unknown-window refusals, and the Stop cooldown. Opt-in because it reads the operator's screen; `--act-app "<app>"` dispatches one real action, `--deny "<app>"` proves the denylist, `--titles` prints window titles (withheld by default). macOS only until stage 2 |
| `e2e-provider-client-certificate.mjs` | `pnpm test:e2e:provider-client-certificate` | Isolated Electron 43 model discovery with optional client certificates, authenticated proxy routing, redirects and cancellation |
| `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` |
| `e2e-settings-scroll.mjs` | `pnpm test:e2e:settings-scroll` | Production Settings component navigation, search anchoring, focus-on-mount, and scroll behavior |
diff --git a/scripts/e2e-computer-use-device.mjs b/scripts/e2e-computer-use-device.mjs
new file mode 100644
index 000000000..b100b3e3c
--- /dev/null
+++ b/scripts/e2e-computer-use-device.mjs
@@ -0,0 +1,287 @@
+/**
+ * Real-device acceptance probe for computer use (ADR 0342, ADR 0344).
+ *
+ * The accessibility tree, the window enumeration, and event synthesis are
+ * platform work that fixtures cannot prove, so this script drives the real
+ * host-core binary against the machine it runs on: capabilities, the window
+ * list and its front-to-back order, the automatic desktop grant, one real
+ * inspection, a rebind, the refusals, and the Stop cooldown.
+ *
+ * It is opt-in because it reads the operator's own screen and, with `--act`,
+ * types into one of their windows. `PI_DESKTOP_COMPUTER_USE_DEVICE=1` is the
+ * authorization; nothing here runs in CI.
+ *
+ * PI_DESKTOP_COMPUTER_USE_DEVICE=1 node scripts/e2e-computer-use-device.mjs
+ * ... --titles also print window titles (off by default)
+ * ... --deny "<app name>" prove a user denylist entry refuses a bind
+ * ... --act-app "<app name>" dispatch ONE action into that app's window
+ * ... --act <targetId> the same, by an id from a previous listing
+ *
+ * Window titles are withheld unless `--titles` is passed, so a pasted log
+ * carries app identity without the contents of the operator's screen.
+ */
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+void root;
+
+if (process.env.PI_DESKTOP_COMPUTER_USE_DEVICE !== "1") {
+ console.error(
+ "refusing to run: this probe reads the operator's screen and may type into a window.\n"
+ + "Set PI_DESKTOP_COMPUTER_USE_DEVICE=1 to authorize it.",
+ );
+ process.exit(2);
+}
+if (process.platform !== "darwin") {
+ console.error(`no backend on ${process.platform} yet (stage 2); nothing to probe.`);
+ process.exit(2);
+}
+
+const args = process.argv.slice(2);
+const flag = (name) => {
+ const index = args.indexOf(name);
+ return index >= 0 ? (args[index + 1] ?? true) : undefined;
+};
+const showTitles = args.includes("--titles");
+const title = (value) => (showTitles ? value || "(no title)" : "(title withheld)");
+
+const SESSION = "computer-use-device-probe";
+const dataDir = await mkdtemp(join(tmpdir(), "cu-device-"));
+const host = new Host(resolveHostBinary(), dataDir, { quiet: true });
+const results = [];
+const record = (name, ok, detail) => {
+ results.push({ name, ok });
+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);
+};
+
+/** Expect a refusal, and name the code that came back. */
+const expectRefusal = async (name, code, method, params) => {
+ try {
+ await host.call(method, params);
+ record(name, false, "the call resolved instead of refusing");
+ } catch (error) {
+ record(name, error.errorCode === code, `${error.errorCode ?? "(no code)"}`);
+ }
+};
+
+try {
+ await host.start();
+ await host.call("settings.set", { computerUse: { enabled: true } });
+
+ const capabilities = await host.call("computer.capabilities", {});
+ console.log("capabilities", JSON.stringify(capabilities));
+ if (capabilities.accessibility !== "granted") {
+ console.error(
+ "\nAccessibility is not granted for the process running this probe, so inspection and input\n"
+ + "cannot be proven here. Grant it to this terminal in System Settings > Privacy & Security >\n"
+ + "Accessibility and run the probe again.",
+ );
+ process.exit(3);
+ }
+
+ const { targets } = await host.call("computer.listTargets", {});
+ console.log(`windows: ${targets.length}`);
+ for (const [index, target] of targets.entries()) {
+ console.log(
+ ` ${index}. ${target.appName} | ${title(target.title)} | ${target.refusedReason ?? "usable"} | ${target.targetId}`,
+ );
+ }
+ const firstUsable = targets.findIndex((target) => !target.refusedReason);
+ record(
+ "the window list carries refusals instead of dropping windows",
+ targets.length > 0 && firstUsable >= 0,
+ `${targets.filter((target) => target.refusedReason).length} refused`,
+ );
+
+ const grant = await host.call("computer.grantCreate", { sessionId: SESSION, origin: "agent" });
+ record(
+ "an automatic grant covers the desktop and binds the frontmost usable window",
+ grant.scope === "desktop" && grant.targetId === targets[firstUsable].targetId,
+ `scope=${grant.scope} bound=${grant.appKey} skipped=${firstUsable}`,
+ );
+ record(
+ "the grant takes the settings defaults, not a narrower unbuilt policy",
+ grant.inputPolicy === "autonomous-in-scope" && grant.capture === "a11y-only",
+ `${grant.inputPolicy} / ${grant.capture}`,
+ );
+
+ const inspection = await host.call("computer.inspect", { grantId: grant.grantId, sessionId: SESSION });
+ record(
+ "the real accessibility tree comes back with roles and actions",
+ inspection.nodes.length > 0 && inspection.fidelity === "full",
+ `${inspection.nodes.length} nodes, fidelity=${inspection.fidelity}`,
+ );
+ record(
+ "inspection reports whether a value exists, never the value",
+ inspection.nodes.every((node) => !("value" in node)),
+ "no node carries a value field",
+ );
+
+ // Re-listed immediately before the bind: overlay windows (Stage Manager, the
+ // Dock's helpers) come and go, and a vanished id is a scope violation rather
+ // than the rebind this step is trying to prove.
+ const fresh = (await host.call("computer.listTargets", {})).targets;
+ const candidates = fresh.filter(
+ (target) => !target.refusedReason && target.targetId !== grant.targetId,
+ );
+ if (candidates.length > 0) {
+ let rebound;
+ let lastCode;
+ for (const candidate of candidates) {
+ try {
+ rebound = await host.call("computer.inspect", {
+ grantId: grant.grantId,
+ sessionId: SESSION,
+ targetId: candidate.targetId,
+ });
+ break;
+ } catch (error) {
+ // Overlay windows vanish between two enumerations; that is the scope
+ // violation working, not the rebind failing. Try the next one.
+ lastCode = error.errorCode;
+ }
+ }
+ if (!rebound) console.log(`SKIP rebind — every candidate window went away mid-probe (${lastCode})`);
+ if (rebound) {
+ record(
+ "a rebind moves the revision, so every earlier uid stops validating",
+ rebound.revision > inspection.revision,
+ `revision ${inspection.revision} -> ${rebound.revision}`,
+ );
+ await expectRefusal(
+ "an action holding the pre-rebind revision is refused",
+ "COMPUTER_STALE_REVISION",
+ "computer.act",
+ {
+ grantId: grant.grantId,
+ sessionId: SESSION,
+ expectedRevision: inspection.revision,
+ action: { kind: "click", uid: rebound.nodes[0]?.uid ?? "0" },
+ },
+ );
+ }
+ } else {
+ console.log("SKIP rebind — no second usable window on screen");
+ }
+
+ const own = targets.find((target) => target.refusedReason === "self");
+ if (own) {
+ await expectRefusal(
+ "binding one of our own windows is refused",
+ "COMPUTER_SELF_TARGET_REFUSED",
+ "computer.inspect",
+ { grantId: grant.grantId, sessionId: SESSION, targetId: own.targetId },
+ );
+ } else {
+ console.log("SKIP self-target bind — no PI-Desktop window on screen");
+ }
+ await expectRefusal(
+ "binding a window that is not in the host's list is refused",
+ "COMPUTER_SCOPE_VIOLATION",
+ "computer.inspect",
+ { grantId: grant.grantId, sessionId: SESSION, targetId: "no-such-window" },
+ );
+
+ // `--act-app` resolves inside this run, because window ids change between
+ // runs and a stale id would read as a refusal rather than a missed target.
+ const actApp = flag("--act-app");
+ const actTarget = typeof actApp === "string"
+ ? (await host.call("computer.listTargets", {})).targets.find(
+ (target) => !target.refusedReason && target.appName.includes(actApp),
+ )?.targetId
+ : flag("--act");
+ if (typeof actApp === "string" && !actTarget) {
+ console.log(`SKIP act — no usable window from an app matching "${actApp}"`);
+ }
+ if (typeof actTarget === "string") {
+ const bound = await host.call("computer.inspect", {
+ grantId: grant.grantId,
+ sessionId: SESSION,
+ targetId: actTarget,
+ });
+ const editable = bound.nodes.find((node) => node.actions.includes("set_value"));
+ const clickable = bound.nodes.find((node) => node.actions.includes("click"));
+ const node = editable ?? clickable;
+ if (!node) {
+ console.log("SKIP act — that window exposes no actionable element");
+ } else {
+ const action = editable
+ ? { kind: "set_value", uid: node.uid, text: "PI-Desktop computer-use device probe" }
+ : { kind: "click", uid: node.uid };
+ const result = await host.call("computer.act", {
+ grantId: grant.grantId,
+ sessionId: SESSION,
+ expectedRevision: bound.revision,
+ action,
+ });
+ record(
+ "one action reaches the window through the platform accessibility action",
+ result.dispatched === "accessibility-action" && result.remainingBudget === grant.remainingBudget - 1,
+ `${action.kind} on ${node.role}, dispatched=${result.dispatched}, budget ${grant.remainingBudget} -> ${result.remainingBudget}`,
+ );
+ }
+ } else {
+ console.log("SKIP act — pass --act <targetId> to dispatch one real action");
+ }
+
+ const denyApp = flag("--deny");
+ if (typeof denyApp === "string") {
+ await host.call("computer.grantRevoke", { reason: "probe-denylist-setup" });
+ await host.call("settings.set", { computerUse: { enabled: true, denylist: [denyApp] } });
+ const listed = (await host.call("computer.listTargets", {})).targets.find((target) =>
+ target.appName.includes(denyApp),
+ );
+ record(
+ "a denylisted window is listed with its reason",
+ listed?.refusedReason === "denylisted",
+ `${listed?.appName ?? "not found"} -> ${listed?.refusedReason ?? "none"}`,
+ );
+ const denyGrant = await host.call("computer.grantCreate", { sessionId: SESSION, origin: "user" });
+ record(
+ "the automatic grant does not bind a denylisted window",
+ denyGrant.targetId !== listed?.targetId,
+ `bound ${denyGrant.appKey}`,
+ );
+ if (listed) {
+ await expectRefusal(
+ "binding a denylisted window is refused",
+ "COMPUTER_TARGET_DENYLISTED",
+ "computer.inspect",
+ { grantId: denyGrant.grantId, sessionId: SESSION, targetId: listed.targetId },
+ );
+ }
+ await host.call("settings.set", { computerUse: { enabled: true, denylist: [] } });
+ } else {
+ console.log("SKIP denylist — pass --deny \"<app name>\" to prove it on a real window");
+ }
+
+ await host.call("computer.grantRevoke", { reason: "user" });
+ await expectRefusal(
+ "the agent cannot re-grant itself inside the Stop cooldown",
+ "COMPUTER_STOPPED_BY_USER",
+ "computer.grantCreate",
+ { sessionId: SESSION, origin: "agent" },
+ );
+ const userGrant = await host.call("computer.grantCreate", { sessionId: SESSION, origin: "user" });
+ record(
+ "the user's own request clears the cooldown immediately",
+ userGrant.scope === "desktop",
+ `scope=${userGrant.scope}`,
+ );
+ await host.call("computer.grantRevoke", { reason: "probe-cleanup" });
+
+ const failed = results.filter((result) => !result.ok);
+ console.log(`\n${results.length - failed.length} / ${results.length} device checks passed`);
+ if (failed.length > 0) {
+ console.error("failed: " + failed.map((result) => result.name).join("; "));
+ process.exitCode = 1;
+ }
+} finally {
+ await host.stop().catch(() => undefined);
+ await rm(dataDir, { recursive: true, force: true });
+}