Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(cu): foreground target guard + actuation hardening across click/drag/type tools
Ruben Lütkeef3e5de6718b
diff --git a/jarvis/cu/actuate/__init__.py b/jarvis/cu/actuate/__init__.pyindex 86b975df1d..42aeeef33f 100644--- a/jarvis/cu/actuate/__init__.py+++ b/jarvis/cu/actuate/__init__.py@@ -19,6 +19,8 @@ from jarvis.cu.actuate.base import (ActuationUnavailable,Actuator,get_actuator,+ verified_click,+ verified_drag,verified_move,)@@ -28,5 +30,7 @@ __all__ = ["Actuator","LANDING_TOLERANCE","get_actuator",+ "verified_click",+ "verified_drag","verified_move",]diff --git a/jarvis/cu/actuate/base.py b/jarvis/cu/actuate/base.pyindex d941480292..725699039b 100644--- a/jarvis/cu/actuate/base.py+++ b/jarvis/cu/actuate/base.py@@ -18,6 +18,7 @@ import abcimport loggingimport osimport sys+from collections.abc import Callablefrom dataclasses import dataclasslogger = logging.getLogger(__name__)@@ -26,6 +27,30 @@ logger = logging.getLogger(__name__)#: 2 units absorbs sub-pixel rounding; a real mapping bug is off by 10s-100s.LANDING_TOLERANCE = 2+# Platform-neutral vocabulary accepted at the tool boundary. Backends may map+# aliases differently (``cmd`` is Command on macOS and Super on X11), but the+# shared validation must not reject a key before the selected backend sees it.+_NAMED_KEYS = frozenset({+ "ctrl", "control", "shift", "alt", "option", "menu",+ "win", "windows", "lwin", "rwin", "cmd", "command", "meta", "super",+ "esc", "escape", "enter", "return", "tab", "space", "spacebar",+ "backspace", "back", "delete", "del", "insert", "ins", "home", "end",+ "pageup", "pgup", "pagedown", "pgdn", "left", "up", "right", "down",+ "capslock",+ *{f"f{i}" for i in range(1, 13)},+ *{f"numpad{i}" for i in range(10)},+ "multiply", "add", "subtract", "decimal", "divide",+})+++def is_known_key_name(key: str) -> bool:+ """Whether ``key`` belongs to the cross-platform Computer-Use vocabulary."""+ normalized = str(key).strip().lower()+ return bool(normalized) and (+ normalized in _NAMED_KEYS+ or (len(normalized) == 1 and normalized.isprintable())+ )+class ActuationUnavailable(RuntimeError):"""No input backend can act on this host (headless, Wayland, deps absent).@@ -93,8 +118,8 @@ def verified_move("""Move the cursor to ``(x, y)`` and verify it landed.One retry: transient focus/animation can eat the first positioning. When- the cursor position is unreadable the move is trusted (``landed=None``) —- refusing to act on an unreadable-but-working host would brick CU there.+ an unreadable cursor is retried once and then refused: without read-back,+ Computer-Use cannot prove where the following button event would land.The tiny sleep between inject and read is load-bearing: injected inputpasses through the OS input queue, so an immediate ``cursor_pos`` read@@ -103,22 +128,56 @@ def verified_move("""import time # noqa: PLC0415+ # A virtual desktop is a bounding rectangle, but real displays can form an+ # L-shape with dead gaps. Never move/click into such a gap when live display+ # geometry is available; an empty list means headless/probe-unavailable and+ # remains the backend capability check's responsibility.+ try:+ from jarvis.cu.geometry import ( # noqa: PLC0415+ list_monitors,+ point_on_physical_display,+ )++ monitors = list_monitors()+ if monitors and not point_on_physical_display(x, y, monitors):+ return ActResult(+ ok=False,+ detail=(+ f"target ({x},{y}) is outside every physical display — "+ "refusing to act in a virtual-desktop gap"+ ),+ landed=None,+ )+ except Exception: # noqa: BLE001 — actuation backend remains authoritative+ logger.debug("physical-display target validation failed", exc_info=True)+last: tuple[int, int] | None = Nonefor attempt in (1, 2):actuator.move(int(x), int(y))time.sleep(0.02)last = actuator.cursor_pos()if last is None:- return ActResult(- ok=True,- detail="cursor position unreadable — move unverified",- landed=None,+ logger.debug(+ "[cu] cursor unreadable after move to (%d,%d) (attempt %d)",+ x,+ y,+ attempt,)+ continueif abs(last[0] - int(x)) <= tolerance and abs(last[1] - int(y)) <= tolerance:return ActResult(ok=True, detail=f"landed at {last}", landed=last)logger.debug("[cu] move to (%d,%d) landed at %s (attempt %d)", x, y, last, attempt,)+ if last is None:+ return ActResult(+ ok=False,+ detail=(+ "cursor position remained unreadable after two move attempts; "+ "refusing to emit a pointer event"+ ),+ landed=None,+ )return ActResult(ok=False,detail=(@@ -129,6 +188,146 @@ def verified_move()+def verified_click(+ actuator: Actuator,+ x: int,+ y: int,+ *,+ button: str = "left",+ double: bool = False,+ pre_action_check: Callable[[], bool] | None = None,+) -> ActResult:+ """Verify pointer landing before emitting any button-down event."""+ landing = verified_move(actuator, x, y)+ if not landing.ok:+ return landing+ click_at_cursor = getattr(actuator, "click_at_cursor", None)+ if not callable(click_at_cursor):+ return ActResult(+ ok=False,+ detail=(+ "input backend lacks a safe at-cursor click primitive; "+ "refusing an unverified second move"+ ),+ landed=landing.landed,+ )+ if pre_action_check is not None and not pre_action_check():+ return ActResult(+ ok=False,+ detail=(+ "foreground window changed during cursor movement; refusing "+ "to press a mouse button"+ ),+ landed=landing.landed,+ )+ click_at_cursor(+ button=button,+ double=double,+ expected=(int(x), int(y)),+ )+ return ActResult(ok=True, detail=landing.detail, landed=landing.landed)+++def verified_drag(+ actuator: Actuator,+ x1: int,+ y1: int,+ x2: int,+ y2: int,+ *,+ duration_s: float = 0.4,+ tolerance: int = LANDING_TOLERANCE,+ pre_action_check: Callable[[], bool] | None = None,+) -> ActResult:+ """Refuse a drag unless its start lands, then verify its released endpoint."""+ # Validate the destination before button-down. A virtual desktop's bounding+ # rectangle can contain dead gaps between L-shaped displays; discovering+ # that only after dragging would already have acted at an unsafe point.+ try:+ from jarvis.cu.geometry import ( # noqa: PLC0415+ list_monitors,+ point_on_physical_display,+ segment_on_physical_displays,+ )++ monitors = list_monitors()+ if monitors and not point_on_physical_display(x2, y2, monitors):+ return ActResult(+ ok=False,+ detail=(+ f"drag destination ({x2},{y2}) is outside every physical "+ "display — refusing to drag into a virtual-desktop gap"+ ),+ landed=None,+ )+ if monitors and not segment_on_physical_displays(+ x1, y1, x2, y2, monitors,+ ):+ return ActResult(+ ok=False,+ detail=(+ "drag path crosses a virtual-desktop gap; refusing to "+ "hold a mouse button across disconnected displays"+ ),+ landed=None,+ )+ except Exception: # noqa: BLE001 — backend validation remains authoritative+ logger.debug("drag destination display validation failed", exc_info=True)++ start = verified_move(actuator, x1, y1, tolerance=tolerance)+ if not start.ok:+ return start+ drag_from_cursor = getattr(actuator, "drag_from_cursor", None)+ if not callable(drag_from_cursor):+ return ActResult(+ ok=False,+ detail=(+ "input backend lacks a safe at-cursor drag primitive; "+ "refusing an unverified second start move"+ ),+ landed=start.landed,+ )+ if pre_action_check is not None and not pre_action_check():+ return ActResult(+ ok=False,+ detail=(+ "foreground window changed during drag positioning; refusing "+ "to press a mouse button"+ ),+ landed=start.landed,+ )+ drag_from_cursor(+ x1, y1, x2, y2, duration_s=max(0.0, duration_s),+ )+ import time # noqa: PLC0415++ end: tuple[int, int] | None = None+ for _attempt in (1, 2):+ # Quartz/SendInput posting is queued just like a plain move. Give the+ # release endpoint a bounded chance to become visible before judging.+ time.sleep(0.02)+ end = actuator.cursor_pos()+ if end is not None and (+ abs(end[0] - int(x2)) <= tolerance+ and abs(end[1] - int(y2)) <= tolerance+ ):+ return ActResult(ok=True, detail=f"drag ended at {end}", landed=end)+ if end is None:+ return ActResult(+ ok=False,+ detail="drag endpoint is unreadable, so its landing cannot be verified",+ landed=None,+ )+ return ActResult(+ ok=False,+ detail=(+ f"drag to ({x2},{y2}) landed at {end} — coordinate-space mismatch "+ "(DPI/monitor mapping)"+ ),+ landed=end,+ )++# ---------------------------------------------------------------------------# Backend selection# ---------------------------------------------------------------------------@@ -149,6 +348,47 @@ _NO_BACKEND_MSG = ()+def _require_macos_input_permissions() -> None:+ """Fail closed unless macOS currently permits synthetic input.++ TCC grants can be revoked while Jarvis is running, so this deliberately+ creates a fresh permission port and probes both grants for every action.+ No result is cached in the actuator layer.+ """+ if sys.platform != "darwin":+ return++ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ PermissionState,+ get_system_permission_port,+ )++ port = get_system_permission_port()+ requirements = (+ (PermissionId.ACCESSIBILITY, "Accessibility"),+ (PermissionId.EVENT_POSTING, "Input Control"),+ )+ missing: list[str] = []+ for permission_id, label in requirements:+ if not port.runtime_access_granted(permission_id):+ state = port.state(permission_id)+ detail = (+ state.value+ if state is not PermissionState.GRANTED+ else "grant belongs to an unstable app identity or needs restart"+ )+ missing.append(f"{label} ({detail})")+ if missing:+ joined = ", ".join(missing)+ raise ActuationUnavailable(+ "Cannot control the mouse or keyboard on macOS because these "+ f"permissions are not granted: {joined}. Open Personal Jarvis "+ "> Settings > Permissions (or System Settings > Privacy & "+ "Security), grant the listed access, then retry."+ )++def get_actuator() -> Actuator:"""Resolve the platform input backend by runtime capability.@@ -156,6 +396,8 @@ def get_actuator() -> Actuator:when the host cannot receive synthetic input. Never returns a backendthat is known-broken for the session type."""+ _require_macos_input_permissions()+if os.name == "nt":from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415diff --git a/jarvis/cu/actuate/posix.py b/jarvis/cu/actuate/posix.pyindex d91dee4590..26862fcd70 100644--- a/jarvis/cu/actuate/posix.py+++ b/jarvis/cu/actuate/posix.py@@ -15,10 +15,15 @@ there); this module only ever runs on X11 or macOS.from __future__ import annotationsimport logging+import sysimport timefrom typing import Any-from jarvis.cu.actuate.base import ActuationUnavailable, Actuator+from jarvis.cu.actuate.base import (+ LANDING_TOLERANCE,+ ActuationUnavailable,+ Actuator,+)logger = logging.getLogger(__name__)@@ -40,10 +45,10 @@ def _pynput_key_table(keyboard: Any) -> dict[str, Any]:names = {"ctrl": "ctrl", "control": "ctrl","shift": "shift",- "alt": "alt", "menu": "alt",+ "alt": "alt", "option": "alt", "menu": "alt",# "win" is the Super/Command key off-Windows."win": "cmd", "windows": "cmd", "lwin": "cmd", "cmd": "cmd",- "command": "cmd", "super": "cmd",+ "command": "cmd", "meta": "cmd", "super": "cmd","esc": "esc", "escape": "esc","enter": "enter", "return": "enter","tab": "tab",@@ -111,6 +116,16 @@ class PosixActuator(Actuator):def cursor_pos(self) -> tuple[int, int] | None:try:+ if sys.platform == "darwin":+ # Use the same Quartz global coordinate space as CGEventPost,+ # CGDisplayBounds/mss and AX window geometry. pynput's macOS+ # getter converts NSEvent coordinates through the main+ # display's pixel height, which can diverge on Retina and+ # vertically arranged multi-monitor desktops.+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ point = Quartz.CGEventGetLocation(Quartz.CGEventCreate(None))+ return (int(point.x), int(point.y))if self._mouse is not None:x, y = self._mouse.positionelse:@@ -122,6 +137,17 @@ class PosixActuator(Actuator):return Nonedef move(self, x: int, y: int) -> None:+ if sys.platform == "darwin":+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ event = Quartz.CGEventCreateMouseEvent(+ None,+ Quartz.kCGEventMouseMoved,+ (int(x), int(y)),+ Quartz.kCGMouseButtonLeft,+ )+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)+ returnif self._mouse is not None:self._mouse.position = (int(x), int(y))else:@@ -130,31 +156,75 @@ class PosixActuator(Actuator):def click(self, x: int, y: int, *, button: str = "left", double: bool = False,) -> None:+ self.move(x, y)+ self.click_at_cursor(+ button=button,+ double=double,+ expected=(int(x), int(y)),+ )++ def click_at_cursor(+ self,+ *,+ button: str = "left",+ double: bool = False,+ expected: tuple[int, int] | None = None,+ ) -> None:+ """Press and release at the current, already-verified cursor position."""b = button.lower()if b not in ("left", "right", "middle"):raise ValueError(f"Unknown mouse button: {button!r}. Allowed: left/right/middle",)- self.move(x, y)+ current = self.cursor_pos()+ if current is None or (+ expected is not None+ and (+ abs(current[0] - expected[0]) > LANDING_TOLERANCE+ or abs(current[1] - expected[1]) > LANDING_TOLERANCE+ )+ ):+ raise RuntimeError(+ "cursor moved after landing verification; refusing to click",+ )+ if sys.platform == "darwin":+ self._quartz_click(current, b, double=double)+ returnif self._mouse is not None:self._mouse.click(self._buttons[b], 2 if double else 1)else:self._pyautogui.click(- x=int(x), y=int(y), clicks=2 if double else 1, button=b,+ clicks=2 if double else 1, button=b,)def drag(self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,) -> None:+ self.move(x1, y1)+ self.drag_from_cursor(x1, y1, x2, y2, duration_s=duration_s)++ def drag_from_cursor(+ self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,+ ) -> None:+ """Drag from the current, already-verified position to ``(x2, y2)``."""+ current = self.cursor_pos()+ if current is None or (+ abs(current[0] - int(x1)) > LANDING_TOLERANCE+ or abs(current[1] - int(y1)) > LANDING_TOLERANCE+ ):+ raise RuntimeError(+ "cursor moved after drag-start verification; refusing to drag",+ )+ if sys.platform == "darwin":+ self._quartz_drag(current, (int(x2), int(y2)), duration_s)+ returnif self._mouse is None:- self._pyautogui.moveTo(int(x1), int(y1))self._pyautogui.dragTo(int(x2), int(y2), duration=max(0.0, duration_s), button="left",)returnsteps = max(2, min(40, int(duration_s * 60)))pause = max(0.0, duration_s) / steps- self._mouse.position = (int(x1), int(y1))self._mouse.press(self._buttons["left"])try:for i in range(1, steps + 1):@@ -181,6 +251,18 @@ class PosixActuator(Actuator):self.move(int(x), int(y))dx = n if d == "right" else -n if d == "left" else 0dy = n if d == "up" else -n if d == "down" else 0+ if sys.platform == "darwin":+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ event = Quartz.CGEventCreateScrollWheelEvent(+ None,+ Quartz.kCGScrollEventUnitLine,+ 2,+ dy,+ dx,+ )+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)+ returnif self._mouse is not None:self._mouse.scroll(dx, dy)elif dx:@@ -194,7 +276,17 @@ class PosixActuator(Actuator):expanded = expand_combo_keys([str(k) for k in keys])if self._keyboard is None:- self._pyautogui.hotkey(*[k.lower() for k in expanded])+ aliases = {"cmd", "command", "meta", "super", "win", "windows", "lwin"}+ mapped: list[str] = []+ for key in expanded:+ normalized = key.strip().lower()+ if normalized in aliases:+ mapped.append("command" if sys.platform == "darwin" else "winleft")+ elif normalized == "option":+ mapped.append("alt")+ else:+ mapped.append(normalized)+ self._pyautogui.hotkey(*mapped)returnresolved: list[Any] = []for k in expanded:@@ -210,6 +302,84 @@ class PosixActuator(Actuator):for r in reversed(resolved):self._keyboard.release(r)+ @staticmethod+ def _quartz_button_spec(quartz: Any, button: str) -> tuple[Any, Any, Any, Any]:+ return {+ "left": (+ quartz.kCGEventLeftMouseDown,+ quartz.kCGEventLeftMouseUp,+ quartz.kCGEventLeftMouseDragged,+ quartz.kCGMouseButtonLeft,+ ),+ "right": (+ quartz.kCGEventRightMouseDown,+ quartz.kCGEventRightMouseUp,+ quartz.kCGEventRightMouseDragged,+ quartz.kCGMouseButtonRight,+ ),+ "middle": (+ quartz.kCGEventOtherMouseDown,+ quartz.kCGEventOtherMouseUp,+ quartz.kCGEventOtherMouseDragged,+ quartz.kCGMouseButtonCenter,+ ),+ }[button]++ @classmethod+ def _quartz_click(+ cls,+ point: tuple[int, int],+ button: str,+ *,+ double: bool,+ ) -> None:+ """Post macOS button events in Quartz global display coordinates."""+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ down, up, _dragged, button_id = cls._quartz_button_spec(Quartz, button)+ for click_state in range(1, 3 if double else 2):+ for event_type in (down, up):+ event = Quartz.CGEventCreateMouseEvent(+ None, event_type, point, button_id,+ )+ Quartz.CGEventSetIntegerValueField(+ event,+ Quartz.kCGMouseEventClickState,+ click_state,+ )+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)++ @classmethod+ def _quartz_drag(+ cls,+ start: tuple[int, int],+ end: tuple[int, int],+ duration_s: float,+ ) -> None:+ """Post a left-button drag entirely in Quartz global coordinates."""+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ down, up, dragged, button_id = cls._quartz_button_spec(Quartz, "left")+ press = Quartz.CGEventCreateMouseEvent(None, down, start, button_id)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, press)+ steps = max(2, min(40, int(max(0.0, duration_s) * 60)))+ pause = max(0.0, duration_s) / steps+ try:+ for index in range(1, steps + 1):+ point = (+ int(start[0] + (end[0] - start[0]) * index / steps),+ int(start[1] + (end[1] - start[1]) * index / steps),+ )+ event = Quartz.CGEventCreateMouseEvent(+ None, dragged, point, button_id,+ )+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)+ if pause:+ time.sleep(pause)+ finally:+ release = Quartz.CGEventCreateMouseEvent(None, up, end, button_id)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, release)+def type_text(self, text: str, *, delay_s: float = 0.02) -> None:if self._keyboard is None:self._pyautogui.typewrite(text, interval=delay_s)diff --git a/jarvis/cu/actuate/windows.py b/jarvis/cu/actuate/windows.pyindex e133be05b2..bc9b5369f1 100644--- a/jarvis/cu/actuate/windows.py+++ b/jarvis/cu/actuate/windows.py@@ -24,7 +24,7 @@ import loggingimport timefrom types import SimpleNamespace-from jarvis.cu.actuate.base import Actuator+from jarvis.cu.actuate.base import Actuator, is_known_key_namefrom jarvis.cu.geometry import input_spacelogger = logging.getLogger(__name__)@@ -55,8 +55,9 @@ _MOUSE_FLAGS_UP: dict[str, int] = {_VK_TABLE: dict[str, int] = {"ctrl": 0x11, "control": 0x11,"shift": 0x10,- "alt": 0x12, "menu": 0x12,+ "alt": 0x12, "option": 0x12, "menu": 0x12,"win": 0x5B, "windows": 0x5B, "lwin": 0x5B, "rwin": 0x5C,+ "cmd": 0x5B, "command": 0x5B, "meta": 0x5B, "super": 0x5B,"esc": 0x1B, "escape": 0x1B,"enter": 0x0D, "return": 0x0D,"tab": 0x09,@@ -112,7 +113,7 @@ def expand_combo_keys(keys: list[str]) -> list[str]:t = str(token).strip()if "+" in t and len(t) > 1:parts = [p.strip() for p in t.split("+") if p.strip()]- if len(parts) >= 2 and all(resolve_vk(p) is not None for p in parts):+ if len(parts) >= 2 and all(is_known_key_name(p) for p in parts):out.extend(parts)continueout.append(str(token))@@ -255,7 +256,13 @@ class WindowsActuator(Actuator):events.append(self._mouse_input(0, 0, 0, _MOUSE_FLAGS_UP[b]))self._send(events)- def click_at_cursor(self, *, button: str = "left", double: bool = False) -> None:+ def click_at_cursor(+ self,+ *,+ button: str = "left",+ double: bool = False,+ expected: tuple[int, int] | None = None,+ ) -> None:"""Press+release at the CURRENT cursor position (no positioning).For callers that already positioned the cursor themselves (e.g. the@@ -266,6 +273,17 @@ class WindowsActuator(Actuator):raise ValueError(f"Unknown mouse button: {button!r}. Allowed: left/right/middle",)+ current = self.cursor_pos()+ if current is None or (+ expected is not None+ and (+ abs(current[0] - expected[0]) > 2+ or abs(current[1] - expected[1]) > 2+ )+ ):+ raise RuntimeError(+ "cursor moved after landing verification; refusing to click",+ )with input_space():events = []for _ in range(2 if double else 1):@@ -276,10 +294,21 @@ class WindowsActuator(Actuator):def drag(self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,) -> None:+ self.move(x1, y1)+ self.drag_from_cursor(x1, y1, x2, y2, duration_s=duration_s)++ def drag_from_cursor(+ self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,+ ) -> None:+ """Drag from the current, already-verified cursor position."""+ current = self.cursor_pos()+ if current is None or abs(current[0] - x1) > 2 or abs(current[1] - y1) > 2:+ raise RuntimeError(+ "cursor moved after drag-start verification; refusing to drag",+ )steps = max(2, min(40, int(duration_s * 60)))pause = max(0.0, duration_s) / stepswith input_space():- self._send([self._abs_move_event(x1, y1)])self._send([self._mouse_input(0, 0, 0, _MOUSE_FLAGS_DOWN["left"])])try:for i in range(1, steps + 1):diff --git a/jarvis/cu/capture.py b/jarvis/cu/capture.pyindex d84cdc4198..e06dc0ed6b 100644--- a/jarvis/cu/capture.py+++ b/jarvis/cu/capture.py@@ -62,6 +62,39 @@ class Grabber(Protocol):def __call__(self, bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]: ...+def _require_macos_screen_recording_permission() -> None:+ """Fail closed unless macOS currently permits screen capture.++ The native state is probed before every grab, not only at mission start,+ because a user can revoke Screen Recording while Jarvis is running.+ """+ from jarvis.platform import detect_platform # noqa: PLC0415++ if detect_platform() != "darwin":+ return++ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ PermissionState,+ get_system_permission_port,+ )++ port = get_system_permission_port()+ if not port.runtime_access_granted(PermissionId.SCREEN_RECORDING):+ state = port.state(PermissionId.SCREEN_RECORDING)+ detail = (+ state.value+ if state is not PermissionState.GRANTED+ else "grant belongs to an unstable app identity or needs restart"+ )+ raise RuntimeError(+ "Cannot capture the screen on macOS because Screen Recording "+ f"permission is not ready ({detail}). Open Personal Jarvis "+ "> Settings > Permissions (or System Settings > Privacy & "+ "Security > Screen Recording), grant access, then retry."+ )++def mss_grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:"""Default grabber via mss, inside the thread DPI pin."""import mss # noqa: PLC0415@@ -330,6 +363,7 @@ def capture_stable_frame(grab: Grabber | None = None,blob_dir: Path | None = None,sleep: Callable[[float], None] = time.sleep,+ capture_guard: Callable[[], bool] | None = None,) -> Frame:"""Capture the monitor, waiting briefly for the UI to settle.@@ -344,15 +378,30 @@ def capture_stable_frame(plus the encoded image size: the one central translation."""grabber = grab or grabber_for(monitor)++ def guarded_grab() -> tuple[tuple[int, int], bytes]:+ if capture_guard is not None and not capture_guard():+ raise RuntimeError(+ "foreground window changed before screen capture",+ )+ raw = grabber(monitor.bbox)+ if capture_guard is not None and not capture_guard():+ raise RuntimeError(+ "foreground window changed during screen capture",+ )+ return raw+deadline = time.monotonic() + max(0.0, stability_timeout_s)- current = grabber(monitor.bbox)+ _require_macos_screen_recording_permission()+ current = guarded_grab()stable = Falsewhile True:remaining = deadline - time.monotonic()if remaining <= 0:breaksleep(min(max(0.01, stability_interval_s), remaining))- nxt = grabber(monitor.bbox)+ _require_macos_screen_recording_permission()+ nxt = guarded_grab()if not frames_differ(current, nxt):current = nxtstable = True@@ -403,11 +452,15 @@ def grab_region() -> tuple[tuple[int, int], bytes] | None:"""One raw region grab for pre/post verification diffs.- Returns ``None`` on any failure (headless, transient GDI error) so- verification degrades to "cannot tell" instead of killing the action.+ Returns ``None`` on capture failures (headless, transient GDI error, or a+ revoked macOS grant) so pixel-effect verification can report "cannot+ tell". The Computer-Use dispatcher independently rechecks Screen Recording+ immediately before every action, so this degradation cannot permit blind+ input after a revoked grant."""grabber = grab or mss_grabtry:+ _require_macos_screen_recording_permission()return grabber(bbox)except Exception: # noqa: BLE001logger.debug("[cu] region grab failed (non-fatal)", exc_info=True)diff --git a/jarvis/cu/conventions.py b/jarvis/cu/conventions.pyindex 0946bf30e6..60c9f24d43 100644--- a/jarvis/cu/conventions.py+++ b/jarvis/cu/conventions.py@@ -23,6 +23,7 @@ from __future__ import annotationsimport jsonimport loggingimport re+import sysfrom typing import Anyfrom jarvis.cu.geometry import CoordinateConvention@@ -121,7 +122,9 @@ def action_grammar_block() -> str:"into the FOCUSED field; set clear_first true to replace existing ""content (address bars, search boxes)\n"' {"action": "key", "keys": ["enter"]} key or combo, e.g. '- '["ctrl","t"]\n'+ '["ctrl","t"]. The current host is '+ f'{sys.platform!r}: use ["cmd", ...] for standard macOS shortcuts '+ 'and ["ctrl", ...] on Windows/Linux; never substitute ctrl for Command.\n'' {"action": "scroll", "direction": "up|down|left|right", ''"amount": <notches>, "x": <num>, "y": <num>} x/y optional\n'' {"action": "drag", "x": <num>, "y": <num>, "x2": <num>, 'diff --git a/jarvis/cu/engine.py b/jarvis/cu/engine.pyindex 97aa83e211..1d60b39c85 100644--- a/jarvis/cu/engine.py+++ b/jarvis/cu/engine.py@@ -59,8 +59,15 @@ from jarvis.cu.geometry import (CoordinateConvention,CoordinateMapper,MonitorInfo,+ list_monitors,+ monitor_topology_signature,)from jarvis.cu.ledger import ActionLedger+from jarvis.cu.target_guard import (+ foreground_matches,+ read_foreground_target,+ window_signature,+)from jarvis.cu.verify import (crop_raw,foreground_ui_snapshot,@@ -293,10 +300,35 @@ def _foreground_title() -> str:return ""+def _window_state_signature(+ window: Any,+ rect: tuple[int, int, int, int] | None,+) -> tuple[Any, ...]:+ """Stable-enough foreground identity for capture-to-action race checks."""+ return window_signature(window, rect)+++async def _live_window_state_signature() -> tuple[Any, ...]:+ """Read foreground identity and geometry as one fail-closed check."""+ return (await asyncio.to_thread(read_foreground_target)).signature++async def _dispatch_tool(ctx: Any, tool_name: str, args: dict[str, Any], trace_id: Any,) -> tuple[bool, str]:"""Run one action through the ToolExecutor (AP-3 choke point)."""+ # A macOS Screen Recording grant can be revoked after perception but+ # before actuation. Re-probe at the final dispatcher choke point so no CU+ # action can run against a screen Jarvis is no longer allowed to observe.+ try:+ from jarvis.cu.capture import ( # noqa: PLC0415+ _require_macos_screen_recording_permission,+ )++ _require_macos_screen_recording_permission()+ except RuntimeError as exc:+ return False, str(exc)+tools = ctx.tools or {}tool = tools.get(tool_name)if tool is None:@@ -390,6 +422,7 @@ async def _zoom_refine_point(*,goal: str,target: str,+ expected_window_signature: tuple[Any, ...],) -> tuple[int, int] | None:"""One coarse-to-fine grounding round after a VERIFIED miss.@@ -403,9 +436,14 @@ async def _zoom_refine_point(import json as _json # noqa: PLC0415import re as _re # noqa: PLC0415+ if await _live_window_state_signature() != expected_window_signature:+ return Nonebbox = frame.mapper.region_around(int(x), int(y), _REFINE_RADIUS)raw = await asyncio.to_thread(grab_region, bbox)- if raw is None:+ if (+ raw is None+ or await _live_window_state_signature() != expected_window_signature+ ):return Nonetry:from PIL import Image # noqa: PLC0415@@ -436,6 +474,8 @@ async def _zoom_refine_point(except Exception: # noqa: BLE001 — refine is strictly best-effortlog.debug("[cu] zoom refine call failed", exc_info=True)return None+ if await _live_window_state_signature() != expected_window_signature:+ return Nonecleaned = (reply.text or "").strip()fence = _re.search(r"```(?:json)?\s*(.+?)\s*```", cleaned, _re.DOTALL)if fence is not None:@@ -622,6 +662,20 @@ async def run_cu_loop(except Exception: # noqa: BLE001 — normalize is best-effortlog.debug("[cu] window normalize failed", exc_info=True)try:+ captured_displays = await asyncio.to_thread(list_monitors)+ if not captured_displays:+ raise RuntimeError(+ "no physical displays are available for Computer-Use",+ )+ captured_topology = monitor_topology_signature(captured_displays)+ pre_capture_target = await asyncio.to_thread(read_foreground_target)+ pre_capture_window_signature = pre_capture_target.signature++ def capture_identity_guard(+ expected: tuple[Any, ...] = pre_capture_window_signature,+ ) -> bool:+ return foreground_matches(expected)+monitor = await asyncio.to_thread(select_capture_target,monitor_policy,@@ -633,12 +687,46 @@ async def run_cu_loop(monitor,max_dimension=image_cfg.max_dimension,blob_dir=image_cfg.blob_dir,+ capture_guard=capture_identity_guard,+ )+ snapshot_coro = foreground_ui_snapshot(+ observation_guard=capture_identity_guard,)- snapshot_coro = foreground_ui_snapshot()frame, (labels, field_hint, handoff, clickables) = await asyncio.wait_for(asyncio.gather(frame_coro, snapshot_coro),timeout=_OBSERVE_TIMEOUT_S,)+ if captured_topology:+ live_topology = monitor_topology_signature(+ await asyncio.to_thread(list_monitors),+ )+ if live_topology != captured_topology:+ raise RuntimeError(+ "display topology changed during capture; retrying with fresh geometry"+ )+ captured_target = await asyncio.to_thread(read_foreground_target)+ captured_window = captured_target.window+ captured_window_rect = captured_target.rect+ captured_window_signature = captured_target.signature+ if captured_window_signature[0] == "none":+ raise RuntimeError(+ "foreground window identity is unavailable; refusing "+ "unbound Computer-Use input"+ )+ if captured_window_signature != pre_capture_window_signature:+ raise RuntimeError(+ "foreground window changed during capture; retrying with a fresh frame"+ )+ if monitor.window_handle is not None and (+ captured_window is None+ or captured_window.handle != monitor.window_handle+ or captured_window_rect != (+ monitor.left, monitor.top, monitor.width, monitor.height,+ )+ ):+ raise RuntimeError(+ "foreground window changed during capture; retrying with a fresh frame"+ )except Exception as exc: # noqa: BLE001 — capture is inherently flakyobserve_failures += 1log.warning("[cu] observe failed (step %d): %s", step_idx, exc)@@ -857,9 +945,10 @@ async def run_cu_loop(return# -- pointer staleness rule ------------------------------------ is_pointer = kind in ("click", "drag") or (- kind == "scroll" and "x" in action- )+ # Scrolling always targets the pointer's current surface. Treat it+ # as a pointer action even when the model omitted coordinates; the+ # omission is resolved to this frame's capture center below.+ is_pointer = kind in ("click", "click_element", "drag", "scroll")if is_pointer and pointer_used:history.append(f"step {step_idx}: {_summarize_action(action)} SKIPPED — "@@ -902,13 +991,32 @@ async def run_cu_loop(resolved_xy = frame.mapper.model_to_screen(action["x"], action["y"], convention,)- elif kind == "scroll" and "x" in action:- sx, sy = frame.mapper.model_to_screen(- action["x"], action["y"], convention,- )+ elif kind == "scroll":+ if "x" in action:+ sx, sy = frame.mapper.model_to_screen(+ action["x"], action["y"], convention,+ )+ else:+ # A stale cursor can sit on a different monitor. Ground a+ # coordinate-less scroll in the center of the window or+ # monitor that THIS screenshot represents.+ sx = monitor.left + max(0, monitor.width) // 2+ sy = monitor.top + max(0, monitor.height) // 2action = {**action, "x": sx, "y": sy}# -- idempotency ledger -----------------------------------------+ if kind in {"click", "click_element", "drag", "scroll"} and captured_topology:+ live_topology = monitor_topology_signature(+ await asyncio.to_thread(list_monitors),+ )+ if live_topology != captured_topology:+ history.append(+ f"step {step_idx}: {_summarize_action(action)} REFUSED — "+ "the display layout changed after the screenshot; "+ "capturing fresh geometry before any pointer action."+ )+ break+if ledger.is_duplicate(action, frame.thumb, resolved_xy=resolved_xy):guard_hits += 1history.append(@@ -927,6 +1035,15 @@ async def run_cu_loop(returnbreak # re-perceive+ if kind in {"click", "click_element", "drag", "scroll", "type", "key"}:+ if await _live_window_state_signature() != captured_window_signature:+ history.append(+ f"step {step_idx}: {_summarize_action(action)} REFUSED — "+ "the foreground window changed after the screenshot; "+ "capturing a fresh frame before acting."+ )+ break+# -- execute ------------------------------------------------------t0 = time.monotonic()ok = False@@ -940,6 +1057,7 @@ async def run_cu_loop({"x": resolved_xy[0], "y": resolved_xy[1],"button": action["button"], "double": action["double"],+ "_expected_window_signature": captured_window_signature,},trace_id,)@@ -996,7 +1114,9 @@ async def run_cu_loop(# happy path never pays for it.refined = await _zoom_refine_point(ctx, frame, *resolved_xy,- goal=goal, target=str(action.get("target", "")),+ goal=goal,+ target=str(action.get("target", "")),+ expected_window_signature=captured_window_signature,)if refined is not None and (abs(refined[0] - resolved_xy[0]) > 12@@ -1010,12 +1130,29 @@ async def run_cu_loop(pre2 = await asyncio.to_thread(grab_region, monitor.bbox,)+ if (+ await _live_window_state_signature()+ != captured_window_signature+ or monitor_topology_signature(+ await asyncio.to_thread(list_monitors),+ )+ != captured_topology+ ):+ history.append(+ f"step {step_idx}: zoom-refined click REFUSED — "+ "the foreground window or display layout changed; "+ "capturing a fresh frame before retrying."+ )+ breakok2, detail2 = await _dispatch_tool(ctx, "click",{"x": refined[0], "y": refined[1],"button": action["button"],"double": action["double"],+ "_expected_window_signature": (+ captured_window_signature+ ),},trace_id,)@@ -1047,12 +1184,43 @@ async def run_cu_loop(elif kind == "type":if action.get("clear_first"):- await _dispatch_tool(- ctx, "hotkey", {"keys": _select_all_keys()}, trace_id,+ clear_ok, clear_detail = await _dispatch_tool(+ ctx,+ "hotkey",+ {+ "keys": _select_all_keys(),+ "_expected_window_signature": captured_window_signature,+ },+ trace_id,+ )+ if not clear_ok:+ ok = False+ detail = (+ "could not select existing text before replacement: "+ f"{clear_detail}; refusing to append new text"+ )+ else:+ ok, detail = await _dispatch_tool(+ ctx,+ "type_text",+ {+ "text": action["text"],+ "_expected_window_signature": (+ captured_window_signature+ ),+ },+ trace_id,+ )+ else:+ ok, detail = await _dispatch_tool(+ ctx,+ "type_text",+ {+ "text": action["text"],+ "_expected_window_signature": captured_window_signature,+ },+ trace_id,)- ok, detail = await _dispatch_tool(- ctx, "type_text", {"text": action["text"]}, trace_id,- )profiler.add("act", t0, step_idx)t0 = time.monotonic()if ok:@@ -1084,7 +1252,13 @@ async def run_cu_loop(elif kind == "key":ok, detail = await _dispatch_tool(- ctx, "hotkey", {"keys": action["keys"]}, trace_id,+ ctx,+ "hotkey",+ {+ "keys": action["keys"],+ "_expected_window_signature": captured_window_signature,+ },+ trace_id,)if ok:ledger.record(action, frame.thumb)@@ -1093,10 +1267,10 @@ async def run_cu_loop(elif kind == "scroll":args: dict[str, Any] = {"direction": action["direction"], "amount": action["amount"],+ "x": int(action["x"]), "y": int(action["y"]),+ "_expected_window_signature": captured_window_signature,}- if "x" in action:- pointer_used = True- args["x"], args["y"] = int(action["x"]), int(action["y"])+ pointer_used = Trueok, detail = await _dispatch_tool(ctx, "scroll", args, trace_id)if ok:ledger.record(action, frame.thumb)@@ -1114,6 +1288,7 @@ async def run_cu_loop("x1": resolved_xy[0], "y1": resolved_xy[1],"x2": end_xy[0], "y2": end_xy[1],"duration_ms": action["duration_ms"],+ "_expected_window_signature": captured_window_signature,},trace_id,)@@ -1148,7 +1323,13 @@ async def run_cu_loop(elif kind == "click_element":pointer_used = Trueok, detail = await _dispatch_tool(- ctx, "click_element", {"name": action["name"]}, trace_id,+ ctx,+ "click_element",+ {+ "name": action["name"],+ "_expected_window_signature": captured_window_signature,+ },+ trace_id,)if ok:ledger.record(action, frame.thumb)diff --git a/jarvis/cu/geometry.py b/jarvis/cu/geometry.pyindex b4058597ce..3ac4abfeb3 100644--- a/jarvis/cu/geometry.py+++ b/jarvis/cu/geometry.py@@ -187,6 +187,50 @@ def virtual_screen_bounds(monitors: list[MonitorInfo]) -> tuple[int, int, int, ireturn (left, top, right - left, bottom - top)+def monitor_topology_signature(+ monitors: list[MonitorInfo],+) -> tuple[tuple[int, int, int, int], ...]:+ """Stable geometry-only display signature for capture/action race checks."""+ return tuple(sorted((m.left, m.top, m.width, m.height) for m in monitors))+++def point_on_physical_display(+ x: float,+ y: float,+ monitors: list[MonitorInfo],+) -> bool:+ """True when a point is on a real display, not a virtual-desktop gap."""+ return any(m.contains(x, y) for m in monitors)+++def segment_on_physical_displays(+ x1: int,+ y1: int,+ x2: int,+ y2: int,+ monitors: list[MonitorInfo],+) -> bool:+ """Whether the complete straight segment stays on real displays.++ Pointer moves without a pressed button may safely cross a virtual-desktop+ gap because their final landing is verified. A drag may not: the OS can+ clamp or reroute its held-button path before the endpoint check runs.+ Sampling once per input unit covers the integer cursor trajectory while+ keeping even very wide desktops cheap to validate.+ """+ steps = max(abs(int(x2) - int(x1)), abs(int(y2) - int(y1)))+ if steps == 0:+ return point_on_physical_display(x1, y1, monitors)+ return all(+ point_on_physical_display(+ int(round(x1 + (x2 - x1) * index / steps)),+ int(round(y1 + (y2 - y1) * index / steps)),+ monitors,+ )+ for index in range(steps + 1)+ )++# ---------------------------------------------------------------------------# CoordinateMapper — one per captured frame# ---------------------------------------------------------------------------diff --git a/jarvis/cu/target_guard.py b/jarvis/cu/target_guard.pynew file mode 100644index 0000000000..939e9d8bd5--- /dev/null+++ b/jarvis/cu/target_guard.py@@ -0,0 +1,57 @@+"""Cross-platform foreground identity bound to the CU input coordinate space."""+from __future__ import annotations++from dataclasses import dataclass+from typing import Any+++@dataclass(frozen=True)+class ForegroundTarget:+ """One atomic-enough foreground sample in platform input units."""++ window: Any+ rect: tuple[int, int, int, int] | None+ signature: tuple[Any, ...]+++def window_signature(+ window: Any,+ rect: tuple[int, int, int, int] | None,+) -> tuple[Any, ...]:+ if window is None:+ return ("none",)+ handle = getattr(window, "handle", None)+ if handle:+ return ("handle", int(handle), rect)+ return ("title", str(getattr(window, "title", "") or "").casefold(), rect)+++def read_foreground_target() -> ForegroundTarget:+ """Read hwnd/title and frame under one per-thread DPI context.++ ``asyncio.to_thread`` may use a different worker for every call. Pinning+ both reads in one block prevents a mixed-DPI Windows hwnd from producing+ physical pixels in one guard and DPI-virtualized coordinates in another.+ macOS and X11 use the same helper; ``input_space`` is a no-op there.+ """+ from jarvis.cu.geometry import input_space # noqa: PLC0415+ from jarvis.platform import window_state # noqa: PLC0415++ with input_space():+ window = window_state.foreground_window()+ rect = (+ window_state.window_frame_rect(window)+ if window is not None+ else None+ )+ return ForegroundTarget(window, rect, window_signature(window, rect))+++def foreground_signature() -> tuple[Any, ...]:+ return read_foreground_target().signature+++def foreground_matches(expected: tuple[Any, ...]) -> bool:+ return bool(expected) and expected[0] != "none" and (+ foreground_signature() == expected+ )diff --git a/jarvis/cu/verify.py b/jarvis/cu/verify.pyindex 499e420e5d..a9da3c924a 100644--- a/jarvis/cu/verify.py+++ b/jarvis/cu/verify.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport asyncioimport logging+from collections.abc import Callablefrom typing import Anylogger = logging.getLogger(__name__)@@ -368,12 +369,16 @@ def snap_point_to_element(# ---------------------------------------------------------------------------async def foreground_ui_snapshot(- timeout_s: float = UIA_TIMEOUT_S, max_labels: int = 28,+ timeout_s: float = UIA_TIMEOUT_S,+ max_labels: int = 28,+ observation_guard: Callable[[], bool] | None = None,) -> tuple[list[str], str, str | None, list[tuple[str, str, tuple[int, int, int, int]]]]:"""One tree observation → (clickable labels, field-values hint, handoffreason, clickable rects). ``([], "", None, [])`` on any failure or alabel-less surface — that empty path self-gates the loop back to rawpixel clicks (canvas apps expose no useful tree)."""+ if observation_guard is not None and not observation_guard():+ raise RuntimeError("foreground window changed before UI-tree observation")try:obs = await asyncio.wait_for(_get_ui_tree_source().observe(), timeout=timeout_s,@@ -381,6 +386,8 @@ async def foreground_ui_snapshot(except Exception as exc: # noqa: BLE001 — best-effort enumerationlogger.debug("[cu] UI-tree snapshot failed (non-fatal): %s", exc)return [], "", None, []+ if observation_guard is not None and not observation_guard():+ raise RuntimeError("foreground window changed during UI-tree observation")nodes = tuple(getattr(obs, "nodes", ()) or ())return (clickable_labels(nodes, max_n=max_labels),diff --git a/jarvis/harness/action_registry.py b/jarvis/harness/action_registry.pyindex fc85105801..3cb09d325f 100644--- a/jarvis/harness/action_registry.py+++ b/jarvis/harness/action_registry.py@@ -28,6 +28,7 @@ from dataclasses import dataclass, fieldfrom typing import Anyfrom jarvis.core.protocols import ToolResult+from jarvis.platform import detect_platformlog = logging.getLogger(__name__)@@ -182,13 +183,15 @@ def _transform_press_shortcut(args: dict[str, Any]) -> dict[str, Any]:def _transform_open_terminal(args: dict[str, Any]) -> dict[str, Any]:- """``open_terminal(profile='powershell')`` -> ``open_app(app_name='wt')``.+ """Map the generic terminal action to the current platform's launcher.- Default is Windows Terminal (``wt``). Fallback profiles via argument:- ``cmd``, ``powershell``, ``pwsh``.+ Explicit Windows profiles remain available; the default and generic+ ``terminal`` alias resolve to ``wt`` only on Windows."""- profile = (args.get("profile") or args.get("app") or "wt").strip().lower()- if profile in ("wt", "windowsterminal", "terminal"):+ profile = (args.get("profile") or args.get("app") or "terminal").strip().lower()+ if profile == "terminal":+ app = "wt" if detect_platform() == "win32" else "terminal"+ elif profile in ("wt", "windowsterminal"):app = "wt"elif profile in ("cmd", "command"):app = "cmd"@@ -213,10 +216,10 @@ async def _composite_open_new_tab(tools: dict[str, Any],trace_id: Any,) -> ToolResult:- """Sends Ctrl+T to the active window — the standard shortcut for 'new tab'.+ """Send the platform-native standard shortcut for a new tab.- Works in every browser, Windows Terminal, and many editors. If an app- maps this differently, the LLM can use ``press_shortcut`` directly instead.+ macOS uses Command+T; Windows and Linux use Ctrl+T. If an app maps this+ differently, the LLM can use ``press_shortcut`` directly instead."""hotkey_tool = tools.get("hotkey")if hotkey_tool is None:@@ -226,7 +229,7 @@ async def _composite_open_new_tab()return await executor.execute(hotkey_tool,- {"keys": ["ctrl", "t"]},+ {"keys": ["cmd" if detect_platform() == "darwin" else "ctrl", "t"]},user_utterance="open_new_tab",trace_id=trace_id,)@@ -286,6 +289,12 @@ def build_default_registry() -> ActionRegistry:is architecturally impossible."""reg = ActionRegistry()+ platform_name = detect_platform()+ is_macos = platform_name == "darwin"+ new_tab_combo = "cmd+t" if is_macos else "ctrl+t"+ window_switch_combo = "cmd+tab" if is_macos else "alt+tab"+ restore_tab_combo = "cmd+shift+t" if is_macos else "ctrl+shift+t"+ terminal_name = "Windows Terminal (wt)" if platform_name == "win32" else "Terminal"# ---- Direct (1:1 tool mapping) -----------------------------------reg.register(ActionSpec(@@ -409,10 +418,11 @@ def build_default_registry() -> ActionRegistry:name="press_shortcut",tool_name="hotkey",description=(- "Sends a key combination such as 'ctrl+t' (new tab), "- "'alt+tab' (window switch), 'ctrl+shift+t' (restore tab)."+ f"Sends a key combination such as '{new_tab_combo}' (new tab), "+ f"'{window_switch_combo}' (window switch), "+ f"'{restore_tab_combo}' (restore tab)."),- arg_schema={"combo": "string (e.g. 'ctrl+t')"},+ arg_schema={"combo": f"string (e.g. '{new_tab_combo}')"},arg_transform=_transform_press_shortcut,risk_hint="monitor",))@@ -420,8 +430,8 @@ def build_default_registry() -> ActionRegistry:name="open_terminal",tool_name="open_app",description=(- "Opens a terminal window. Default: Windows Terminal (wt). "- "Optional: profile='cmd'|'powershell'|'pwsh'."+ f"Opens a terminal window. Default: {terminal_name}. "+ "An optional profile may select another installed terminal."),arg_schema={"profile": "string?"},arg_transform=_transform_open_terminal,@@ -432,7 +442,10 @@ def build_default_registry() -> ActionRegistry:reg.register(ActionSpec(name="open_new_tab",tool_name=None,- description="Opens a new tab in the active window (sends Ctrl+T).",+ description=(+ "Opens a new tab in the active window "+ f"(sends {new_tab_combo})."+ ),arg_schema={},composite=_composite_open_new_tab,risk_hint="monitor",diff --git a/jarvis/harness/screenshot_only_loop.py b/jarvis/harness/screenshot_only_loop.pyindex dbdbc704c5..f33d164910 100644--- a/jarvis/harness/screenshot_only_loop.py+++ b/jarvis/harness/screenshot_only_loop.py@@ -2154,6 +2154,12 @@ def _save_user_screenshot() -> Path | None:a capture error) so the caller falls through to the interactive loop with noregression."""try:+ from jarvis.vision.screenshot import ( # noqa: PLC0415+ warn_if_screen_recording_denied,+ )++ if warn_if_screen_recording_denied():+ return Noneimport mss # noqa: PLC0415from PIL import Image # noqa: PLC0415diff --git a/jarvis/harness/screenshot_only_loop_stable.py b/jarvis/harness/screenshot_only_loop_stable.pyindex 53694f4e5b..0949c34734 100644--- a/jarvis/harness/screenshot_only_loop_stable.py+++ b/jarvis/harness/screenshot_only_loop_stable.py@@ -1951,6 +1951,12 @@ def _save_user_screenshot() -> Path | None:a capture error) so the caller falls through to the interactive loop with noregression."""try:+ from jarvis.vision.screenshot import ( # noqa: PLC0415+ warn_if_screen_recording_denied,+ )++ if warn_if_screen_recording_denied():+ return Noneimport mss # noqa: PLC0415from PIL import Image # noqa: PLC0415diff --git a/jarvis/platform/window_capture.py b/jarvis/platform/window_capture.pyindex d48f0fcb0f..1ea9b33d74 100644--- a/jarvis/platform/window_capture.py+++ b/jarvis/platform/window_capture.py@@ -139,6 +139,20 @@ def _grab_window_macos(window_id: int) -> tuple[tuple[int, int], bytes] | None:config.setWidth_(max(1, round(frame.size.width * scale)))config.setHeight_(max(1, round(frame.size.height * scale)))config.setShowsCursor_(False)+ # A framed single-window image can include drop-shadow pixels outside the+ # SCWindow frame. The coordinate mapper is anchored to that frame, so+ # accepting shadow padding would shift every inferred target. macOS 14++ # exposes this selector; if the runtime bridge cannot provide it, fall+ # back to the frame-rect capture path instead of using ambiguous pixels.+ ignore_shadows = getattr(config, "setIgnoreShadowsSingleWindow_", None)+ if not callable(ignore_shadows):+ log.debug("SCK cannot disable single-window shadows; using rect fallback")+ return None+ try:+ ignore_shadows(True)+ except Exception: # noqa: BLE001 - unsafe framing must fail closed+ log.debug("SCK single-window shadow suppression failed", exc_info=True)+ return Noneimage_box: dict[str, Any] = {}image_ready = threading.Event()diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.pyindex 5a44086e4e..3c07a7a67d 100644--- a/jarvis/platform/window_state.py+++ b/jarvis/platform/window_state.py@@ -12,9 +12,9 @@ Design contract (matches the platform seam, AD-5/AD-6/AD-13):* Every public function is best-effort and NEVER raises into a caller — a missingtool, a denied permission, a headless / Wayland session, or a native-call errordegrades to an empty result, not an exception.-* The Windows ctypes path is moved verbatim from ``switch_window`` (AD-7: behavior- unchanged); macOS (osascript) and Linux/X11 (wmctrl) are the cross-platform- siblings. Wayland and headless sessions degrade cleanly.+* The Windows ctypes path is moved verbatim from ``switch_window`` (AD-7:+ behavior unchanged); macOS uses Quartz/AppKit/Accessibility and Linux/X11+ uses wmctrl. Wayland and headless sessions degrade cleanly.* ``is_app_running`` is conservative: it only reports a match when an app token(>=3 chars) clearly appears in a window title. When uncertain it returns``None`` so the caller falls through to a normal launch — a false negative just@@ -28,7 +28,6 @@ from __future__ import annotationsimport loggingimport os-import reimport shutilimport subprocessimport time@@ -36,6 +35,7 @@ from dataclasses import dataclassfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.platform import detect_platform+from jarvis.platform.macos_ax import decode_ax_point, decode_ax_sizefrom jarvis.platform.probes import display_present, is_waylandlog = logging.getLogger(__name__)@@ -54,8 +54,9 @@ _TITLE_ALIASES: dict[str, tuple[str, ...]] = {class WindowInfo:"""A single visible top-level window.- ``handle`` is an opaque platform handle (the Win32 ``hwnd`` on Windows,- ``None`` on macOS/Linux where the backends address windows by title).+ ``handle`` is an opaque platform handle: Win32 ``hwnd``, macOS+ ``CGWindowID``, or an X11 window id. A degraded title-only probe uses+ ``None``."""title: str@@ -246,128 +247,295 @@ def _foreground_title_windows() -> str:# -----------------------------------------------------------------------# macOS backend (osascript) — focus path moved verbatim from switch_window (AD-7)+# macOS backend (Quartz/AppKit/AX; no System Events Automation grant)# ----------------------------------------------------------------------+def _macos_window_title(entry: dict) -> str:+ return str(entry.get("kCGWindowName") or entry.get("kCGWindowOwnerName") or "")+++def _macos_window_pid(entry: dict) -> int:+ try:+ return int(entry.get("kCGWindowOwnerPID", 0) or 0)+ except (TypeError, ValueError):+ return 0+++def _macos_ax_attr(element: object, attribute: str) -> object | None:+ try:+ from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415+ AXUIElementCopyAttributeValue,+ )++ error, value = AXUIElementCopyAttributeValue(element, attribute, None)+ return value if error == 0 else None+ except Exception: # noqa: BLE001+ return None+++def _macos_entry_bounds(entry: dict) -> tuple[float, float, float, float] | None:+ raw = entry.get("kCGWindowBounds") or {}+ try:+ rect = (+ float(raw["X"]),+ float(raw["Y"]),+ float(raw["Width"]),+ float(raw["Height"]),+ )+ except (KeyError, TypeError, ValueError):+ return None+ return rect if rect[2] > 0 and rect[3] > 0 else None+++def _macos_ax_window_bounds(window: object) -> tuple[float, float, float, float] | None:+ point = decode_ax_point(_macos_ax_attr(window, "AXPosition"))+ size = decode_ax_size(_macos_ax_attr(window, "AXSize"))+ if point is None or size is None or size[0] <= 0 or size[1] <= 0:+ return None+ return point[0], point[1], size[0], size[1]+++def _macos_rects_match(+ first: tuple[float, float, float, float],+ second: tuple[float, float, float, float],+ *,+ tolerance: float = 3.0,+) -> bool:+ return all(+ abs(left - right) <= tolerance+ for left, right in zip(first, second, strict=True)+ )+++def _select_macos_ax_window(+ windows: list[object],+ entry: dict,+ *,+ title_contains: str | None = None,+ title_equals: str | None = None,+) -> object | None:+ """Correlate a CGWindow entry to exactly one AX window.++ CGWindowID is not exposed as a public AX attribute. Position and size are+ therefore the strongest public correlation key. A unique title is a safe+ fallback for minimized windows whose geometry is unavailable; duplicate+ titles fail closed instead of focusing or resizing an arbitrary sibling.+ """+ cg_bounds = _macos_entry_bounds(entry)+ if cg_bounds is not None:+ geometry_matches = [+ window+ for window in windows+ if (+ (ax_bounds := _macos_ax_window_bounds(window)) is not None+ and _macos_rects_match(cg_bounds, ax_bounds)+ )+ ]+ if len(geometry_matches) == 1:+ return geometry_matches[0]+ if len(geometry_matches) > 1:+ return None++ contains = (title_contains or "").strip().casefold()+ equals = (title_equals or "").strip().casefold()+ title_matches: list[object] = []+ for window in windows:+ title = str(_macos_ax_attr(window, "AXTitle") or "").strip().casefold()+ if (equals and title == equals) or (contains and contains in title):+ title_matches.append(window)+ if len(title_matches) == 1:+ return title_matches[0]+ if not title_matches and len(windows) == 1:+ return windows[0]+ return None++def _find_and_focus_macos(title_contains: str) -> tuple[bool, str]:- """Bring the first window whose title contains the substring to the front- via AppleScript / System Events (H2, DEEP-DIVE-AUDIT-2026-06-19).+ """Activate and AX-raise a matching macOS window without AppleScript.- Needs the macOS Accessibility grant; without it osascript errors out, which- is reported as a clear onboarding message instead of a silent no-op. All- user-facing strings are English (Output-Language Policy).+ Quartz supplies the stable owner PID/window catalogue, AppKit activates+ the owning process, and Accessibility raises the exact window. This avoids+ the separate Automation permission that System Events requires."""- if shutil.which("osascript") is None:- return False, "osascript not found — cannot switch windows on this macOS host."- # Lowercase for case-insensitive matching (parity with the Linux path), then- # escape every AppleScript string-literal metacharacter — including newlines/- # tabs — so a crafted title cannot break out of the `contains "..."` literal- # and inject statements into the `tell` block (review HIGH).- needle = (- title_contains.lower()- .replace("\\", "\\\\")- .replace('"', '\\"')- .replace("\n", "\\n")- .replace("\r", "\\r")- .replace("\t", "\\t")+ needle = (title_contains or "").strip().casefold()+ if not needle:+ return False, "A non-empty window title is required."++ matched_entry: dict | None = None+ for entry in _quartz_window_list(on_screen_only=False):+ try:+ if int(entry.get("kCGWindowLayer", 0) or 0) != 0:+ continue+ except (TypeError, ValueError):+ continue+ if needle in _macos_window_title(entry).casefold():+ matched_entry = entry+ break+ if matched_entry is None:+ return False, f"No window with title containing '{title_contains}' found."++ pid = _macos_window_pid(matched_entry)+ if not pid:+ return False, "The matching macOS window has no owning process identifier."++ try:+ from AppKit import ( # type: ignore[import-not-found] # noqa: PLC0415+ NSApplicationActivateAllWindows,+ NSApplicationActivateIgnoringOtherApps,+ NSRunningApplication,+ )+ from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415+ AXUIElementCreateApplication,+ AXUIElementPerformAction,+ AXUIElementSetAttributeValue,+ )+ except (ImportError, ModuleNotFoundError) as exc:+ return False, f"macOS window APIs are unavailable: {exc}"++ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ PermissionState,+ get_system_permission_port,)- needle = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", needle) # strip other control chars- script = (- 'tell application "System Events"\n'- " repeat with proc in (every process whose visible is true)\n"- " repeat with w in (every window of proc)\n"- f' if (the lowercase of (name of w)) contains "{needle}" then\n'- " set frontmost of proc to true\n"- ' perform action "AXRaise" of w\n'- " return name of w\n"- " end if\n"- " end repeat\n"- " end repeat\n"- "end tell\n"- 'return ""\n'++ permission_port = get_system_permission_port()+ if not permission_port.runtime_access_granted(PermissionId.ACCESSIBILITY):+ accessibility_state = permission_port.state(PermissionId.ACCESSIBILITY)+ detail = (+ accessibility_state.value+ if accessibility_state is not PermissionState.GRANTED+ else "grant belongs to an unstable app identity or needs restart"+ )+ return False, (+ f"macOS Accessibility permission is not ready ({detail}) — grant it in System "+ "Settings > Privacy & Security > Accessibility so Jarvis can switch windows."+ )++ app = NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)+ if app is None:+ return False, "The matching macOS application exited before it could be focused."+ options = NSApplicationActivateIgnoringOtherApps | NSApplicationActivateAllWindows+ if not bool(app.activateWithOptions_(options)):+ return False, "macOS refused to activate the matching application."++ root = AXUIElementCreateApplication(pid)+ windows = list(_macos_ax_attr(root, "AXWindows") or [])+ owner_name = str(matched_entry.get("kCGWindowOwnerName") or "")+ target_title = _macos_window_title(matched_entry)+ target = _select_macos_ax_window(+ windows,+ matched_entry,+ title_contains=needle if needle not in owner_name.casefold() else None,)- proc = subprocess.run(- ["osascript", "-e", script],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=10,- creationflags=NO_WINDOW_CREATIONFLAGS,+ if target is None:+ return False, (+ "The application activated, but its matching AX window was "+ "unavailable or ambiguous."+ )+ target_title = str(_macos_ax_attr(target, "AXTitle") or target_title)++ minimized = bool(_macos_ax_attr(target, "AXMinimized") or False)+ restore_error = (+ AXUIElementSetAttributeValue(target, "AXMinimized", False)+ if minimized+ else 0)- if proc.returncode != 0:- err = (proc.stderr or "").strip()- if "not allowed assistive access" in err.lower() or "-1719" in err:- return False, (- "macOS Accessibility permission not granted — grant it in System "- "Settings > Privacy & Security > Accessibility so Jarvis can switch windows."- )- return False, f"osascript window switch failed: {err or proc.returncode}"- matched = (proc.stdout or "").strip()- if matched:- return True, matched- return False, f"No visible window with title containing '{title_contains}' found."+ raise_error = AXUIElementPerformAction(target, "AXRaise")+ focus_error = AXUIElementSetAttributeValue(root, "AXFocusedWindow", target)+ front_error = AXUIElementSetAttributeValue(root, "AXFrontmost", True)+ if any(+ error != 0+ for error in (front_error, focus_error, restore_error, raise_error)+ ):+ return False, "macOS Accessibility refused to focus the matching window."+ return True, target_titledef _list_windows_macos() -> list[WindowInfo]:- """Titles of every visible window via System Events (best-effort)."""- if shutil.which("osascript") is None:- return []- script = (- 'set out to ""\n'- 'tell application "System Events"\n'- " repeat with proc in (every process whose visible is true)\n"- " repeat with w in (every window of proc)\n"- " set out to out & (name of w) & linefeed\n"- " end repeat\n"- " end repeat\n"- "end tell\n"- "return out\n"- )- proc = subprocess.run(- ["osascript", "-e", script],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=10,- creationflags=NO_WINDOW_CREATIONFLAGS,- )- if proc.returncode != 0:- return []- return [- WindowInfo(title=line.strip())- for line in (proc.stdout or "").splitlines()- if line.strip()- ]+ """Top-level normal-layer windows from Quartz, front-to-back."""+ entries: list[dict] = []+ for entry in _quartz_window_list(on_screen_only=False):+ try:+ if int(entry.get("kCGWindowLayer", 0) or 0) != 0:+ continue+ title = _macos_window_title(entry).strip()+ except (TypeError, ValueError):+ continue+ if title:+ entries.append(entry)++ minimized_by_number: dict[int, bool] = {}+ try:+ from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415+ AXUIElementCreateApplication,+ )++ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ get_system_permission_port,+ )++ port = get_system_permission_port()+ if port.runtime_access_granted(PermissionId.ACCESSIBILITY):+ ax_windows_by_pid: dict[int, list[object]] = {}+ for entry in entries:+ pid = _macos_window_pid(entry)+ number = int(entry.get("kCGWindowNumber", 0) or 0)+ if not pid or not number:+ continue+ if pid not in ax_windows_by_pid:+ root = AXUIElementCreateApplication(pid)+ ax_windows_by_pid[pid] = list(+ _macos_ax_attr(root, "AXWindows") or [],+ )+ ax_windows = ax_windows_by_pid[pid]+ title_key = _macos_window_title(entry).strip().casefold()+ target = _select_macos_ax_window(+ ax_windows,+ entry,+ title_equals=title_key,+ )+ if target is not None:+ native_minimized = _macos_ax_attr(target, "AXMinimized")+ if native_minimized is not None:+ minimized_by_number[number] = bool(native_minimized)+ except Exception: # noqa: BLE001 — minimized state is advisory+ log.debug("macOS AX minimized-state lookup failed", exc_info=True)++ result: list[WindowInfo] = []+ for entry in entries:+ try:+ number = int(entry.get("kCGWindowNumber", 0) or 0)+ except (TypeError, ValueError):+ number = 0+ result.append(WindowInfo(+ title=_macos_window_title(entry).strip(),+ minimized=minimized_by_number.get(number, False),+ handle=number or None,+ ))+ return resultdef _foreground_title_macos() -> str:- if shutil.which("osascript") is None:- return ""- script = (- 'tell application "System Events"\n'- " set frontApp to first application process whose frontmost is true\n"- " try\n"- " return name of first window of frontApp\n"- " on error\n"- " return name of frontApp\n"- " end try\n"- "end tell\n"- )- proc = subprocess.run(- ["osascript", "-e", script],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=10,- creationflags=NO_WINDOW_CREATIONFLAGS,- )- if proc.returncode != 0:+ try:+ from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415++ app = NSWorkspace.sharedWorkspace().frontmostApplication()+ if app is None:+ return ""+ pid = int(app.processIdentifier())+ for entry in _quartz_window_list():+ if (+ _macos_window_pid(entry) == pid+ and int(entry.get("kCGWindowLayer", 0) or 0) == 0+ ):+ title = _macos_window_title(entry).strip()+ if title:+ return title+ return str(app.localizedName() or "")+ except Exception: # noqa: BLE001return ""- return (proc.stdout or "").strip()# ----------------------------------------------------------------------@@ -713,26 +881,27 @@ def _foreground_window_windows() -> WindowInfo | None:return WindowInfo(title=buf.value or "", handle=int(hwnd))-def _quartz_window_list() -> list:- """On-screen window info dicts via Quartz, front-to-back; ``[]`` when the- framework is absent (base install without ``[desktop-macos]``) or the call- fails. Bounds and ids come in the CG global space (points, top-left- origin) — the SAME space Quartz mouse events and mss capture rects use,- so no extra conversion may ever be applied to them."""+def _quartz_window_list(*, on_screen_only: bool = True) -> list:+ """Quartz window info dicts, front-to-back, or ``[]`` when unavailable.++ Foreground/capture callers use the default on-screen catalogue. Window+ enumeration and switching request the all-windows catalogue so minimized+ and other-Space windows can still be found and restored. Bounds and ids+ use the same global point space as Quartz input and mss capture rects.+ """try:- from Quartz import ( # noqa: PLC0415- CGWindowListCopyWindowInfo,- kCGNullWindowID,- kCGWindowListExcludeDesktopElements,- kCGWindowListOptionOnScreenOnly,- )+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415except Exception: # noqa: BLE001 — pyobjc not installedreturn []try:- return list(CGWindowListCopyWindowInfo(- kCGWindowListOptionOnScreenOnly- | kCGWindowListExcludeDesktopElements,- kCGNullWindowID,+ scope = (+ Quartz.kCGWindowListOptionOnScreenOnly+ if on_screen_only+ else getattr(Quartz, "kCGWindowListOptionAll", 0)+ )+ return list(Quartz.CGWindowListCopyWindowInfo(+ scope | Quartz.kCGWindowListExcludeDesktopElements,+ Quartz.kCGNullWindowID,) or [])except Exception: # noqa: BLE001 — permission / transient CG errorlog.debug("CGWindowListCopyWindowInfo failed", exc_info=True)@@ -746,13 +915,23 @@ def _foreground_window_macos() -> WindowInfo | None:the first entry on layer 0 is the frontmost app window (status items,the Dock and overlays live on higher layers). ``kCGWindowName`` needsthe Screen-Recording permission — without it the owning app's name still- identifies the window. Falls back to the osascript title (no handle)- when Quartz is unavailable.+ identifies the window. Falls back to the native foreground-title probe+ (without a handle) when Quartz is unavailable."""+ front_pid = 0+ try:+ from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415++ app = NSWorkspace.sharedWorkspace().frontmostApplication()+ front_pid = int(app.processIdentifier()) if app is not None else 0+ except Exception: # noqa: BLE001+ log.debug("frontmost macOS process lookup failed", exc_info=True)for entry in _quartz_window_list():try:if int(entry.get("kCGWindowLayer", 0) or 0) != 0:continue+ if front_pid and _macos_window_pid(entry) != front_pid:+ continuenumber = int(entry.get("kCGWindowNumber", 0) or 0)title = str(entry.get("kCGWindowName")@@ -1061,11 +1240,91 @@ def _window_frame_rect_linux(win: WindowInfo) -> tuple[int, int, int, int] | Nonreturn (left, top, width, height)+def _resolve_macos_ax_window(win: WindowInfo) -> tuple[object | None, str]:+ """Resolve a Quartz ``WindowInfo`` to its owning native AX window."""+ try:+ from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415+ from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415+ AXUIElementCreateApplication,+ )+ except (ImportError, ModuleNotFoundError) as exc:+ return None, f"macOS window APIs are unavailable: {exc}"++ pid = 0+ catalog_match = False+ matched_entry: dict | None = None+ title_key = (win.title or "").strip().casefold()+ for entry in _quartz_window_list(on_screen_only=False):+ try:+ number = int(entry.get("kCGWindowNumber", 0) or 0)+ title = _macos_window_title(entry).strip().casefold()+ except (TypeError, ValueError):+ continue+ if (win.handle and number == int(win.handle)) or (+ not win.handle and title_key and title == title_key+ ):+ catalog_match = True+ pid = _macos_window_pid(entry)+ matched_entry = entry+ break+ if win.handle and not catalog_match:+ return None, "The requested macOS window no longer exists."+ if not pid:+ try:+ app = NSWorkspace.sharedWorkspace().frontmostApplication()+ pid = int(app.processIdentifier()) if app is not None else 0+ except Exception: # noqa: BLE001+ pid = 0+ if not pid:+ return None, "The macOS window has no owning process identifier."++ root = AXUIElementCreateApplication(pid)+ windows = list(_macos_ax_attr(root, "AXWindows") or [])+ target = (+ _select_macos_ax_window(+ windows,+ matched_entry,+ title_equals=title_key,+ )+ if matched_entry is not None+ else None+ )+ if target is None and matched_entry is None and len(windows) == 1:+ target = windows[0]+ if target is None:+ return None, "The matching macOS AX window is unavailable or ambiguous."+ return target, ""+++def _window_is_maximized_macos(win: WindowInfo) -> bool | None:+ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ get_system_permission_port,+ )++ if not get_system_permission_port().runtime_access_granted(+ PermissionId.ACCESSIBILITY,+ ):+ return None+ target, _error = _resolve_macos_ax_window(win)+ if target is None:+ return None+ full_screen = _macos_ax_attr(target, "AXFullScreen")+ if full_screen is not None and bool(full_screen):+ return True+ zoomed = _macos_ax_attr(target, "AXZoomed")+ if zoomed is not None:+ return bool(zoomed)+ return None if full_screen is None else bool(full_screen)++def window_is_maximized(win: WindowInfo) -> bool | None:- """Whether the window is maximized; ``None`` when it cannot be read- (non-Windows today — callers must treat that as "don't touch")."""+ """Whether the window is maximized; ``None`` when it cannot be read."""try:- if detect_platform() != "win32" or not win.handle:+ platform_name = detect_platform()+ if platform_name == "darwin":+ return _window_is_maximized_macos(win)+ if platform_name != "win32" or not win.handle:return Noneimport ctypes # noqa: PLC0415from ctypes import wintypes # noqa: PLC0415@@ -1091,6 +1350,48 @@ def window_is_maximized(win: WindowInfo) -> bool | None:return None+def _maximize_window_macos(win: WindowInfo) -> tuple[bool, str]:+ """Set the native AXZoomed attribute without Apple Events automation."""+ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ PermissionState,+ get_system_permission_port,+ )++ port = get_system_permission_port()+ if not port.runtime_access_granted(PermissionId.ACCESSIBILITY):+ state = port.state(PermissionId.ACCESSIBILITY)+ detail = (+ state.value+ if state is not PermissionState.GRANTED+ else "grant belongs to an unstable app identity or needs restart"+ )+ return False, (+ "macOS Accessibility permission is not ready "+ f"({detail}); grant it in Personal Jarvis > Settings > "+ "Permissions or System Settings > Privacy & Security > "+ "Accessibility, then retry."+ )++ try:+ from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415+ AXUIElementSetAttributeValue,+ )+ except (ImportError, ModuleNotFoundError) as exc:+ return False, f"macOS window APIs are unavailable: {exc}"+ target, error = _resolve_macos_ax_window(win)+ if target is None:+ return False, error++ error = AXUIElementSetAttributeValue(target, "AXZoomed", True)+ if error != 0:+ return False, (+ "macOS Accessibility could not zoom this window; it may be a "+ "fixed-size dialog or not expose AXZoomed."+ )+ return True, f"zoomed '{(win.title or 'window')[:40]}' to fill its display"++def maximize_window(win: WindowInfo) -> tuple[bool, str]:"""Maximize ``win`` ON ITS CURRENT monitor (never a cross-monitor move —moving across a DPI boundary is what shrinks/mangles windows).@@ -1118,27 +1419,7 @@ def maximize_window(win: WindowInfo) -> tuple[bool, str]:user32.ShowWindow(hwnd, _SW_MAXIMIZE)return True, f"maximized '{(win.title or 'window')[:40]}'"if plat == "darwin":- if shutil.which("osascript") is None:- return False, "osascript not found"- # AXZoomed = the native green-button "fill the screen" zoom (NOT- # the separate macOS full-screen Space). Apps without the- # attribute error out -> honest failure, window untouched.- script = (- 'tell application "System Events"\n'- " set frontProc to first application process whose frontmost is true\n"- ' set value of attribute "AXZoomed" of front window of frontProc to true\n'- "end tell\n"- )- proc = subprocess.run(- ["osascript", "-e", script],- capture_output=True, text=True,- encoding="utf-8", errors="replace",- timeout=10,- creationflags=NO_WINDOW_CREATIONFLAGS,- )- if proc.returncode != 0:- return False, "could not zoom the front window (Accessibility?)"- return True, "zoomed the front window to fill the screen"+ return _maximize_window_macos(win)if plat == "linux":if is_wayland() or not display_present():return False, "cannot maximize on Wayland/headless"diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.pyindex 20591371ea..f79a9869e0 100644--- a/jarvis/plugins/harness/computer_use.py+++ b/jarvis/plugins/harness/computer_use.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport asyncioimport logging+import sysimport timefrom collections.abc import AsyncIterator@@ -31,15 +32,15 @@ _TIMEOUT_EXIT_CODE = 124def _resolve_run_cu_loop():- """Select the Computer-Use engine per ``[computer_use].engine`` (reversible).-- ``"v2"`` (default) -> the rebuilt perceive->act->verify engine- (``jarvis/cu/engine.py``). Legacy fallbacks stay selectable: ``"current"``- = the last maintained legacy loop, ``"june13"`` / ``"stable"`` = frozen- known-good snapshots. Read PER MISSION so a config flip applies on the- next mission (no restart needed). Logs the live engine — INFO for every- non-default choice so it is never ambiguous which version is running.- Never raises: a config-read problem falls back to the default engine.+ """Resolve every live Computer-Use mission to the guarded v2 engine.++ ``"v2"`` is the only action-capable engine: it owns live permission,+ monitor-topology and foreground-window guards. Historical ``current``,+ ``june13`` and ``stable`` values remain readable for config compatibility+ but route to v2; their frozen loops can still be imported by forensic tests+ and must never dispatch live desktop input. Read per mission so config+ recovery applies without restart. Never raises: a config-read problem also+ falls back to v2."""try:from jarvis.core.config import load_config # noqa: PLC0415@@ -48,6 +49,15 @@ def _resolve_run_cu_loop():engine = str(getattr(cu, "engine", "v2") or "v2")except Exception: # noqa: BLE001 — a config read must never break a missionengine = "v2"+ if engine != "v2":+ _log.warning(+ "[cu] ENGINE = %s is retired for live input because legacy loops "+ "lack current permission, topology and foreground-window action "+ "guards on %s; using the maintained v2 engine instead.",+ engine,+ sys.platform,+ )+ engine = "v2"if engine == "v2":from jarvis.cu.engine import run_cu_loop as _loop # noqa: PLC0415diff --git a/jarvis/plugins/tool/click.py b/jarvis/plugins/tool/click.pyindex 04c84e5cc4..61ede73642 100644--- a/jarvis/plugins/tool/click.py+++ b/jarvis/plugins/tool/click.py@@ -27,9 +27,18 @@ from jarvis.cu.actuate.windows import (from jarvis.cu.actuate.windows import (normalize_virtualdesk as _normalize_virtualdesk, # noqa: F401 — re-export (tests + callers))+from jarvis.cu.target_guard import foreground_matches, foreground_signaturefrom jarvis.overlay.virtual_cursor import get_virtual_cursor+def _foreground_window_signature() -> tuple[Any, ...]:+ return foreground_signature()+++def _window_signature_matches(expected: tuple[Any, ...]) -> bool:+ return foreground_matches(expected)++def _send_click(button: str, double: bool, abs_xy: tuple[int, int] | None = None) -> None:"""Press a mouse button via the shared Windows SendInput backend.@@ -48,7 +57,14 @@ def _send_click(button: str, double: bool, abs_xy: tuple[int, int] | None = Noneactuator.click_at_cursor(button=button, double=double)-def _click_windows(x: int, y: int, button: str, double: bool) -> None:+def _click_windows(+ x: int,+ y: int,+ button: str,+ double: bool,+ *,+ expected_window_signature: tuple[Any, ...] | None = None,+) -> None:"""Click at an absolute screen coordinate, with a visible cursor glide.The real OS cursor glides to ``(x, y)`` (so the user can watch where@@ -64,15 +80,30 @@ def _click_windows(x: int, y: int, button: str, double: bool) -> None:if button_l not in _MOUSE_FLAGS_DOWN:raise ValueError(f"Unknown mouse button: {button!r}. Allowed: left/right/middle")+ from jarvis.cu.actuate.base import verified_move # noqa: PLC0415+ from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415+glide_os_cursor(int(x), int(y))+ actuator = WindowsActuator()+ landing = verified_move(actuator, int(x), int(y))+ if not landing.ok:+ raise OSError(landing.detail)try:get_virtual_cursor().show_click(int(x), int(y), button=button_l, double=double)- except Exception: # noqa: BLE001 — overlay must never break a real click+ except Exception: # noqa: BLE001, S110 — overlay must never break a real clickpass- # Click ABSOLUTELY on the virtual desktop (negative-X monitors included) so a- # flaky SetCursorPos during the glide can't make the button-press land on the- # wrong screen — the glide is now purely the visible cursor animation.- _send_click(button_l, double, abs_xy=(int(x), int(y)))+ if (+ expected_window_signature is not None+ and not _window_signature_matches(expected_window_signature)+ ):+ raise OSError(+ "foreground window changed during cursor movement; refusing to click",+ )+ actuator.click_at_cursor(+ button=button_l,+ double=double,+ expected=(int(x), int(y)),+ )class ClickTool:@@ -122,9 +153,36 @@ class ClickTool:error=f"Unknown button={button!r}. Allowed: left/right/middle",)+ current_signature = _foreground_window_signature()+ expected_raw = args.get("_expected_window_signature")+ if expected_raw is not None and not isinstance(expected_raw, (list, tuple)):+ return ToolResult(+ success=False, output=None,+ error="Refusing click: invalid captured-window identity.",+ )+ expected_signature = (+ tuple(expected_raw) if expected_raw is not None else current_signature+ )+ if not _window_signature_matches(expected_signature):+ return ToolResult(+ success=False,+ output=None,+ error=(+ "Refusing click: foreground window identity is unavailable "+ "or changed after the screenshot."+ ),+ )+if os.name == "nt":try:- await asyncio.to_thread(_click_windows, x, y, button, double)+ await asyncio.to_thread(+ _click_windows,+ x,+ y,+ button,+ double,+ expected_window_signature=expected_signature,+ )kind = "double-click" if double else "click"return ToolResult(success=True,@@ -137,13 +195,27 @@ class ClickTool:error=f"Click at ({x},{y}) failed: {exc}",)- from jarvis.cu.actuate import ActuationUnavailable, get_actuator+ from jarvis.cu.actuate import (+ ActuationUnavailable,+ get_actuator,+ verified_click,+ )try:actuator = get_actuator()- await asyncio.to_thread(- actuator.click, x, y, button=button, double=double,+ landing = await asyncio.to_thread(+ verified_click,+ actuator,+ x,+ y,+ button=button,+ double=double,+ pre_action_check=lambda: _window_signature_matches(+ expected_signature,+ ),)+ if not landing.ok:+ return ToolResult(success=False, output=None, error=landing.detail)return ToolResult(success=True,output=(diff --git a/jarvis/plugins/tool/click_element.py b/jarvis/plugins/tool/click_element.pyindex 478165fdcd..96ca7559c9 100644--- a/jarvis/plugins/tool/click_element.py+++ b/jarvis/plugins/tool/click_element.py@@ -21,7 +21,13 @@ import osfrom typing import Anyfrom jarvis.core.protocols import ExecutionContext, ToolResult-from jarvis.plugins.tool.click import _click_windows+from jarvis.plugins.tool.click import (+ _click_windows,+ _window_signature_matches,+)+from jarvis.plugins.tool.click import (+ _foreground_window_signature as _click_foreground_window_signature,+)# Re-export ``_click_windows`` as a module global so tests can patch it via# ``monkeypatch.setattr("jarvis.plugins.tool.click_element._click_windows", ...)``.@@ -31,6 +37,11 @@ _VALID_BUTTONS = ("left", "right", "middle")_MAX_AVAILABLE_NAMES = 15+def _foreground_window_signature() -> tuple[Any, ...]:+ """Re-exported seam for tests; implementation is shared with raw click."""+ return _click_foreground_window_signature()++class ClickElementTool:name: str = "click_element"risk_tier: str = "monitor"@@ -123,6 +134,36 @@ class ClickElementTool:)source = self._vision_source or make_ui_tree_source()+ observed_signature = _foreground_window_signature()+ if observed_signature[0] == "none":+ return ToolResult(+ success=False,+ output=None,+ error=(+ "Refusing click_element: the foreground window identity "+ "is unavailable."+ ),+ )+ expected_raw = args.get("_expected_window_signature")+ if expected_raw is not None:+ if not isinstance(expected_raw, (list, tuple)):+ return ToolResult(+ success=False,+ output=None,+ error="Refusing click_element: invalid captured-window identity.",+ )+ expected_signature = tuple(expected_raw)+ if observed_signature != expected_signature:+ return ToolResult(+ success=False,+ output=None,+ error=(+ "Refusing click_element: the foreground window changed "+ "after the screenshot."+ ),+ )+ else:+ expected_signature = observed_signaturetry:obs = await source.observe()except Exception as exc: # noqa: BLE001@@ -178,10 +219,31 @@ class ClickElementTool:cx = x + w // 2cy = y + h // 2+ # Observation is asynchronous (AX/UIA can block). Bind the selected+ # node to the window current before observation and, for CU, to the+ # exact window captured by the engine. A same-labelled control in a+ # newly focused app must never receive the stale click.+ if _foreground_window_signature() != expected_signature:+ return ToolResult(+ success=False,+ output=None,+ error=(+ "Refusing click_element: the foreground window changed "+ "while its UI tree was being observed."+ ),+ )+# 5. Click — native on Windows, pyautogui fallback elsewhere.if os.name == "nt":try:- await asyncio.to_thread(_click_windows, cx, cy, button, double)+ await asyncio.to_thread(+ _click_windows,+ cx,+ cy,+ button,+ double,+ expected_window_signature=expected_signature,+ )except (ValueError, OSError) as exc:return ToolResult(success=False,@@ -192,16 +254,32 @@ class ClickElementTool:# Capability probe instead of a raw pyautogui import: Wayland /# headless / missing-deps hosts get the actionable# ActuationUnavailable message (§3 honest degradation).- from jarvis.cu.actuate.base import ActuationUnavailable, get_actuator+ from jarvis.cu.actuate.base import (+ ActuationUnavailable,+ get_actuator,+ verified_click,+ )try:actuator = get_actuator()except ActuationUnavailable as exc:return ToolResult(success=False, output=None, error=str(exc))try:- await asyncio.to_thread(- actuator.click, cx, cy, button=button, double=double+ landing = await asyncio.to_thread(+ verified_click,+ actuator,+ cx,+ cy,+ button=button,+ double=double,+ pre_action_check=lambda: _window_signature_matches(+ expected_signature,+ ),)+ if not landing.ok:+ return ToolResult(+ success=False, output=None, error=landing.detail,+ )except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None, error=str(exc))diff --git a/jarvis/plugins/tool/drag.py b/jarvis/plugins/tool/drag.pyindex 7a10711a49..a77ccd6670 100644--- a/jarvis/plugins/tool/drag.py+++ b/jarvis/plugins/tool/drag.py@@ -10,14 +10,14 @@ cleanly reversible, but it raises no irreversible system change. Routing itthrough this tool (instead of an inline call) gives the drag the same risk-tier /blacklist / audit path as every other Computer-Use action (audit #13).-pyautogui is imported lazily so the module still loads on a non-desktop host (the-harness is desktop-gated anyway); on a host without pyautogui the tool fails-gracefully with a clear message rather than raising.+The shared verified-actuation layer selects native ``SendInput`` on Windows,+native Quartz mouse events on macOS, or a supported X11 desktop backend. It+remains import-clean on headless hosts and fails with an actionable message+when no safe input backend is available."""from __future__ import annotationsimport asyncio-import osfrom typing import Anyfrom jarvis.core.protocols import ExecutionContext, ToolResult@@ -27,25 +27,39 @@ from jarvis.core.protocols import ExecutionContext, ToolResult_DEFAULT_DRAG_DURATION_MS = 400-def _perform_drag(x1: int, y1: int, x2: int, y2: int, duration_s: float) -> None:+def _perform_drag(+ x1: int,+ y1: int,+ x2: int,+ y2: int,+ duration_s: float,+ *,+ expected_window_signature: tuple[Any, ...] | None = None,+) -> None:"""Press left at ``(x1, y1)``, drag to ``(x2, y2)``, release. Blocking;callers run it via ``asyncio.to_thread``.- Windows keeps the proven pyautogui path unchanged. Elsewhere the backend- is resolved via the capability probe so Wayland/headless/missing-deps- hosts raise ``ActuationUnavailable`` with the actionable message instead- of a raw pyautogui error.+ The platform backend is resolved through the capability probe and the+ start/end pointer positions are verified around the gesture."""- if os.name == "nt":- import pyautogui # noqa: PLC0415 — lazy: keeps non-desktop import clean-- pyautogui.moveTo(x1, y1)- pyautogui.dragTo(x2, y2, duration=max(0.0, duration_s), button="left")- return-- from jarvis.cu.actuate.base import get_actuator # noqa: PLC0415-- get_actuator().drag(x1, y1, x2, y2, duration_s=max(0.0, duration_s))+ from jarvis.cu.actuate.base import get_actuator, verified_drag # noqa: PLC0415+ from jarvis.plugins.tool.click import _window_signature_matches # noqa: PLC0415++ result = verified_drag(+ get_actuator(),+ x1,+ y1,+ x2,+ y2,+ duration_s=max(0.0, duration_s),+ pre_action_check=(+ (lambda: _window_signature_matches(expected_window_signature))+ if expected_window_signature is not None+ else None+ ),+ )+ if not result.ok:+ raise RuntimeError(result.detail)class DragTool:@@ -94,8 +108,39 @@ class DragTool:)from jarvis.cu.actuate.base import ActuationUnavailable # noqa: PLC0415+ expected_raw = args.get("_expected_window_signature")+ if expected_raw is not None and not isinstance(expected_raw, (list, tuple)):+ return ToolResult(+ success=False, output=None,+ error="Refusing drag: invalid captured-window identity.",+ )try:- await asyncio.to_thread(_perform_drag, x1, y1, x2, y2, duration_s)+ if expected_raw is None:+ await asyncio.to_thread(_perform_drag, x1, y1, x2, y2, duration_s)+ else:+ expected_signature = tuple(expected_raw)+ from jarvis.plugins.tool.click import ( # noqa: PLC0415+ _window_signature_matches,+ )++ if not _window_signature_matches(expected_signature):+ return ToolResult(+ success=False,+ output=None,+ error=(+ "Refusing drag: foreground window identity is "+ "unavailable or changed after the screenshot."+ ),+ )+ await asyncio.to_thread(+ _perform_drag,+ x1,+ y1,+ x2,+ y2,+ duration_s,+ expected_window_signature=expected_signature,+ )except ActuationUnavailable as exc:return ToolResult(success=False, output=None, error=str(exc))except ImportError as exc:diff --git a/jarvis/plugins/tool/hotkey.py b/jarvis/plugins/tool/hotkey.pyindex 435183e895..62cbf4b5ce 100644--- a/jarvis/plugins/tool/hotkey.py+++ b/jarvis/plugins/tool/hotkey.py@@ -1,9 +1,9 @@-"""hotkey tool: simulates key combos like Ctrl+T, Alt+Tab, Win+R.+"""hotkey tool: simulate platform-native keyboard combinations.-Uses Win32 ``SendInput`` with virtual-key codes as the primary path. Falls-back to ``pyautogui.hotkey`` when the Win32 subsystem is missing — so tests-keep running on Linux/Mac and headless CI, even though real keystrokes only-work on Windows.+Windows uses ``SendInput``; macOS maps Command/Option aliases through the+native Quartz-capable desktop actuator; X11 uses the available pynput or+pyautogui backend. Unsupported and headless hosts fail with an actionable+error.Risk tier: ``monitor`` — a key combo can trigger non-reversible actions(Ctrl+W closes a tab, Ctrl+S opens a dialog). Toast notification, but no@@ -17,9 +17,9 @@ from typing import Anyfrom jarvis.core.protocols import ExecutionContext, ToolResult-# Key-name resolution + combined-token expansion ("ctrl+v" -> ["ctrl", "v"])-# live in the shared CU v2 Windows backend; re-exported here so callers and-# tests keep their import path. The vocabulary is unchanged.+# Combined-token expansion ("ctrl+v" -> ["ctrl", "v"]) lives in the shared+# CU backend. Validation is platform-neutral off Windows so Command/Meta can+# reach the macOS actuator instead of being rejected by a Win32-only table.from jarvis.cu.actuate.windows import ( # noqa: E402expand_combo_keys as _expand_combo_keys,)@@ -28,6 +28,25 @@ from jarvis.cu.actuate.windows import ()+class _ForegroundTargetChanged(RuntimeError):+ """Raised before a shortcut when its screenshot-bound target changed."""+++def _send_for_expected_window(+ sender: Any,+ keys: list[str],+ expected_signature: tuple[Any, ...] | None,+) -> None:+ if expected_signature is not None:+ from jarvis.cu.target_guard import foreground_matches # noqa: PLC0415++ if not foreground_matches(expected_signature):+ raise _ForegroundTargetChanged(+ "foreground window changed after the screenshot"+ )+ sender(keys)++def _send_hotkey_windows(keys: list[str]) -> None:"""Sends a key combination as a Win32 SendInput sequence.@@ -60,7 +79,9 @@ class HotkeyTool:"items": {"type": "string"},"description": ("List of keys in press order. Modifiers (ctrl, shift, "- "alt, win) first, then the action key. Letters individually, "+ "alt/option, win, cmd/command/meta) first, then the action key. "+ "Use cmd for standard macOS shortcuts and ctrl on Windows/Linux. "+ "Letters individually, ""special keys by name (enter, tab, esc, f1-f12, left, right, ""up, down, home, end, pageup, pagedown, delete, backspace)."),@@ -81,17 +102,31 @@ class HotkeyTool:# Tolerate a combined shortcut string ("ctrl+v") in place of the# documented list form (["ctrl", "v"]) — LLM callers emit it constantly.keys_str = _expand_combo_keys(keys_str)+ expected_raw = args.get("_expected_window_signature")+ if expected_raw is not None and not isinstance(expected_raw, (list, tuple)):+ return ToolResult(+ success=False,+ output=None,+ error="Refusing hotkey: invalid captured-window identity.",+ )+ expected_signature = (+ tuple(expected_raw) if expected_raw is not None else None+ )++ from jarvis.cu.actuate.base import is_known_key_name- # Pre-validation for a better error message — otherwise only- # "Unknown key 'X'" comes out of the ctypes path.+ # Keep Windows validation exact; off Windows use the common vocabulary+ # and let the selected backend perform its final capability check.for k in keys_str:- if _resolve_vk(k) is None:+ known = _resolve_vk(k) is not None if os.name == "nt" else is_known_key_name(k)+ if not known:return ToolResult(success=False,output=None,error=(f"Unknown key: {k!r}. Known modifiers: ctrl, shift, "- f"alt, win. Known keys: a-z, 0-9, f1-f12, enter, tab, "+ f"alt/option, win, cmd/command/meta. Known keys: printable "+ f"characters, f1-f12, enter, tab, "f"esc, space, backspace, delete, home, end, pageup, "f"pagedown, left, right, up, down."),@@ -103,11 +138,22 @@ class HotkeyTool:# mapping (e.g. 'win' is called 'winleft' there).if os.name == "nt":try:- await asyncio.to_thread(_send_hotkey_windows, keys_str)+ await asyncio.to_thread(+ _send_for_expected_window,+ _send_hotkey_windows,+ keys_str,+ expected_signature,+ )return ToolResult(success=True,output=f"Hotkey sent: {'+'.join(keys_str)}",)+ except _ForegroundTargetChanged as exc:+ return ToolResult(+ success=False,+ output=None,+ error=f"Refusing hotkey: {exc}.",+ )except (ValueError, OSError) as exc:return ToolResult(success=False,@@ -119,12 +165,23 @@ class HotkeyTool:try:actuator = get_actuator()- await asyncio.to_thread(actuator.key_combo, keys_str)+ await asyncio.to_thread(+ _send_for_expected_window,+ actuator.key_combo,+ keys_str,+ expected_signature,+ )return ToolResult(success=True,output=f"Hotkey sent ({actuator.name}): {'+'.join(keys_str)}",)except ActuationUnavailable as exc:return ToolResult(success=False, output=None, error=str(exc))+ except _ForegroundTargetChanged as exc:+ return ToolResult(+ success=False,+ output=None,+ error=f"Refusing hotkey: {exc}.",+ )except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None, error=str(exc))diff --git a/jarvis/plugins/tool/move_mouse.py b/jarvis/plugins/tool/move_mouse.pyindex a8c54a3db1..e117fba72b 100644--- a/jarvis/plugins/tool/move_mouse.py+++ b/jarvis/plugins/tool/move_mouse.py@@ -23,10 +23,16 @@ def _move_windows(x: int, y: int) -> None:if os.name != "nt":raise RuntimeError("Native mouse movement is only available on Windows")+ from jarvis.cu.actuate.base import verified_move # noqa: PLC0415+ from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415+glide_os_cursor(int(x), int(y))+ landing = verified_move(WindowsActuator(), int(x), int(y))+ if not landing.ok:+ raise OSError(landing.detail)try:get_virtual_cursor().show_move(int(x), int(y))- except Exception: # noqa: BLE001 — overlay must never break a move+ except Exception: # noqa: BLE001, S110 — overlay must never break a movepass@@ -63,11 +69,17 @@ class MoveMouseTool:# Non-Windows: resolve the input backend via the capability probe so# Wayland/headless/missing-deps hosts fail with the actionable# ActuationUnavailable message instead of a raw pyautogui error.- from jarvis.cu.actuate.base import ActuationUnavailable, get_actuator+ from jarvis.cu.actuate.base import (+ ActuationUnavailable,+ get_actuator,+ verified_move,+ )try:actuator = get_actuator()- await asyncio.to_thread(actuator.move, x, y)+ landing = await asyncio.to_thread(verified_move, actuator, x, y)+ if not landing.ok:+ return ToolResult(success=False, output=None, error=landing.detail)return ToolResult(success=True, output=f"Mouse ({actuator.name}) at ({x},{y})")diff --git a/jarvis/plugins/tool/scroll.py b/jarvis/plugins/tool/scroll.pyindex d347078aa1..a4ca77f617 100644--- a/jarvis/plugins/tool/scroll.py+++ b/jarvis/plugins/tool/scroll.py@@ -1,8 +1,8 @@-"""scroll tool: simulates mouse-wheel scrolling at the current (or a given) cursor position.+"""scroll tool: scroll at the current cursor position or a verified target.-Win32-native via ``SendInput`` with ``MOUSEEVENTF_WHEEL`` / ``MOUSEEVENTF_HWHEEL``.-Falls back to ``pyautogui.scroll`` / ``pyautogui.hscroll`` when Win32 is not available,-so the tests run on Linux/Mac even though real scrolling only works on Windows.+Windows uses native ``SendInput``; macOS uses native Quartz wheel events; X11+uses the available pynput/pyautogui desktop backend. Wayland, headless hosts,+and missing desktop extras degrade with an actionable error.This is the missing scroll primitive for computer-use: without it, lists (contacts,chats, file pickers) cannot be scrolled.@@ -40,7 +40,38 @@ def _notch_for(direction: str, amount: int) -> int:return magnitude-def _scroll_windows(direction: str, amount: int, x: int | None, y: int | None) -> int:+def _scroll_with_verified_target(+ actuator: Any,+ direction: str,+ amount: int,+ x: int | None,+ y: int | None,+ *,+ expected_window_signature: tuple[Any, ...] | None = None,+) -> None:+ """Land on an explicit scroll target before emitting the wheel event."""+ if x is not None and y is not None:+ from jarvis.cu.actuate import verified_move # noqa: PLC0415++ landing = verified_move(actuator, int(x), int(y))+ if not landing.ok:+ raise RuntimeError(landing.detail)+ if expected_window_signature is not None:+ from jarvis.cu.target_guard import foreground_matches # noqa: PLC0415++ if not foreground_matches(expected_window_signature):+ raise RuntimeError("foreground window changed after the screenshot")+ actuator.scroll(direction, amount)+++def _scroll_windows(+ direction: str,+ amount: int,+ x: int | None,+ y: int | None,+ *,+ expected_window_signature: tuple[Any, ...] | None = None,+) -> int:"""Scroll via Win32 ``SendInput``; returns the signed wheel delta transmitted.Delegates to the shared CU v2 Windows backend. If both ``x`` and ``y``@@ -59,15 +90,36 @@ def _scroll_windows(direction: str, amount: int, x: int | None, y: int | None) -from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415- WindowsActuator().scroll(direction_l, amount, x=x, y=y)+ _scroll_with_verified_target(+ WindowsActuator(),+ direction_l,+ amount,+ x,+ y,+ expected_window_signature=expected_window_signature,+ )return _notch_for(direction_l, amount)-def _scroll_posix(direction: str, amount: int, x: int | None, y: int | None) -> int:+def _scroll_posix(+ direction: str,+ amount: int,+ x: int | None,+ y: int | None,+ *,+ expected_window_signature: tuple[Any, ...] | None = None,+) -> int:"""Cross-platform scroll via the actuate backend (pynput preferred)."""from jarvis.cu.actuate import get_actuator- get_actuator().scroll(direction.lower(), amount, x=x, y=y)+ _scroll_with_verified_target(+ get_actuator(),+ direction.lower(),+ amount,+ x,+ y,+ expected_window_signature=expected_window_signature,+ )return _notch_for(direction.lower(), amount)@@ -140,14 +192,32 @@ class ScrollTool:error="x and y must be integer coordinates",)+ expected_raw = args.get("_expected_window_signature")+ if expected_raw is not None and not isinstance(expected_raw, (list, tuple)):+ return ToolResult(+ success=False,+ output=None,+ error="Refusing scroll: invalid captured-window identity.",+ )+ expected_signature = (+ tuple(expected_raw) if expected_raw is not None else None+ )+if os.name == "nt":try:- await asyncio.to_thread(_scroll_windows, direction, amount, x, y)+ await asyncio.to_thread(+ _scroll_windows,+ direction,+ amount,+ x,+ y,+ expected_window_signature=expected_signature,+ )return ToolResult(success=True,output=f"Scrolled {direction} by {amount}",)- except (ValueError, OSError) as exc:+ except (ValueError, OSError, RuntimeError) as exc:return ToolResult(success=False,output=None,@@ -157,7 +227,14 @@ class ScrollTool:from jarvis.cu.actuate import ActuationUnavailabletry:- await asyncio.to_thread(_scroll_posix, direction, amount, x, y)+ await asyncio.to_thread(+ _scroll_posix,+ direction,+ amount,+ x,+ y,+ expected_window_signature=expected_signature,+ )return ToolResult(success=True,output=f"Scrolled {direction} by {amount}",diff --git a/jarvis/plugins/tool/type_text.py b/jarvis/plugins/tool/type_text.pyindex c7ad2f1866..a15bd40a17 100644--- a/jarvis/plugins/tool/type_text.py+++ b/jarvis/plugins/tool/type_text.py@@ -19,6 +19,26 @@ from jarvis.core.protocols import ExecutionContext, ToolResultlog = logging.getLogger(__name__)+class _ForegroundTargetChanged(RuntimeError):+ """Raised before input when the screenshot-bound window is no longer active."""+++def _type_for_expected_window(+ sender: Any,+ text: str,+ delay_s: float,+ expected_signature: tuple[Any, ...] | None,+) -> None:+ if expected_signature is not None:+ from jarvis.cu.target_guard import foreground_matches # noqa: PLC0415++ if not foreground_matches(expected_signature):+ raise _ForegroundTargetChanged(+ "foreground window changed after the screenshot"+ )+ sender(text, delay_s=delay_s)++def _build_windows_input_types() -> Any:"""Build the ctypes structs for SendInput keyboard injection.@@ -117,6 +137,16 @@ class TypeTextTool:delay_s = float(args.get("delay_s", 0.02))if not text:return ToolResult(success=False, output=None, error="text missing")+ expected_raw = args.get("_expected_window_signature")+ if expected_raw is not None and not isinstance(expected_raw, (list, tuple)):+ return ToolResult(+ success=False,+ output=None,+ error="Refusing text input: invalid captured-window identity.",+ )+ expected_signature = (+ tuple(expected_raw) if expected_raw is not None else None+ )# Windows: prefer the native KEYEVENTF_UNICODE SendInput path. It injects# the exact Unicode codepoint regardless of the active keyboard layout# (this machine runs German QWERTZ) and is far more robust into@@ -125,11 +155,23 @@ class TypeTextTool:# (CU typo bug 2026-06-15). pyautogui stays a best-effort fallback.if os.name == "nt":try:- await asyncio.to_thread(_send_text_windows, text, delay_s)+ await asyncio.to_thread(+ _type_for_expected_window,+ lambda value, *, delay_s: _send_text_windows(value, delay_s),+ text,+ delay_s,+ expected_signature,+ )return ToolResult(success=True,output=f"Typed {len(text)} chars via native Windows Unicode input",)+ except _ForegroundTargetChanged as exc:+ return ToolResult(+ success=False,+ output=None,+ error=f"Refusing text input: {exc}.",+ )except Exception as native_exc: # noqa: BLE001log.warning("native Unicode SendInput failed, falling back to pyautogui: %r",@@ -146,8 +188,23 @@ class TypeTextTool:error=f"text input unavailable: pyautogui import failed: {exc}",)try:- await asyncio.to_thread(pyautogui.typewrite, text, interval=delay_s)+ await asyncio.to_thread(+ _type_for_expected_window,+ lambda value, *, delay_s: pyautogui.typewrite(+ value,+ interval=delay_s,+ ),+ text,+ delay_s,+ expected_signature,+ )return ToolResult(success=True, output=f"Typed {len(text)} chars")+ except _ForegroundTargetChanged as exc:+ return ToolResult(+ success=False,+ output=None,+ error=f"Refusing text input: {exc}.",+ )except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None, error=str(exc))@@ -155,7 +212,13 @@ class TypeTextTool:try:actuator = get_actuator()- await asyncio.to_thread(actuator.type_text, text, delay_s=delay_s)+ await asyncio.to_thread(+ _type_for_expected_window,+ actuator.type_text,+ text,+ delay_s,+ expected_signature,+ )return ToolResult(success=True,output=f"Typed {len(text)} chars ({actuator.name})",@@ -166,5 +229,11 @@ class TypeTextTool:output=None,error=f"text input unavailable: {exc}",)+ except _ForegroundTargetChanged as exc:+ return ToolResult(+ success=False,+ output=None,+ error=f"Refusing text input: {exc}.",+ )except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None, error=str(exc))diff --git a/jarvis/plugins/tool/verify_localhost.py b/jarvis/plugins/tool/verify_localhost.pyindex db95091b91..2123896e51 100644--- a/jarvis/plugins/tool/verify_localhost.py+++ b/jarvis/plugins/tool/verify_localhost.py@@ -76,6 +76,17 @@ class VerifyLocalhostTool:import mss # type: ignore[import-not-found]import mss.tools+ from jarvis.vision.screenshot import ( # noqa: PLC0415+ warn_if_screen_recording_denied,+ )++ if warn_if_screen_recording_denied():+ raise PermissionError(+ "macOS Screen Recording permission is not granted. "+ "Grant it in Personal Jarvis > Settings > Permissions "+ "and retry."+ )+with mss.mss() as sct:sct_img = sct.shot()artifacts.append({"screenshot_path": sct_img})diff --git a/jarvis/vision/ax_tree.py b/jarvis/vision/ax_tree.pyindex 85595408c1..f212c5fc82 100644--- a/jarvis/vision/ax_tree.py+++ b/jarvis/vision/ax_tree.py@@ -15,12 +15,12 @@ and the model prompt are platform-agnostic. The only macOS-specific work is:``jarvis.vision.role_map.normalize_role`` so the emitted ``UIANode.role`` isexactly what the Windows source would have produced.-Permission gate (AD-13): before walking, ``observe`` checks-``AXIsProcessTrusted()``. If accessibility access is not granted it logs an-English onboarding message and returns an ``Observation`` with empty ``nodes``-and ``source="screenshot_only"`` — never raises. That empty-tree path self-gates-the consumers back to the already-working pixel-click loop, exactly like-``_foreground_clickable_labels`` returning ``[]`` (AD-6 / AD-OE6).+Permission gate (AD-13): before walking, ``observe`` checks the process-wide+system-permission port. That combines the live native Accessibility probe with+stable app identity and pending-restart enforcement. A missing/revoked grant+returns an ``Observation`` with empty ``nodes`` and+``source="screenshot_only"``; named-UI lookup and protected input remain+disabled until the grant is ready.Import-cleanliness contract (HN-7): the pyobjc frameworks(``Quartz`` / ``ApplicationServices`` / ``HIServices`` / ``AppKit``) are imported@@ -59,9 +59,9 @@ _DEPTH_RETRY_LADDER: tuple[int, ...] = (6, 5, 4)# Onboarding message surfaced once when the macOS Accessibility permission is# missing — English-only, per the Output Language Policy + AD-13._AX_PERMISSION_MSG = (- "macOS Accessibility permission not granted — grant it in "- "System Settings > Privacy & Security > Accessibility to enable named UI "- "clicks; falling back to pixel clicks."+ "macOS Accessibility permission is not ready — grant it to Personal "+ "Jarvis in System Settings > Privacy & Security > Accessibility, then "+ "restart Jarvis. Named UI lookup and protected input remain disabled.")@@ -107,7 +107,7 @@ class AXTreeSource:if cancel_token is not None and cancel_token.is_cancelled():raise RuntimeError(f"cancelled: {cancel_token.reason}")- # Permission gate (AD-13): never raise — degrade to the pixel path.+ # Permission gate (AD-13): never raise; protected input stays disabled.permission_check = self._permission_check or self._ax_is_process_trustedif not await asyncio.to_thread(permission_check):logger.warning(_AX_PERMISSION_MSG)@@ -193,22 +193,22 @@ class AXTreeSource:@staticmethoddef _ax_is_process_trusted() -> bool:- """Real ``AXIsProcessTrusted()`` probe (lazy pyobjc import, HN-7).+ """Unified live Accessibility + stable-app-identity gate.- Returns ``False`` when pyobjc is absent or the call raises — both mean- "cannot read the AX tree", which routes the caller to the pixel path.+ The process-wide permission port owns the uncached native TCC probe,+ stable bundle identity check, and pending-restart state. Imports remain+ lazy so this module is clean on Windows and headless Linux."""try:- from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415- AXIsProcessTrusted,+ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ get_system_permission_port,+ )+ return get_system_permission_port().runtime_access_granted(+ PermissionId.ACCESSIBILITY,)- except (ImportError, ModuleNotFoundError):- logger.warning("pyobjc (ApplicationServices) not installed — AX tree empty")- return False- try:- return bool(AXIsProcessTrusted())except Exception: # noqa: BLE001- logger.debug("AXIsProcessTrusted() raised", exc_info=True)+ logger.debug("Accessibility permission gate raised", exc_info=True)return Falsedef _empty_observation(self) -> Observation:@@ -317,6 +317,8 @@ class AXTreeSource:enabled=n.enabled,parent_index=n.parent_index,value=n.value,+ is_password=n.is_password,+ focused=n.focused,)for n in raw]@@ -358,6 +360,8 @@ _AX_IDENTIFIER = "AXIdentifier"_AX_POSITION = "AXPosition"_AX_SIZE = "AXSize"_AX_ENABLED = "AXEnabled"+_AX_FOCUSED = "AXFocused"+_AX_SUBROLE = "AXSubrole"_AX_CHILDREN = "AXChildren"@@ -396,29 +400,22 @@ def _ax_copy_attr(element: Any, attribute: str) -> Any:def _ax_point(value: Any) -> tuple[int, int]:- """Extract an (x, y) from an AX position value (CGPoint-like or dict)."""- if value is None:- return (0, 0)- if isinstance(value, dict):- return (int(value.get("x", 0)), int(value.get("y", 0)))- x = getattr(value, "x", None)- y = getattr(value, "y", None)- if x is not None and y is not None:- return (int(x), int(y))+ """Extract an (x, y) from an AX position value."""+ from jarvis.platform.macos_ax import decode_ax_point # noqa: PLC0415++ pair = decode_ax_point(value)+ if pair is not None:+ return (int(pair[0]), int(pair[1]))return (0, 0)def _ax_size(value: Any) -> tuple[int, int]:- """Extract a (w, h) from an AX size value (CGSize-like or dict)."""- if value is None:- return (0, 0)- if isinstance(value, dict):- return (int(value.get("w", value.get("width", 0))),- int(value.get("h", value.get("height", 0))))- w = getattr(value, "width", None)- h = getattr(value, "height", None)- if w is not None and h is not None:- return (int(w), int(h))+ """Extract a (w, h) from an AX size value."""+ from jarvis.platform.macos_ax import decode_ax_size # noqa: PLC0415++ pair = decode_ax_size(value)+ if pair is not None:+ return (int(pair[0]), int(pair[1]))return (0, 0)@@ -442,11 +439,18 @@ def _ax_flatten(returntry:native_role = str(_ax_copy_attr(element, _AX_ROLE) or "")+ native_subrole = str(_ax_copy_attr(element, _AX_SUBROLE) or "")canonical = normalize_role(native_role, "darwin")role = canonical or ""+ is_password = (+ native_role.casefold() == "axsecuretextfield"+ or native_subrole.casefold() == "axsecuretextfield"+ )+ focused = bool(_ax_copy_attr(element, _AX_FOCUSED) or False)+name = _ax_copy_attr(element, _AX_TITLE)- if not name:+ if not name and not is_password:name = _ax_copy_attr(element, _AX_VALUE)if not name:name = _ax_copy_attr(element, _AX_DESCRIPTION)@@ -464,7 +468,7 @@ def _ax_flatten(# L3 value-read: AXValue is the current text of an editable control# (search box, text field). Read separately from the name-fallback above# so the loop can see what a field already holds.- value = str(_ax_copy_attr(element, _AX_VALUE) or "")+ value = "" if is_password else str(_ax_copy_attr(element, _AX_VALUE) or "")except Exception: # noqa: BLE001return@@ -479,6 +483,8 @@ def _ax_flatten(depth=depth,parent_index=parent_index,value=value,+ is_password=is_password,+ focused=focused,))if depth >= max_depth:diff --git a/jarvis/vision/element_at_point.py b/jarvis/vision/element_at_point.pyindex 41f46b2663..5c7adab62e 100644--- a/jarvis/vision/element_at_point.py+++ b/jarvis/vision/element_at_point.py@@ -71,6 +71,28 @@ class AXPointerResolver(_BaseResolver):name = "macos-pointer"_native = staticmethod(lambda x, y: _ax_query_element_at_point(x, y))+ def at(self, x: int, y: int) -> PointerElement | None:+ """Query AX only for the canonical, currently authorized app process.++ This check deliberately runs for every point lookup: TCC grants can be+ revoked while Jarvis is running, and an ad-hoc Python/Terminal launch+ must never inherit a different executable's Accessibility grant.+ """+ try:+ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ get_system_permission_port,+ )++ if not get_system_permission_port().runtime_access_granted(+ PermissionId.ACCESSIBILITY,+ ):+ return None+ except Exception: # noqa: BLE001 - native permission failures fail closed+ log.debug("macOS Accessibility permission gate failed", exc_info=True)+ return None+ return super().at(x, y)+class AtspiPointerResolver(_BaseResolver):name = "linux-pointer"diff --git a/jarvis/vision/screenshot.py b/jarvis/vision/screenshot.pyindex 6a5512d4be..41b0da9ec5 100644--- a/jarvis/vision/screenshot.py+++ b/jarvis/vision/screenshot.py@@ -42,36 +42,39 @@ _DEFAULT_BLOB_DIR = Path("data") / "flight_recorder" / "blobs"# wallpaper with no error, so Computer-Use would click blind. Surface a clear# onboarding message at the capture site instead of failing silently._SCREEN_RECORDING_MSG = (- "macOS Screen Recording permission not granted — grant it in System "- "Settings > Privacy & Security > Screen Recording so Jarvis can see the "- "screen; without it screenshots capture only the desktop wallpaper and "- "Computer-Use would click blind."+ "macOS Screen Recording permission not granted — grant it in Personal "+ "Jarvis > Settings > Permissions or System Settings > Privacy & Security "+ "> Screen Recording; without it screenshots can contain only the desktop "+ "wallpaper and Computer-Use would click blind.")_screen_recording_warned = Falsedef warn_if_screen_recording_denied() -> bool:- """Log ``_SCREEN_RECORDING_MSG`` once per process if the macOS Screen- Recording grant is missing.+ """Probe Screen Recording now and log once per blocked-state episode.- Returns ``True`` iff capture is expected to be blank (macOS + the grant is- explicitly denied). No-op returning ``False`` on Windows/Linux, when the- grant is present, or when it is unknown (``None`` — pyobjc absent): we never- nag on a state we cannot prove (AD-13 detect-and-degrade).-- One-shot: once a denial has been seen the probe is not re-run, so the- TCC round-trip never happens at the CU frame rate (1-2 Hz) — subsequent- calls are a single boolean read.+ The native result is deliberately uncached: macOS can revoke a TCC grant+ while Jarvis is running. The boolean flag suppresses repeated log lines+ only; it never suppresses a permission probe. Unknown/unavailable native+ state fails closed on macOS and non-macOS reports ``NOT_REQUIRED``."""global _screen_recording_warned- if _screen_recording_warned: # already warned once → still denied; skip the per-frame TCC probe- return True- from jarvis.platform.probes import screen_recording_granted # noqa: PLC0415-- if screen_recording_granted() is False:+ from jarvis.platform.permissions import ( # noqa: PLC0415+ PermissionId,+ get_system_permission_port,+ )++ port = get_system_permission_port()+ blocked = not port.runtime_access_granted(PermissionId.SCREEN_RECORDING)+ if blocked:+ state = port.state(PermissionId.SCREEN_RECORDING)+ if not _screen_recording_warned:+ logger.warning("%s Native state: %s.", _SCREEN_RECORDING_MSG, state.value)_screen_recording_warned = True- logger.warning(_SCREEN_RECORDING_MSG)return True+ if _screen_recording_warned:+ logger.info("macOS Screen Recording permission is available again.")+ _screen_recording_warned = Falsereturn False@@ -123,7 +126,7 @@ def select_capture_monitor(Strategies:- - ``"foreground"`` — foreground-window center -> monitor lookup.+ - ``"foreground"`` — display with the largest foreground-window overlap.Fallback for a minimized/unfindable window: primary.- ``"primary"`` — explicitly the primary monitor (mss-typical ``[1]``).- ``"all"`` — virtual bounding box over all monitors (``[0]``).@@ -172,39 +175,41 @@ def select_capture_monitor()return primary- cx = rect[0] + rect[2] // 2- cy = rect[1] + rect[3] // 2-- for m in physical:- left, top = m["left"], m["top"]- right = left + m["width"]- bottom = top + m["height"]- if left <= cx < right and top <= cy < bottom:- if m is not primary:- logger.info(- "select_capture_monitor: foreground on %s "- "(left=%d top=%d %dx%d) — capturing there "- "instead of primary",- m.get("name"),- left,- top,- m["width"],- m["height"],- )- else:- logger.debug(- "select_capture_monitor: foreground on primary %s",- m.get("name"),- )- return m-- # Foreground center lies outside all physical monitors- # (e.g. window minimized -> rect = -32000/-32000).+ wl, wt, ww, wh = rect++ def overlap_area(m: dict) -> int:+ left = max(wl, int(m["left"]))+ top = max(wt, int(m["top"]))+ right = min(wl + ww, int(m["left"]) + int(m["width"]))+ bottom = min(wt + wh, int(m["top"]) + int(m["height"]))+ return max(0, right - left) * max(0, bottom - top)++ target = max(physical, key=overlap_area)+ target_overlap = overlap_area(target)+ if target_overlap > 0:+ if target is not primary:+ logger.info(+ "select_capture_monitor: largest foreground overlap is on %s "+ "(left=%d top=%d %dx%d) — capturing there instead of primary",+ target.get("name"),+ target["left"],+ target["top"],+ target["width"],+ target["height"],+ )+ else:+ logger.debug(+ "select_capture_monitor: largest foreground overlap is primary %s",+ target.get("name"),+ )+ return target++ # Foreground rectangle intersects no physical monitor (for example a+ # minimized window at -32000/-32000 or a stale window geometry read).logger.debug(- "select_capture_monitor: foreground center (%d,%d) is on no "- "monitor — falling back to primary",- cx,- cy,+ "select_capture_monitor: foreground rect %s is on no monitor — "+ "falling back to primary",+ rect,)return primaryexcept Exception: # noqa: BLE001@@ -276,6 +281,8 @@ def capture_region("""from PIL import Image # noqa: PLC0415+ if warn_if_screen_recording_denied():+ raise RuntimeError(_SCREEN_RECORDING_MSG)grabber = grab or _mss_grabsize, rgb = grabber(bbox)img = Image.frombytes("RGB", size, rgb)@@ -295,11 +302,10 @@ class ScreenshotSource:Monitor strategy (default: ``"foreground"``):- - ``"foreground"`` — follows the active window (GetForegroundWindow +- GetWindowRect → monitor lookup via the window's center point). This- way Jarvis sees what the user currently has in front of them, even on- multi-monitor setups. Fallback for a minimized/unfindable window:- the primary monitor.+ - ``"foreground"`` — follows the active window and selects the display+ with its largest window overlap. This remains correct for windows that+ straddle displays or whose center lies in an L-shaped layout gap.+ Fallback for a minimized/unfindable window: the primary monitor.- ``"primary"`` — the old hardcode (mss.monitors[1]). Only forregression tests / explicit single-monitor setups.- ``"all"`` — virtual bounding box over all monitors@@ -449,10 +455,10 @@ class ScreenshotSource:# mss not installed — ImportError already raised above, unreachable.ScreenShotError = Exception # type: ignore[assignment,misc]- # H1: on macOS without the Screen-Recording grant the grab below returns- # only the wallpaper with no error — tell the user once instead of- # letting Computer-Use click blind.- warn_if_screen_recording_denied()+ # H1: macOS can return only wallpaper without an error when Screen+ # Recording is missing. Probe on every capture and fail closed.+ if warn_if_screen_recording_denied():+ raise RuntimeError(_SCREEN_RECORDING_MSG)monitor_id: str = "unknown"try:diff --git a/tests/unit/cu/test_actuate.py b/tests/unit/cu/test_actuate.pyindex 9326d2528b..1d5ff49714 100644--- a/tests/unit/cu/test_actuate.py+++ b/tests/unit/cu/test_actuate.py@@ -6,13 +6,18 @@ desktop); real-input behaviour is exercised by scripts/cu_test_rig.py.from __future__ import annotationsimport os+import sys+import types+from dataclasses import FrozenInstanceErrorimport pytest+import jarvis.cu.actuate.base as base_modfrom jarvis.cu.actuate.base import (ActResult,ActuationUnavailable,Actuator,+ verified_click,verified_move,)from jarvis.cu.actuate.windows import (@@ -86,16 +91,189 @@ def test_verified_move_retry_recovers():assert res.ok and len(fake.moves) == 2-def test_verified_move_trusts_unreadable_cursor():- fake = FakeActuator(landings=[None])+def test_verified_move_refuses_unreadable_cursor():+ fake = FakeActuator(landings=[None, None])res = verified_move(fake, 50, 60)- assert res.ok and res.landed is None- assert "unverified" in res.detail+ assert not res.ok and res.landed is None+ assert "unreadable" in res.detail+ assert fake.moves == [(50, 60), (50, 60)]+++def test_verified_move_refuses_virtual_desktop_gap(monkeypatch):+ from jarvis.cu.geometry import MonitorInfo++ fake = FakeActuator(landings=[(150, 150)])+ monkeypatch.setattr(+ "jarvis.cu.geometry.list_monitors",+ lambda: [+ MonitorInfo(left=0, top=0, width=100, height=100),+ MonitorInfo(left=100, top=100, width=100, height=100),+ ],+ )++ res = verified_move(fake, 150, 50)++ assert res.ok is False+ assert "virtual-desktop gap" in res.detail+ assert fake.moves == []+++def test_verified_drag_refuses_gap_destination_before_button_down(monkeypatch):+ from jarvis.cu.actuate.base import verified_drag+ from jarvis.cu.geometry import MonitorInfo++ class _DragActuator(FakeActuator):+ def __init__(self):+ super().__init__([(10, 10)])+ self.drags = []++ def drag(self, *args, **kwargs):+ self.drags.append((args, kwargs))++ fake = _DragActuator()+ monkeypatch.setattr(+ "jarvis.cu.geometry.list_monitors",+ lambda: [MonitorInfo(left=0, top=0, width=100, height=100)],+ )++ result = verified_drag(fake, 10, 10, 150, 50)++ assert result.ok is False+ assert "virtual-desktop gap" in result.detail+ assert fake.moves == []+ assert fake.drags == []+++def test_verified_drag_refuses_path_crossing_display_gap(monkeypatch):+ from jarvis.cu.actuate.base import verified_drag+ from jarvis.cu.geometry import MonitorInfo++ class _DragActuator(FakeActuator):+ def __init__(self):+ super().__init__([(50, 50)])+ self.drags = []++ def drag_from_cursor(self, *args, **kwargs):+ self.drags.append((args, kwargs))++ fake = _DragActuator()+ monkeypatch.setattr(+ "jarvis.cu.geometry.list_monitors",+ lambda: [+ MonitorInfo(left=0, top=0, width=100, height=100),+ MonitorInfo(left=200, top=100, width=100, height=100),+ ],+ )++ result = verified_drag(fake, 50, 50, 250, 150)++ assert result.ok is False+ assert "path crosses" in result.detail+ assert fake.moves == []+ assert fake.drags == []+++def test_verified_click_refuses_backend_without_at_cursor_primitive(monkeypatch):+ fake = FakeActuator(landings=[(10, 20)])+ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ result = verified_click(fake, 10, 20)++ assert result.ok is False+ assert "at-cursor click" in result.detail+++def test_verified_click_rechecks_original_target_not_tolerated_landing(monkeypatch):+ class _ClickActuator(FakeActuator):+ def __init__(self):+ super().__init__([(11, 20)])+ self.expected = None++ def click_at_cursor(self, *, button, double, expected):+ self.expected = expected++ fake = _ClickActuator()+ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ result = verified_click(fake, 10, 20)++ assert result.ok is True+ assert fake.expected == (10, 20)+++def test_verified_click_rechecks_foreground_immediately_before_button(monkeypatch):+ class _ClickActuator(FakeActuator):+ def __init__(self):+ super().__init__([(10, 20)])+ self.clicked = False++ def click_at_cursor(self, *, button, double, expected):+ self.clicked = True++ fake = _ClickActuator()+ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ result = verified_click(fake, 10, 20, pre_action_check=lambda: False)++ assert result.ok is False+ assert "foreground window changed" in result.detail+ assert fake.clicked is False+++def test_verified_drag_uses_at_cursor_primitive(monkeypatch):+ from jarvis.cu.actuate.base import verified_drag++ class _DragActuator(FakeActuator):+ def __init__(self):+ super().__init__([(10, 10), (80, 90)])+ self.at_cursor_calls = []++ def drag(self, *args, **kwargs):+ raise AssertionError("drag() would repeat the verified start move")++ def drag_from_cursor(self, *args, **kwargs):+ self.at_cursor_calls.append((args, kwargs))++ fake = _DragActuator()+ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ result = verified_drag(fake, 10, 10, 80, 90, duration_s=0.2)++ assert result.ok is True+ assert fake.at_cursor_calls == [((10, 10, 80, 90), {"duration_s": 0.2})]+++def test_verified_drag_rechecks_foreground_before_button_down(monkeypatch):+ from jarvis.cu.actuate.base import verified_drag++ class _DragActuator(FakeActuator):+ def __init__(self):+ super().__init__([(10, 10)])+ self.dragged = False++ def drag_from_cursor(self, *args, **kwargs):+ self.dragged = True++ fake = _DragActuator()+ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ result = verified_drag(+ fake,+ 10,+ 10,+ 80,+ 90,+ pre_action_check=lambda: False,+ )++ assert result.ok is False+ assert "foreground window changed" in result.detail+ assert fake.dragged is Falsedef test_act_result_is_frozen():res = ActResult(ok=True)- with pytest.raises(Exception):+ with pytest.raises(FrozenInstanceError):res.ok = False # type: ignore[misc]@@ -126,6 +304,8 @@ def test_resolve_vk_letters_digits_and_names():assert resolve_vk("enter") == 0x0Dassert resolve_vk("Ctrl") == 0x11assert resolve_vk("f12") == 0x7B+ assert resolve_vk("option") == 0x12+ assert resolve_vk("command") == 0x5Bassert resolve_vk("bogus") is Noneassert resolve_vk("") is None@@ -163,12 +343,198 @@ def test_get_actuator_on_this_host():assert actuator.name.startswith("posix-")+def test_macos_input_permissions_fail_closed_before_backend_init(monkeypatch):+ from jarvis.platform.permissions import PermissionId, PermissionState++ probes: list[PermissionId] = []++ class _PermissionPort:+ def state(self, permission_id):+ return {+ PermissionId.ACCESSIBILITY: PermissionState.GRANTED,+ PermissionId.EVENT_POSTING: PermissionState.NOT_GRANTED,+ }[permission_id]++ def runtime_access_granted(self, permission_id):+ probes.append(permission_id)+ return permission_id is PermissionId.ACCESSIBILITY++ monkeypatch.setattr(base_mod.sys, "platform", "darwin")+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: _PermissionPort(),+ )++ with pytest.raises(ActuationUnavailable, match="Input Control"):+ base_mod.get_actuator()++ assert probes == [PermissionId.ACCESSIBILITY, PermissionId.EVENT_POSTING]+++def test_macos_input_permissions_are_rechecked_after_revocation(monkeypatch):+ from jarvis.platform.permissions import PermissionState++ states = [True, True, False, True]++ class _PermissionPort:+ def runtime_access_granted(self, _permission_id):+ return states.pop(0)++ def state(self, _permission_id):+ return PermissionState.NOT_GRANTED++ monkeypatch.setattr(base_mod.sys, "platform", "darwin")+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: _PermissionPort(),+ )++ base_mod._require_macos_input_permissions()+ with pytest.raises(ActuationUnavailable, match="Accessibility"):+ base_mod._require_macos_input_permissions()++ assert states == []++def test_pynput_key_table_maps_core_vocabulary():keyboard = pytest.importorskip("pynput.keyboard", reason="pynput not installed")from jarvis.cu.actuate.posix import _pynput_key_tabletable = _pynput_key_table(keyboard)- for name in ("ctrl", "shift", "alt", "enter", "tab", "esc", "left", "f5"):+ for name in (+ "ctrl", "shift", "alt", "option", "enter", "tab", "esc", "left", "f5",+ ):assert name in table# Off-Windows "win" must resolve to the platform super/command key.assert "win" in table+++def test_macos_cursor_readback_uses_quartz_global_coordinates(monkeypatch):+ from jarvis.cu.actuate.posix import PosixActuator++ quartz = types.SimpleNamespace(+ CGEventCreate=lambda _source: object(),+ CGEventGetLocation=lambda _event: types.SimpleNamespace(x=-1440, y=525),+ )+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setitem(sys.modules, "Quartz", quartz)++ class _Mouse:+ @property+ def position(self):+ raise AssertionError("pynput getter used")++ actuator = object.__new__(PosixActuator)+ actuator._mouse = _Mouse()+ actuator._pyautogui = None++ assert actuator.cursor_pos() == (-1440, 525)+++def test_macos_pyautogui_fallback_maps_command_and_option(monkeypatch):+ from jarvis.cu.actuate.posix import PosixActuator++ sent: list[tuple[str, ...]] = []+ actuator = object.__new__(PosixActuator)+ actuator._keyboard = None+ actuator._pyautogui = types.SimpleNamespace(+ hotkey=lambda *keys: sent.append(keys),+ )+ monkeypatch.setattr(sys, "platform", "darwin")++ actuator.key_combo(["cmd", "option", "left"])++ assert sent == [("command", "alt", "left")]+++def _fake_quartz_mouse(monkeypatch, *, location=(-1440, 525)):+ posted: list[types.SimpleNamespace] = []++ def create_mouse(_source, event_type, point, button):+ return types.SimpleNamespace(+ event_type=event_type,+ point=tuple(point),+ button=button,+ click_state=None,+ )++ quartz = types.SimpleNamespace(+ CGEventCreate=lambda _source: object(),+ CGEventGetLocation=lambda _event: types.SimpleNamespace(+ x=location[0], y=location[1],+ ),+ CGEventCreateMouseEvent=create_mouse,+ CGEventSetIntegerValueField=lambda event, _field, value: setattr(+ event, "click_state", value,+ ),+ CGEventPost=lambda _tap, event: posted.append(event),+ kCGHIDEventTap=1,+ kCGMouseEventClickState=2,+ kCGEventMouseMoved=3,+ kCGEventLeftMouseDown=4,+ kCGEventLeftMouseUp=5,+ kCGEventLeftMouseDragged=6,+ kCGEventRightMouseDown=7,+ kCGEventRightMouseUp=8,+ kCGEventRightMouseDragged=9,+ kCGEventOtherMouseDown=10,+ kCGEventOtherMouseUp=11,+ kCGEventOtherMouseDragged=12,+ kCGMouseButtonLeft=0,+ kCGMouseButtonRight=1,+ kCGMouseButtonCenter=2,+ )+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setitem(sys.modules, "Quartz", quartz)+ return posted+++def test_macos_quartz_double_click_uses_exact_global_point_and_click_states(+ monkeypatch,+):+ from jarvis.cu.actuate.posix import PosixActuator++ posted = _fake_quartz_mouse(monkeypatch)+ actuator = object.__new__(PosixActuator)+ actuator._mouse = object()+ actuator._pyautogui = None++ actuator.click_at_cursor(+ button="left",+ double=True,+ expected=(-1440, 525),+ )++ assert [event.event_type for event in posted] == [4, 5, 4, 5]+ assert [event.point for event in posted] == [(-1440, 525)] * 4+ assert [event.click_state for event in posted] == [1, 1, 2, 2]+++def test_macos_quartz_click_refuses_cursor_changed_after_verification(monkeypatch):+ from jarvis.cu.actuate.posix import PosixActuator++ posted = _fake_quartz_mouse(monkeypatch, location=(200, 300))+ actuator = object.__new__(PosixActuator)+ actuator._mouse = object()+ actuator._pyautogui = None++ with pytest.raises(RuntimeError, match="cursor moved"):+ actuator.click_at_cursor(expected=(100, 100))++ assert posted == []+++def test_macos_quartz_drag_posts_down_dragged_endpoint_and_up(monkeypatch):+ from jarvis.cu.actuate.posix import PosixActuator++ posted = _fake_quartz_mouse(monkeypatch, location=(10, 20))+ actuator = object.__new__(PosixActuator)+ actuator._mouse = object()+ actuator._pyautogui = None++ actuator.drag_from_cursor(10, 20, 30, 40, duration_s=0.0)++ assert [event.event_type for event in posted] == [4, 6, 6, 5]+ assert posted[0].point == (10, 20)+ assert posted[-2].point == (30, 40)+ assert posted[-1].point == (30, 40)diff --git a/tests/unit/cu/test_capture.py b/tests/unit/cu/test_capture.pyindex fe3a485a63..a0def63bf1 100644--- a/tests/unit/cu/test_capture.py+++ b/tests/unit/cu/test_capture.py@@ -81,6 +81,84 @@ def test_stable_screen_returns_after_one_regrab():assert frame.jpeg[:2] == b"\xff\xd8" # JPEG magic+def test_macos_screen_recording_denial_stops_before_grab(monkeypatch):+ from jarvis.platform.permissions import PermissionState++ calls = {"grab": 0, "probe": 0}++ class _DeniedPort:+ def runtime_access_granted(self, _permission_id):+ calls["probe"] += 1+ return False++ def state(self, _permission_id):+ return PermissionState.NOT_GRANTED++ monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: _DeniedPort(),+ )++ def grab(_bbox):+ calls["grab"] += 1+ return _solid((192, 108), (10, 20, 30))++ with pytest.raises(RuntimeError, match="Screen Recording"):+ capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)++ assert calls == {"grab": 0, "probe": 1}+++def test_macos_screen_recording_is_rechecked_before_each_grab(monkeypatch):+ from jarvis.platform.permissions import PermissionState++ states = [True, False]+ calls = {"grab": 0}++ class _RevokedPort:+ def runtime_access_granted(self, _permission_id):+ return states.pop(0)++ def state(self, _permission_id):+ return PermissionState.NOT_GRANTED++ monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: _RevokedPort(),+ )++ def grab(_bbox):+ calls["grab"] += 1+ return _solid((192, 108), (10, 20, 30))++ with pytest.raises(RuntimeError, match="Screen Recording"):+ capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)++ assert calls["grab"] == 1+ assert states == []+++def test_capture_guard_rechecks_window_identity_around_each_grab():+ checks = iter((True, False))+ calls = {"grab": 0}++ def grab(_bbox):+ calls["grab"] += 1+ return _solid((192, 108), (10, 20, 30))++ with pytest.raises(RuntimeError, match="during screen capture"):+ capture_stable_frame(+ _monitor(),+ grab=grab,+ sleep=lambda _s: None,+ capture_guard=lambda: next(checks),+ )++ assert calls["grab"] == 1++def test_animating_screen_times_out_unstable():shade = {"v": 0}diff --git a/tests/unit/cu/test_conventions_ledger_verify.py b/tests/unit/cu/test_conventions_ledger_verify.pyindex cc087f53c2..e2dcb2b1f5 100644--- a/tests/unit/cu/test_conventions_ledger_verify.py+++ b/tests/unit/cu/test_conventions_ledger_verify.py@@ -14,6 +14,7 @@ from jarvis.cu.verify import (crop_raw,element_is_focused,field_values_hint,+ foreground_ui_snapshot,human_handoff_reason,regions_equal,typed_text_landed,@@ -276,10 +277,16 @@ def test_field_values_hint_lists_filled_fields_only():def test_human_handoff_reasons():- assert human_handoff_reason((_node(role="Text", name="Complete the reCAPTCHA"),)) == "captcha challenge"- assert human_handoff_reason((_node(role="Text", name="Enter the verification code"),)) == "two-factor / one-time code"+ assert human_handoff_reason(+ (_node(role="Text", name="Complete the reCAPTCHA"),),+ ) == "captcha challenge"+ assert human_handoff_reason(+ (_node(role="Text", name="Enter the verification code"),),+ ) == "two-factor / one-time code"assert human_handoff_reason((_node(role="Edit", name="Password"),)) == "login / password entry"- assert human_handoff_reason((_node(role="Edit", name="", is_password=True),)) == "login / password entry"+ assert human_handoff_reason(+ (_node(role="Edit", name="", is_password=True),),+ ) == "login / password entry"# A "Change password" BUTTON alone must not trip the handoff.assert human_handoff_reason((_node(role="Button", name="Change password"),)) is Noneassert human_handoff_reason(()) is None@@ -297,6 +304,24 @@ def test_clickable_labels_filters_roles_and_dedupes():assert clickable_labels(nodes) == ["OK", "File"]+async def test_ui_snapshot_guard_rejects_foreground_switch(monkeypatch):+ class _Source:+ async def observe(self):+ return SimpleNamespace(nodes=())++ checks = iter((True, False))+ monkeypatch.setattr(+ "jarvis.cu.verify._get_ui_tree_source",+ lambda: _Source(),+ )++ with pytest.raises(RuntimeError, match="during UI-tree observation"):+ await foreground_ui_snapshot(+ observation_guard=lambda: next(checks),+ )++def test_snap_point_to_element_smallest_containing_rect_wins():from jarvis.cu.verify import snap_point_to_elementdiff --git a/tests/unit/cu/test_engine_loop.py b/tests/unit/cu/test_engine_loop.pyindex d8ae400c7f..f61cb9066a 100644--- a/tests/unit/cu/test_engine_loop.py+++ b/tests/unit/cu/test_engine_loop.py@@ -92,6 +92,8 @@ def patched(monkeypatch, tmp_path):clickables=[],focus_hit=None, # verify_click_focus_point verdictcapture_calls=0, # capture_stable_frame invocations+ foreground_handle=11,+ foreground_rect=(0, 0, 192, 108),)def fake_select_capture_target(@@ -107,6 +109,7 @@ def patched(monkeypatch, tmp_path):sleep=lambda s: None,max_dimension=max_dimension,blob_dir=Path(tmp_path),+ capture_guard=kw.get("capture_guard"),)def fake_grab_region(bbox, *, grab=None):@@ -131,6 +134,7 @@ def patched(monkeypatch, tmp_path):monkeypatch.setattr(engine_mod, "select_capture_target", fake_select_capture_target,)+ monkeypatch.setattr(engine_mod, "list_monitors", lambda: [MONITOR])monkeypatch.setattr(engine_mod, "capture_stable_frame", fake_capture)monkeypatch.setattr(engine_mod, "grab_region", fake_grab_region)monkeypatch.setattr(engine_mod, "foreground_ui_snapshot", fake_snapshot)@@ -146,6 +150,14 @@ def patched(monkeypatch, tmp_path):monkeypatch.setattr(ws, "normalize_foreground_window", lambda: (False, "test"),)+ monkeypatch.setattr(+ ws,+ "foreground_window",+ lambda: ws.WindowInfo("Test Window", handle=state.foreground_handle),+ )+ monkeypatch.setattr(+ ws, "window_frame_rect", lambda _window: state.foreground_rect,+ )return state@@ -177,6 +189,27 @@ async def test_done_is_verified_and_proof_flows_to_stdout(patched):assert "[cu] done (verified: the calculator shows 8)" in final.stdout+async def test_dispatch_refuses_action_after_screen_permission_revocation(+ monkeypatch,+):+ executor = FakeExecutor()+ ctx = _ctx(FakeBrain([]), executor)+ monkeypatch.setattr(+ "jarvis.cu.capture._require_macos_screen_recording_permission",+ lambda: (_ for _ in ()).throw(+ RuntimeError("Screen Recording permission was revoked"),+ ),+ )++ ok, detail = await engine_mod._dispatch_tool(+ ctx, "click", {"x": 10, "y": 10}, trace_id=None,+ )++ assert ok is False+ assert "Screen Recording" in detail+ assert executor.calls == []++async def test_rejected_done_feeds_history_and_eventually_fails(patched):brain = FakeBrain(['{"action": "done", "reason": "sure"}',@@ -240,6 +273,95 @@ async def test_second_pointer_action_in_one_batch_is_skipped(patched):assert any("only one pointer action" in user for (_, user) in brain.calls)+async def test_click_then_click_element_in_one_batch_is_skipped(patched):+ brain = FakeBrain([+ '[{"action":"click","x":100,"y":100},'+ '{"action":"click_element","name":"Continue"}]',+ '{"action": "done", "reason": "clicked"}',+ '{"done": true, "proof": "the dialog advanced"}',+ ])+ executor = FakeExecutor()++ chunks = await _run(_ctx(brain, executor))++ assert _final(chunks).exit_code == 0+ assert [name for name, _args in executor.calls].count("click") == 1+ assert not any(name == "click_element" for name, _args in executor.calls)+ assert any("only one pointer action" in user for _system, user in brain.calls)+++async def test_foreground_change_after_model_decision_refuses_action(patched):+ class _FocusChangingBrain(FakeBrain):+ async def complete_text(self, *, system: str, user: str) -> str:+ reply = await super().complete_text(system=system, user=user)+ if len(self.calls) == 1:+ patched.foreground_handle = 22+ return reply++ brain = _FocusChangingBrain([+ '{"action":"click","x":500,"y":500}',+ '{"action":"fail","reason":"the target window changed"}',+ ])+ executor = FakeExecutor()++ chunks = await _run(_ctx(brain, executor))++ assert _final(chunks).exit_code == 5+ assert executor.calls == []+ assert any("foreground window changed" in user for _system, user in brain.calls)+++async def test_foreground_change_during_capture_discards_stale_frame(+ patched,+ monkeypatch,+):+ from jarvis.platform import window_state as ws++ handles = iter((11, 22, 22, 22))+ monkeypatch.setattr(+ ws,+ "foreground_window",+ lambda: ws.WindowInfo("Test Window", handle=next(handles, 22)),+ )+ brain = FakeBrain([+ '{"action":"fail","reason":"fresh frame reached the model"}',+ ])+ executor = FakeExecutor()++ chunks = await _run(_ctx(brain, executor))++ assert _final(chunks).exit_code == 5+ assert patched.capture_calls == 2+ assert len(brain.calls) == 1+ assert executor.calls == []+++async def test_coordinate_less_scroll_targets_capture_center_and_stales_batch(patched):+ brain = FakeBrain([+ '[{"action":"scroll","direction":"down","amount":2},'+ '{"action":"click","x":900,"y":900}]',+ '{"action": "done", "reason": "scrolled"}',+ '{"done": true, "proof": "the target is visible"}',+ ])+ executor = FakeExecutor()++ chunks = await _run(_ctx(brain, executor))++ assert _final(chunks).exit_code == 0+ scrolls = [args for name, args in executor.calls if name == "scroll"]+ assert scrolls == [+ {+ "direction": "down",+ "amount": 2,+ "x": 96,+ "y": 54,+ "_expected_window_signature": ("handle", 11, (0, 0, 192, 108)),+ }+ ]+ assert not any(name == "click" for name, _args in executor.calls)+ assert any("only one pointer action" in user for _system, user in brain.calls)++async def test_done_judge_reuses_the_step_frame_when_no_action_ran(patched):# "Say you are done FAST": when `done` arrives before any action of the# batch executed, the screen is exactly the frame the model saw — the@@ -339,6 +461,25 @@ async def test_clear_first_sends_platform_select_all(patched):assert _final(chunks).exit_code == 0hotkeys = [args for (name, args) in executor.calls if name == "hotkey"]assert hotkeys and hotkeys[0]["keys"][-1] == "a"+ assert hotkeys[0]["_expected_window_signature"] == (+ "handle",+ 11,+ (0, 0, 192, 108),+ )+++async def test_clear_first_aborts_typing_when_select_all_fails(patched):+ brain = FakeBrain([+ '{"action":"type","text":"replacement","clear_first":true}',+ '{"action":"fail","reason":"keyboard shortcut unavailable"}',+ ])+ executor = FakeExecutor(failures={"hotkey"})++ chunks = await _run(_ctx(brain, executor))++ assert _final(chunks).exit_code == 5+ assert not any(name == "type_text" for name, _args in executor.calls)+ assert any("refusing to append" in user for _system, user in brain.calls)async def test_cancelled_token_stops_immediately(patched):@@ -423,6 +564,34 @@ async def test_verified_miss_triggers_one_zoom_refined_retry(patched):clicks = [args for (name, args) in executor.calls if name == "click"]assert len(clicks) == 2, "exactly one refined retry after the verified miss"assert (clicks[1]["x"], clicks[1]["y"]) != (clicks[0]["x"], clicks[0]["y"])+ assert all(+ args["_expected_window_signature"][0:2] == ("handle", 11)+ for args in clicks+ )+++async def test_zoom_refine_refuses_click_after_foreground_switch(patched):+ patched.region_changes_after_click = False++ class _SwitchDuringRefineBrain(FakeBrain):+ async def complete_text(self, *, system: str, user: str) -> str:+ reply = await super().complete_text(system=system, user=user)+ if len(self.calls) == 2:+ patched.foreground_handle = 22+ return reply++ brain = _SwitchDuringRefineBrain([+ '{"action": "click", "x": 500, "y": 500, "target": "tiny icon"}',+ '{"found": true, "x": 900, "y": 900}',+ '{"action": "fail", "reason": "the original window lost focus"}',+ ])+ executor = FakeExecutor()++ chunks = await _run(_ctx(brain, executor))++ assert _final(chunks).exit_code == 5+ clicks = [args for name, args in executor.calls if name == "click"]+ assert len(clicks) == 1, "the stale zoom-refined click must not execute"async def test_handoff_screen_fails_fast_with_speakable_reason(patched, monkeypatch):diff --git a/tests/unit/cu/test_target_guard.py b/tests/unit/cu/test_target_guard.pynew file mode 100644index 0000000000..1e15f91e39--- /dev/null+++ b/tests/unit/cu/test_target_guard.py@@ -0,0 +1,46 @@+"""Foreground identity reads share the CU per-thread input coordinate space."""+from __future__ import annotations++from contextlib import contextmanager++from jarvis.cu.target_guard import read_foreground_target+from jarvis.platform.window_state import WindowInfo+++def test_foreground_target_reads_window_and_rect_inside_input_space(monkeypatch):+ state = {"inside": False, "entered": 0, "exited": 0}+ window = WindowInfo("Editor", handle=77)++ @contextmanager+ def fake_input_space():+ state["entered"] += 1+ state["inside"] = True+ try:+ yield+ finally:+ state["inside"] = False+ state["exited"] += 1++ def foreground_window():+ assert state["inside"] is True+ return window++ def window_frame_rect(actual):+ assert state["inside"] is True+ assert actual is window+ return (100, 50, 800, 600)++ monkeypatch.setattr("jarvis.cu.geometry.input_space", fake_input_space)+ monkeypatch.setattr(+ "jarvis.platform.window_state.foreground_window",+ foreground_window,+ )+ monkeypatch.setattr(+ "jarvis.platform.window_state.window_frame_rect",+ window_frame_rect,+ )++ target = read_foreground_target()++ assert target.signature == ("handle", 77, (100, 50, 800, 600))+ assert state == {"inside": False, "entered": 1, "exited": 1}diff --git a/tests/unit/harness/test_action_registry.py b/tests/unit/harness/test_action_registry.pyindex 92ea8eb87f..552fadac38 100644--- a/tests/unit/harness/test_action_registry.py+++ b/tests/unit/harness/test_action_registry.py@@ -32,7 +32,6 @@ from jarvis.harness.action_registry import (build_default_registry,)-# ---------------------------------------------------------------------# Vocabulary coverage# ---------------------------------------------------------------------@@ -141,9 +140,38 @@ def test_transform_press_shortcut_missing_args_raises() -> None:_transform_press_shortcut({})-def test_transform_open_terminal_default_is_wt() -> None:+ ("platform_name", "expected_app"),+ (("win32", "wt"), ("darwin", "terminal"), ("linux", "terminal")),+)+def test_transform_open_terminal_default_is_platform_native(+ monkeypatch,+ platform_name: str,+ expected_app: str,+) -> None:+ monkeypatch.setattr(+ "jarvis.harness.action_registry.detect_platform",+ lambda: platform_name,+ )result = _transform_open_terminal({})- assert result == {"app_name": "wt", "arguments": ""}+ assert result == {"app_name": expected_app, "arguments": ""}+++ ("platform_name", "expected_app"),+ (("win32", "wt"), ("darwin", "terminal"), ("linux", "terminal")),+)+def test_transform_open_terminal_generic_alias_is_platform_native(+ monkeypatch,+ platform_name: str,+ expected_app: str,+) -> None:+ monkeypatch.setattr(+ "jarvis.harness.action_registry.detect_platform",+ lambda: platform_name,+ )+ result = _transform_open_terminal({"profile": "terminal"})+ assert result["app_name"] == expected_appdef test_transform_open_terminal_profile_aliases() -> None:@@ -158,8 +186,52 @@ def test_transform_open_terminal_passthrough_for_custom_path() -> None:assert result["app_name"] == "/usr/local/bin/iterm2"+ (+ "platform_name",+ "new_tab_combo",+ "window_switch_combo",+ "restore_tab_combo",+ "terminal_name",+ ),+ (+ ("win32", "ctrl+t", "alt+tab", "ctrl+shift+t", "Windows Terminal"),+ ("darwin", "cmd+t", "cmd+tab", "cmd+shift+t", "Terminal"),+ ("linux", "ctrl+t", "alt+tab", "ctrl+shift+t", "Terminal"),+ ),+)+def test_registry_planner_vocabulary_is_platform_native(+ monkeypatch,+ platform_name: str,+ new_tab_combo: str,+ window_switch_combo: str,+ restore_tab_combo: str,+ terminal_name: str,+) -> None:+ monkeypatch.setattr(+ "jarvis.harness.action_registry.detect_platform",+ lambda: platform_name,+ )+ registry = build_default_registry()+ shortcut = registry.get("press_shortcut")+ terminal = registry.get("open_terminal")+ new_tab = registry.get("open_new_tab")++ assert shortcut is not None+ assert new_tab_combo in shortcut.description+ assert window_switch_combo in shortcut.description+ assert restore_tab_combo in shortcut.description+ assert new_tab_combo in shortcut.arg_schema["combo"]+ assert terminal is not None and terminal_name in terminal.description+ assert new_tab is not None and new_tab_combo in new_tab.description+ if platform_name == "darwin":+ assert "ctrl+t" not in shortcut.description+ assert "alt+tab" not in shortcut.description+ assert "Windows Terminal" not in terminal.description++# ----------------------------------------------------------------------# Composite-Runners — ohne echte Tools, mit Fake-Executor+# Composite runners with fake tools and an in-memory executor# ---------------------------------------------------------------------class _FakeExecutor:@@ -196,8 +268,19 @@ class _FakeTool:@pytest.mark.asyncio-async def test_composite_open_new_tab_calls_hotkey_with_ctrl_t() -> None:- """open_new_tab must send exactly ctrl+T — that's the universal tab shortcut."""+ ("platform_name", "modifier"),+ (("win32", "ctrl"), ("darwin", "cmd"), ("linux", "ctrl")),+)+async def test_composite_open_new_tab_uses_platform_shortcut(+ monkeypatch,+ platform_name: str,+ modifier: str,+) -> None:+ monkeypatch.setattr(+ "jarvis.harness.action_registry.detect_platform",+ lambda: platform_name,+ )executor = _FakeExecutor()tools = {"hotkey": _FakeTool("hotkey")}@@ -206,7 +289,7 @@ async def test_composite_open_new_tab_calls_hotkey_with_ctrl_t() -> None:assert result.success is Trueassert len(executor.calls) == 1assert executor.calls[0]["tool"] == "hotkey"- assert executor.calls[0]["args"] == {"keys": ["ctrl", "t"]}+ assert executor.calls[0]["args"] == {"keys": [modifier, "t"]}@pytest.mark.asynciodiff --git a/tests/unit/harness/test_cu_engine_switch.py b/tests/unit/harness/test_cu_engine_switch.pyindex f5124d15f4..8833a39c21 100644--- a/tests/unit/harness/test_cu_engine_switch.py+++ b/tests/unit/harness/test_cu_engine_switch.py@@ -97,16 +97,16 @@ def _patch_engine(monkeypatch, value: str) -> None:)-def test_selector_picks_june13_when_configured(monkeypatch):+def test_selector_routes_june13_to_guarded_v2(monkeypatch):_patch_engine(monkeypatch, "june13")loop = harness._resolve_run_cu_loop()- assert loop.__module__ == "jarvis.harness.screenshot_only_loop_june13"+ assert loop.__module__ == "jarvis.cu.engine"-def test_selector_picks_current_when_configured(monkeypatch):+def test_selector_routes_current_to_guarded_v2(monkeypatch):_patch_engine(monkeypatch, "current")loop = harness._resolve_run_cu_loop()- assert loop.__module__ == "jarvis.harness.screenshot_only_loop"+ assert loop.__module__ == "jarvis.cu.engine"def test_selector_picks_v2_when_configured(monkeypatch):@@ -115,11 +115,19 @@ def test_selector_picks_v2_when_configured(monkeypatch):assert loop.__module__ == "jarvis.cu.engine"-def test_selector_picks_stable_when_configured(monkeypatch):- # The pre-Wave-1 frozen fallback the user flips to if the new work misbehaves.+def test_selector_refuses_unguarded_legacy_engines_on_macos(monkeypatch):+ _patch_engine(monkeypatch, "current")+ monkeypatch.setattr(harness.sys, "platform", "darwin")++ loop = harness._resolve_run_cu_loop()++ assert loop.__module__ == "jarvis.cu.engine"+++def test_selector_routes_stable_to_guarded_v2(monkeypatch):_patch_engine(monkeypatch, "stable")loop = harness._resolve_run_cu_loop()- assert loop.__module__ == "jarvis.harness.screenshot_only_loop_stable"+ assert loop.__module__ == "jarvis.cu.engine"def test_selector_falls_back_to_default_engine_on_config_error(monkeypatch):diff --git a/tests/unit/harness/test_cu_screenshot_fastpath.py b/tests/unit/harness/test_cu_screenshot_fastpath.pyindex 3d6da1fbd8..161596328d 100644--- a/tests/unit/harness/test_cu_screenshot_fastpath.py+++ b/tests/unit/harness/test_cu_screenshot_fastpath.py@@ -288,3 +288,25 @@ async def test_compound_screenshot_goal_uses_the_loop_not_the_fast_path(assert called["n"] == 0assert ctx.vision_engine.calls >= 1+++ "module_name",+ (+ "jarvis.harness.screenshot_only_loop",+ "jarvis.harness.screenshot_only_loop_stable",+ ),+)+def test_legacy_save_screenshot_fails_closed_when_recording_is_denied(+ monkeypatch: pytest.MonkeyPatch,+ module_name: str,+) -> None:+ import importlib++ module = importlib.import_module(module_name)+ monkeypatch.setattr(+ "jarvis.vision.screenshot.warn_if_screen_recording_denied",+ lambda: True,+ )++ assert module._save_user_screenshot() is Nonediff --git a/tests/unit/platform/test_window_state.py b/tests/unit/platform/test_window_state.pyindex 075a0701d3..133f6bbc57 100644--- a/tests/unit/platform/test_window_state.py+++ b/tests/unit/platform/test_window_state.py@@ -2,17 +2,16 @@enumeration / focus / already-running detection behind the platform seam.Seam-level only: the platform is forced via detect_platform/probes and the-ctypes/osascript/wmctrl backends are faked or monkeypatched — this proves the+ctypes/Quartz/AppKit/AX/wmctrl backends are faked or monkeypatched — this proves thedispatch + parsing + matching logic, NOT that real OS APIs behave as assumed onreal hardware (SIGNOFF-LOG honesty)."""from __future__ import annotationsimport subprocess+import sysimport types-import pytest-from jarvis.platform import window_state as wsfrom jarvis.platform.window_state import WindowInfo@@ -21,6 +20,23 @@ def _cp(returncode: int, stdout: str = "", stderr: str = ""):return types.SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)+def _patch_macos_accessibility(monkeypatch, *, granted: bool) -> None:+ from jarvis.platform.permissions import PermissionState++ port = types.SimpleNamespace(+ runtime_access_granted=lambda _permission_id: granted,+ state=lambda _permission_id: (+ PermissionState.GRANTED+ if granted+ else PermissionState.NOT_GRANTED+ ),+ )+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: port,+ )++# --- WindowInfo basics ------------------------------------------------------@@ -152,14 +168,65 @@ def test_list_windows_linux_parses_wmctrl(monkeypatch):assert "Terminal" in titles-def test_list_windows_macos_parses_osascript(monkeypatch):+def test_list_windows_macos_parses_quartz_catalog(monkeypatch):monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- # newline-separated window titles, one per line- monkeypatch.setattr(subprocess, "run", lambda *a, **k: _cp(0, stdout="OBS\nSafari — Apple\n"))+ monkeypatch.setattr(+ ws,+ "_quartz_window_list",+ lambda **_kwargs: [+ {"kCGWindowLayer": 0, "kCGWindowName": "OBS", "kCGWindowNumber": 1},+ {+ "kCGWindowLayer": 0,+ "kCGWindowName": "Safari — Apple",+ "kCGWindowNumber": 2,+ "kCGWindowIsOnscreen": False,+ },+ {"kCGWindowLayer": 8, "kCGWindowName": "Overlay", "kCGWindowNumber": 3},+ ],+ )titles = [w.title for w in ws.list_windows()]assert "OBS" in titlesassert "Safari — Apple" in titles+ assert "Overlay" not in titles+ safari = next(window for window in ws.list_windows() if window.title == "Safari — Apple")+ assert safari.minimized is False, "another Space is not the same as minimized"+++def test_list_windows_macos_reads_ax_minimized_instead_of_onscreen_flag(monkeypatch):+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")+ _patch_macos_accessibility(monkeypatch, granted=True)+ monkeypatch.setattr(+ ws,+ "_quartz_window_list",+ lambda **_kwargs: [{+ "kCGWindowLayer": 0,+ "kCGWindowName": "Hidden notes",+ "kCGWindowOwnerPID": 42,+ "kCGWindowNumber": 9,+ "kCGWindowIsOnscreen": False,+ }],+ )+ root = object()+ window = object()++ def copy_attr(element, attribute, _out):+ if element is root and attribute == "AXWindows":+ return 0, [window]+ if element is window and attribute == "AXTitle":+ return 0, "Hidden notes"+ if element is window and attribute == "AXMinimized":+ return 0, True+ return 1, None++ monkeypatch.setitem(sys.modules, "ApplicationServices", types.SimpleNamespace(+ AXUIElementCreateApplication=lambda _pid: root,+ AXUIElementCopyAttributeValue=copy_attr,+ ))++ windows = ws.list_windows()++ assert len(windows) == 1+ assert windows[0].minimized is Truedef test_list_windows_linux_decodes_non_utf8_locale_titles(monkeypatch):@@ -184,18 +251,19 @@ def test_list_windows_linux_decodes_non_utf8_locale_titles(monkeypatch):assert any("café" in t for t in titles)-def test_list_windows_macos_decodes_non_utf8_locale_titles(monkeypatch):+def test_list_windows_macos_preserves_unicode_quartz_titles(monkeypatch):monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")-- def _fake_run(*args, **kwargs):- if kwargs.get("encoding") != "utf-8" or kwargs.get("errors") != "replace":- raise UnicodeDecodeError("cp1252", b"\xff\xfe", 0, 1, "invalid byte")- return _cp(0, stdout="Safäri — 日本語\n") # i18n-allow: non-ASCII title fixture (encoding under test)-- monkeypatch.setattr(subprocess, "run", _fake_run)+ monkeypatch.setattr(+ ws,+ "_quartz_window_list",+ lambda **_kwargs: [{+ "kCGWindowLayer": 0,+ "kCGWindowName": "Safäri — 日本語", # i18n-allow: non-ASCII title fixture under test+ "kCGWindowNumber": 1,+ }],+ )titles = [w.title for w in ws.list_windows()]- assert any("Safäri" in t for t in titles) # i18n-allow: non-ASCII title fixture (encoding under test)+ assert any("Safäri" in t for t in titles) # i18n-allow: non-ASCII title fixture under testdef test_list_windows_headless_linux_is_empty(monkeypatch):@@ -234,19 +302,39 @@ def test_get_foreground_title_macos_empty_without_tool(monkeypatch):assert ws.get_foreground_title() == ""-def test_get_foreground_title_macos_decodes_non_utf8_locale_title(monkeypatch):- # Same finding-8 contract as the list_windows tests above, for the- # single-title foreground read path.+def test_get_foreground_title_macos_uses_frontmost_app_pid(monkeypatch):monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- def _fake_run(*args, **kwargs):- if kwargs.get("encoding") != "utf-8" or kwargs.get("errors") != "replace":- raise UnicodeDecodeError("cp1252", b"\xff\xfe", 0, 1, "invalid byte")- return _cp(0, stdout="Übersicht — Müller.txt") # i18n-allow: umlaut title fixture (encoding under test)+ class _App:+ def processIdentifier(self):+ return 42- monkeypatch.setattr(subprocess, "run", _fake_run)- assert ws.get_foreground_title() == "Übersicht — Müller.txt" # i18n-allow: umlaut title fixture (encoding under test)+ def localizedName(self):+ return "Finder"++ workspace = types.SimpleNamespace(frontmostApplication=lambda: _App())+ appkit = types.SimpleNamespace(+ NSWorkspace=types.SimpleNamespace(sharedWorkspace=lambda: workspace),+ )+ monkeypatch.setitem(sys.modules, "AppKit", appkit)+ monkeypatch.setattr(+ ws,+ "_quartz_window_list",+ lambda: [+ {+ "kCGWindowLayer": 0,+ "kCGWindowOwnerPID": 7,+ "kCGWindowName": "Wrong app",+ },+ {+ "kCGWindowLayer": 0,+ "kCGWindowOwnerPID": 42,+ "kCGWindowName": "Overview — document.txt",+ },+ ],+ )++ assert ws.get_foreground_title() == "Overview — document.txt"def test_get_foreground_title_linux_decodes_non_utf8_locale_title(monkeypatch):@@ -258,10 +346,16 @@ def test_get_foreground_title_linux_decodes_non_utf8_locale_title(monkeypatch):def _fake_run(*args, **kwargs):if kwargs.get("encoding") != "utf-8" or kwargs.get("errors") != "replace":raise UnicodeDecodeError("cp1252", b"\xff\xfe", 0, 1, "invalid byte")- return _cp(0, stdout="Übersicht — Müller.txt") # i18n-allow: umlaut title fixture (encoding under test)+ return _cp(+ 0,+ stdout="Übersicht — Müller.txt", # i18n-allow: umlaut title fixture+ )monkeypatch.setattr(subprocess, "run", _fake_run)- assert ws.get_foreground_title() == "Übersicht — Müller.txt" # i18n-allow: umlaut title fixture (encoding under test)+ assert (+ ws.get_foreground_title()+ == "Übersicht — Müller.txt" # i18n-allow: umlaut title fixture+ )# --- raise_window (raise a known window via the hardened path) ---------------@@ -271,7 +365,11 @@ def test_raise_window_windows_uses_handle(monkeypatch):monkeypatch.setattr(ws, "detect_platform", lambda: "win32")forced: list = []monkeypatch.setattr(ws, "_force_foreground_windows", lambda h: forced.append(h) or True)- monkeypatch.setattr(ws, "focus_window", lambda t: (_ for _ in ()).throw(AssertionError("title path used")))+ monkeypatch.setattr(+ ws,+ "focus_window",+ lambda t: (_ for _ in ()).throw(AssertionError("title path used")),+ )ok, title = ws.raise_window(WindowInfo("WhatsApp", handle=777))assert ok is Trueassert title == "WhatsApp"@@ -328,7 +426,11 @@ def test_raise_after_launch_windows_uses_hardened_path(monkeypatch):ws, "_force_foreground_windows", lambda h: (forced.append(h), True)[1])# focus_window (title path) must NOT be used on Windows.- monkeypatch.setattr(ws, "focus_window", lambda t: (_ for _ in ()).throw(AssertionError("title path used on win32")))+ monkeypatch.setattr(+ ws,+ "focus_window",+ lambda t: (_ for _ in ()).throw(AssertionError("title path used on win32")),+ )ok, title = ws.raise_after_launch("chrome", timeout_s=1.0, poll_s=0.001)assert ok is True@@ -381,6 +483,175 @@ def test_raise_after_launch_never_raises(monkeypatch):assert ok is False+# --- native macOS maximize -------------------------------------------------+++def test_maximize_window_macos_uses_native_axzoomed(monkeypatch):+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")+ _patch_macos_accessibility(monkeypatch, granted=True)+ monkeypatch.setattr(+ ws,+ "_quartz_window_list",+ lambda **_kwargs: [{+ "kCGWindowNumber": 77,+ "kCGWindowOwnerPID": 42,+ "kCGWindowOwnerName": "Editor",+ "kCGWindowName": "notes.txt",+ }],+ )+ root = object()+ window = object()+ writes: list[tuple[object, str, object]] = []++ def copy_attr(element, attribute, _out):+ if element is root and attribute == "AXWindows":+ return 0, [window]+ if element is window and attribute == "AXTitle":+ return 0, "notes.txt"+ return 1, None++ services = types.SimpleNamespace(+ AXIsProcessTrusted=lambda: True,+ AXUIElementCreateApplication=lambda pid: root,+ AXUIElementCopyAttributeValue=copy_attr,+ AXUIElementSetAttributeValue=lambda element, attribute, value: (+ writes.append((element, attribute, value)) or 0+ ),+ )+ appkit = types.SimpleNamespace(NSWorkspace=object())+ monkeypatch.setitem(sys.modules, "ApplicationServices", services)+ monkeypatch.setitem(sys.modules, "AppKit", appkit)+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ AssertionError("native macOS maximize must not invoke osascript"),+ ),+ )++ ok, message = ws.maximize_window(WindowInfo("notes.txt", handle=77))++ assert ok is True+ assert "zoomed" in message+ assert writes == [(window, "AXZoomed", True)]+++def test_normalize_window_macos_reads_and_sets_native_axzoomed(monkeypatch):+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")+ _patch_macos_accessibility(monkeypatch, granted=True)+ target_info = WindowInfo("notes.txt", handle=77)+ monkeypatch.setattr(ws, "foreground_window", lambda: target_info)+ monkeypatch.setattr(ws, "is_shell_window", lambda _window: False)+ monkeypatch.setattr(+ ws,+ "_quartz_window_list",+ lambda **_kwargs: [{+ "kCGWindowNumber": 77,+ "kCGWindowOwnerPID": 42,+ "kCGWindowName": "notes.txt",+ }],+ )+ root = object()+ window = object()+ writes: list[tuple[object, str, object]] = []++ def copy_attr(element, attribute, _out):+ if element is root and attribute == "AXWindows":+ return 0, [window]+ if element is window and attribute == "AXTitle":+ return 0, "notes.txt"+ if element is window and attribute == "AXZoomed":+ return 0, False+ return 1, None++ services = types.SimpleNamespace(+ AXIsProcessTrusted=lambda: True,+ AXUIElementCreateApplication=lambda _pid: root,+ AXUIElementCopyAttributeValue=copy_attr,+ AXUIElementSetAttributeValue=lambda element, attribute, value: (+ writes.append((element, attribute, value)) or 0+ ),+ )+ monkeypatch.setitem(sys.modules, "ApplicationServices", services)+ monkeypatch.setitem(sys.modules, "AppKit", types.SimpleNamespace(NSWorkspace=object()))++ ok, message = ws.normalize_foreground_window()++ assert ok is True+ assert "zoomed" in message+ assert writes == [(window, "AXZoomed", True)]+++def test_macos_full_screen_counts_as_maximized(monkeypatch):+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")+ _patch_macos_accessibility(monkeypatch, granted=True)+ target = object()+ monkeypatch.setattr(ws, "_resolve_macos_ax_window", lambda _win: (target, ""))+ monkeypatch.setattr(+ ws,+ "_macos_ax_attr",+ lambda element, attribute: (+ True+ if element is target and attribute == "AXFullScreen"+ else False if element is target and attribute == "AXZoomed"+ else None+ ),+ )++ assert ws.window_is_maximized(WindowInfo("Full-screen document", handle=77)) is True+++def test_resolve_macos_ax_window_uses_bounds_for_duplicate_titles(monkeypatch):+ first = object()+ second = object()+ root = object()+ entry = {+ "kCGWindowNumber": 77,+ "kCGWindowOwnerPID": 42,+ "kCGWindowName": "notes.txt",+ "kCGWindowBounds": {"X": 400, "Y": 50, "Width": 800, "Height": 600},+ }+ monkeypatch.setattr(ws, "_quartz_window_list", lambda **_kwargs: [entry])++ def copy_attr(element, attribute, _out):+ values = {+ (root, "AXWindows"): [first, second],+ (first, "AXTitle"): "notes.txt",+ (second, "AXTitle"): "notes.txt",+ (first, "AXPosition"): (10, 20),+ (first, "AXSize"): (300, 200),+ (second, "AXPosition"): (400, 50),+ (second, "AXSize"): (800, 600),+ }+ value = values.get((element, attribute))+ return (0, value) if value is not None else (1, None)++ monkeypatch.setitem(sys.modules, "ApplicationServices", types.SimpleNamespace(+ AXUIElementCreateApplication=lambda _pid: root,+ AXUIElementCopyAttributeValue=copy_attr,+ ))+ monkeypatch.setitem(sys.modules, "AppKit", types.SimpleNamespace(NSWorkspace=object()))++ target, error = ws._resolve_macos_ax_window(+ WindowInfo("notes.txt", handle=77),+ )++ assert error == ""+ assert target is second+++def test_maximize_window_macos_fails_closed_without_accessibility(monkeypatch):+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")+ _patch_macos_accessibility(monkeypatch, granted=False)+ services = types.SimpleNamespace(AXIsProcessTrusted=lambda: False)+ monkeypatch.setitem(sys.modules, "ApplicationServices", services)++ ok, message = ws.maximize_window(WindowInfo("notes.txt", handle=77))++ assert ok is False+ assert "Accessibility" in message++# --- real smoke on the host platform (non-deterministic, just must not crash)diff --git a/tests/unit/platform/test_window_state_rects.py b/tests/unit/platform/test_window_state_rects.pyindex 67f6b9c34c..73f7d1c255 100644--- a/tests/unit/platform/test_window_state_rects.py+++ b/tests/unit/platform/test_window_state_rects.py@@ -175,6 +175,131 @@ def test_grab_window_macos_degrades_without_frameworks(monkeypatch):"width": 100, "height": 100}) is None+def _install_fake_sck(monkeypatch, *, supports_shadow_suppression: bool):+ calls: dict[str, object] = {"capture_count": 0}+ target = types.SimpleNamespace(+ windowID=lambda: 7,+ frame=lambda: types.SimpleNamespace(+ size=types.SimpleNamespace(width=100.0, height=50.0),+ ),+ )+ content = types.SimpleNamespace(windows=lambda: [target])++ class _ShareableContent:+ @staticmethod+ def getShareableContentWithCompletionHandler_(handler):+ handler(content, None)++ class _Filter:+ @classmethod+ def alloc(cls):+ return cls()++ def initWithDesktopIndependentWindow_(self, window):+ calls["target"] = window+ return self++ @staticmethod+ def pointPixelScale():+ return 2.0++ class _ConfigurationBase:+ @classmethod+ def alloc(cls):+ return cls()++ def init(self):+ calls["config"] = self+ return self++ def setWidth_(self, value):+ calls["width"] = value++ def setHeight_(self, value):+ calls["height"] = value++ def setShowsCursor_(self, value):+ calls["shows_cursor"] = value++ if supports_shadow_suppression:+ class _Configuration(_ConfigurationBase):+ def setIgnoreShadowsSingleWindow_(self, value):+ calls["ignore_shadows"] = value+ else:+ class _Configuration(_ConfigurationBase):+ pass++ class _ScreenshotManager:+ @staticmethod+ def captureImageWithFilter_configuration_completionHandler_(+ sc_filter,+ config,+ handler,+ ):+ calls["capture_count"] = int(calls["capture_count"]) + 1+ calls["captured_config"] = config+ handler(object(), None)++ sck = types.ModuleType("ScreenCaptureKit")+ sck.SCShareableContent = _ShareableContent+ sck.SCContentFilter = _Filter+ sck.SCStreamConfiguration = _Configuration+ sck.SCScreenshotManager = _ScreenshotManager+ monkeypatch.setitem(sys.modules, "ScreenCaptureKit", sck)++ class _BitmapRep:+ @classmethod+ def alloc(cls):+ return cls()++ def initWithCGImage_(self, image):+ return self++ @staticmethod+ def representationUsingType_properties_(image_type, properties):+ return b"fake-png"++ appkit = types.ModuleType("AppKit")+ appkit.NSBitmapImageRep = _BitmapRep+ monkeypatch.setitem(sys.modules, "AppKit", appkit)++ class _Image:+ width = 200+ height = 100++ def convert(self, mode):+ return self++ @staticmethod+ def tobytes():+ return b"rgb"++ monkeypatch.setattr("PIL.Image.open", lambda stream: _Image())+ return calls+++def test_macos_window_capture_disables_shadow_framing(monkeypatch):+ from jarvis.platform import window_capture as wc++ calls = _install_fake_sck(monkeypatch, supports_shadow_suppression=True)++ assert wc._grab_window_macos(7) == ((200, 100), b"rgb")+ assert calls["ignore_shadows"] is True+ assert calls["width"] == 200+ assert calls["height"] == 100+ assert calls["shows_cursor"] is False+ assert calls["capture_count"] == 1+++def test_macos_window_capture_falls_back_without_shadow_suppression(monkeypatch):+ from jarvis.platform import window_capture as wc++ calls = _install_fake_sck(monkeypatch, supports_shadow_suppression=False)++ assert wc._grab_window_macos(7) is None+ assert calls["capture_count"] == 0++def test_grab_window_never_raises(monkeypatch):from jarvis.platform import window_capture as wcdiff --git a/tests/unit/plugins/tool/test_click_element.py b/tests/unit/plugins/tool/test_click_element.pyindex cf0610cbd9..33130807fd 100644--- a/tests/unit/plugins/tool/test_click_element.py+++ b/tests/unit/plugins/tool/test_click_element.py@@ -7,7 +7,6 @@ it would have clicked."""from __future__ import annotations-from typing import Anyfrom uuid import uuid4import pytest@@ -43,12 +42,26 @@ class _FakeVisionSource:)[email protected](autouse=True)+def stable_foreground(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "jarvis.plugins.tool.click_element._foreground_window_signature",+ lambda: ("handle", 11, (0, 0, 800, 600)),+ )++@pytest.fixturedef recorder(monkeypatch: pytest.MonkeyPatch) -> list[tuple[int, int, str, bool]]:"""Patch _click_windows so the test runs cross-platform and records calls."""calls: list[tuple[int, int, str, bool]] = []- def _record(x: int, y: int, button: str, double: bool) -> None:+ def _record(+ x: int,+ y: int,+ button: str,+ double: bool,+ **_kwargs,+ ) -> None:calls.append((x, y, button, double))monkeypatch.setattr(@@ -164,3 +177,52 @@ async def test_posix_unavailable_backend_reports_actionable_message(assert result.success is Falseassert "desktop extras" in (result.error or "")+++async def test_refuses_engine_capture_from_a_different_foreground_window(+ monkeypatch: pytest.MonkeyPatch,+ recorder: list[tuple[int, int, str, bool]],+) -> None:+ current = ("handle", 22, (0, 0, 800, 600))+ captured = ("handle", 11, (0, 0, 800, 600))+ monkeypatch.setattr(+ "jarvis.plugins.tool.click_element._foreground_window_signature",+ lambda: current,+ )+ tool = ClickElementTool(vision_source=_FakeVisionSource((+ UIANode(role="Button", name="Save", bounds=(10, 20, 100, 40)),+ )))++ result = await tool.execute(+ {"name": "save", "_expected_window_signature": captured},+ _ctx(),+ )++ assert result.success is False+ assert "foreground window changed" in (result.error or "")+ assert recorder == []+++async def test_refuses_switch_during_async_ui_tree_observation(+ monkeypatch: pytest.MonkeyPatch,+ recorder: list[tuple[int, int, str, bool]],+) -> None:+ signatures = iter((+ ("handle", 11, (0, 0, 800, 600)),+ ("handle", 22, (0, 0, 800, 600)),+ ))+ monkeypatch.setattr(+ "jarvis.plugins.tool.click_element._foreground_window_signature",+ lambda: next(signatures),+ )+ tool = ClickElementTool(vision_source=_FakeVisionSource((+ UIANode(role="Button", name="Save", bounds=(10, 20, 100, 40)),+ )))++ result = await tool.execute({"name": "save"}, _ctx())++ assert result.success is False+ assert "while its UI tree was being observed" in (result.error or "")+ assert recorder == []diff --git a/tests/unit/plugins/tool/test_click_foreground_guard.py b/tests/unit/plugins/tool/test_click_foreground_guard.pynew file mode 100644index 0000000000..51b5a6f56b--- /dev/null+++ b/tests/unit/plugins/tool/test_click_foreground_guard.py@@ -0,0 +1,55 @@+"""Action-time foreground binding for the visible Windows click glide."""+from __future__ import annotations++import types++import pytest++from jarvis.plugins.tool import click as click_mod+++def test_windows_glide_refuses_button_down_after_foreground_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ instances = []++ class _Actuator:+ def __init__(self) -> None:+ self.current = (0, 0)+ self.clicked = False+ instances.append(self)++ def move(self, x: int, y: int) -> None:+ self.current = (x, y)++ def cursor_pos(self) -> tuple[int, int]:+ return self.current++ def click_at_cursor(self, **_kwargs) -> None:+ self.clicked = True++ monkeypatch.setattr(click_mod, "os", types.SimpleNamespace(name="nt"))+ monkeypatch.setattr(click_mod, "glide_os_cursor", lambda _x, _y: None)+ monkeypatch.setattr(click_mod, "_window_signature_matches", lambda _expected: False)+ monkeypatch.setattr(+ click_mod,+ "get_virtual_cursor",+ lambda: types.SimpleNamespace(show_click=lambda *_args, **_kwargs: None),+ )+ monkeypatch.setattr(+ "jarvis.cu.actuate.windows.WindowsActuator",+ _Actuator,+ )+ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ with pytest.raises(OSError, match="foreground window changed"):+ click_mod._click_windows(+ 100,+ 200,+ "left",+ False,+ expected_window_signature=("handle", 11, (0, 0, 800, 600)),+ )++ assert len(instances) == 1+ assert instances[0].clicked is Falsediff --git a/tests/unit/plugins/tool/test_drag.py b/tests/unit/plugins/tool/test_drag.pyindex e0d7862cf1..167bd164e4 100644--- a/tests/unit/plugins/tool/test_drag.py+++ b/tests/unit/plugins/tool/test_drag.py@@ -71,6 +71,31 @@ async def test_drag_reports_backend_error(monkeypatch):assert "failed" in (res.error or "")+async def test_drag_refuses_engine_capture_from_different_window(+ monkeypatch,+ _no_real_mouse,+):+ monkeypatch.setattr(+ "jarvis.plugins.tool.click._window_signature_matches",+ lambda _expected: False,+ )++ res = await DragTool().execute(+ {+ "x1": 0,+ "y1": 0,+ "x2": 10,+ "y2": 10,+ "_expected_window_signature": ("handle", 11, (0, 0, 800, 600)),+ },+ SimpleNamespace(),+ )++ assert res.success is False+ assert "changed after the screenshot" in (res.error or "")+ assert _no_real_mouse == []++async def test_drag_reports_missing_pyautogui(monkeypatch):def _no_pyautogui(*_a, **_k):raise ImportError("No module named 'pyautogui'")@@ -109,13 +134,21 @@ async def test_drag_reports_actuation_unavailable_verbatim(monkeypatch):def test_perform_drag_posix_routes_through_capability_probe(monkeypatch):- """Non-Windows _perform_drag must use get_actuator(), not raw pyautogui."""- monkeypatch.setattr(drag_mod.os, "name", "posix")+ """Drag must use the capability-probed actuator and verify both endpoints."""drags: list[tuple] = []class _FakeActuator:- def drag(self, x1, y1, x2, y2, *, duration_s=0.4):+ current = (0, 0)++ def move(self, x, y):+ self.current = (x, y)++ def cursor_pos(self):+ return self.current++ def drag_from_cursor(self, x1, y1, x2, y2, *, duration_s=0.4):drags.append((x1, y1, x2, y2, duration_s))+ self.current = (x2, y2)monkeypatch.setattr("jarvis.cu.actuate.base.get_actuator", lambda: _FakeActuator()diff --git a/tests/unit/plugins/tool/test_hotkey_tool.py b/tests/unit/plugins/tool/test_hotkey_tool.pyindex 8161ce693f..7c7f201a83 100644--- a/tests/unit/plugins/tool/test_hotkey_tool.py+++ b/tests/unit/plugins/tool/test_hotkey_tool.py@@ -90,3 +90,65 @@ async def test_unknown_combo_part_still_reports_clean_error(monkeypatch):# existing "Unknown key" error instead of a confusing split.assert res.success is Falseassert "Unknown key" in (res.error or "")+++async def test_macos_command_combo_reaches_posix_actuator(monkeypatch):+ sent: list[list[str]] = []++ class _Actuator:+ name = "fake-macos"++ def key_combo(self, keys):+ sent.append(list(keys))++ monkeypatch.setattr(hk.os, "name", "posix")+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", lambda: _Actuator())++ res = await HotkeyTool().execute({"keys": ["cmd+a"]}, _Ctx())++ assert res.success is True+ assert sent == [["cmd", "a"]]+++async def test_macos_option_alias_reaches_posix_actuator(monkeypatch):+ sent: list[list[str]] = []++ class _Actuator:+ name = "fake-macos"++ def key_combo(self, keys):+ sent.append(keys)++ monkeypatch.setattr(hk.os, "name", "posix")+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", lambda: _Actuator())++ result = await HotkeyTool().execute({"keys": ["option", "left"]}, _Ctx())++ assert result.success is True+ assert sent == [["option", "left"]]+++async def test_screenshot_bound_hotkey_refuses_changed_foreground(monkeypatch):+ sent: list[list[str]] = []++ class _Actuator:+ name = "fake-macos"++ def key_combo(self, keys):+ sent.append(list(keys))++ monkeypatch.setattr(hk.os, "name", "posix")+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", lambda: _Actuator())+ monkeypatch.setattr("jarvis.cu.target_guard.foreground_matches", lambda _: False)++ result = await HotkeyTool().execute(+ {+ "keys": ["cmd", "a"],+ "_expected_window_signature": ("handle", 7, (0, 0, 800, 600)),+ },+ _Ctx(),+ )++ assert result.success is False+ assert "foreground window changed" in (result.error or "")+ assert sent == []diff --git a/tests/unit/plugins/tool/test_move_mouse.py b/tests/unit/plugins/tool/test_move_mouse.pyindex d3bb0734f6..ea3a7f96b5 100644--- a/tests/unit/plugins/tool/test_move_mouse.py+++ b/tests/unit/plugins/tool/test_move_mouse.py@@ -48,6 +48,9 @@ async def test_posix_success_moves_via_probed_backend(def move(self, x: int, y: int) -> None:moves.append((x, y))+ def cursor_pos(self) -> tuple[int, int]:+ return moves[-1]+monkeypatch.setattr("jarvis.cu.actuate.base.get_actuator", lambda: _FakeActuator())diff --git a/tests/unit/plugins/tool/test_scroll.py b/tests/unit/plugins/tool/test_scroll.pyindex 9794765c95..25f21f2745 100644--- a/tests/unit/plugins/tool/test_scroll.py+++ b/tests/unit/plugins/tool/test_scroll.py@@ -35,9 +35,25 @@ def captured(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, object]]:"""calls: list[dict[str, object]] = []- def _fake(direction: str, amount: int, x: int | None, y: int | None) -> int:+ def _fake(+ direction: str,+ amount: int,+ x: int | None,+ y: int | None,+ *,+ expected_window_signature: tuple[object, ...] | None = None,+ ) -> int:notch = _notch_for(direction.lower(), amount)- calls.append({"direction": direction, "amount": amount, "x": x, "y": y, "notch": notch})+ calls.append(+ {+ "direction": direction,+ "amount": amount,+ "x": x,+ "y": y,+ "notch": notch,+ "expected_window_signature": expected_window_signature,+ }+ )return notchmonkeypatch.setattr(scroll_mod, "_scroll_windows", _fake)@@ -137,6 +153,65 @@ def test_notch_helper_direction_contract() -> None:assert _notch_for("left", 3) == -360+def test_explicit_scroll_target_is_verified_before_wheel(monkeypatch) -> None:+ from jarvis.plugins.tool.scroll import _scroll_with_verified_target++ calls: list[tuple] = []++ class _Actuator:+ def move(self, x, y):+ calls.append(("move", x, y))++ def cursor_pos(self):+ calls.append(("cursor",))+ return (640, 480)++ def scroll(self, direction, amount):+ calls.append(("scroll", direction, amount))++ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])++ _scroll_with_verified_target(_Actuator(), "down", 2, 640, 480)++ assert calls == [+ ("move", 640, 480),+ ("cursor",),+ ("scroll", "down", 2),+ ]+++def test_scroll_refuses_wheel_after_foreground_changes_during_move(monkeypatch) -> None:+ from jarvis.plugins.tool.scroll import _scroll_with_verified_target++ calls: list[tuple] = []++ class _Actuator:+ def move(self, x, y):+ calls.append(("move", x, y))++ def cursor_pos(self):+ calls.append(("cursor",))+ return (640, 480)++ def scroll(self, direction, amount):+ calls.append(("scroll", direction, amount))++ monkeypatch.setattr("jarvis.cu.geometry.list_monitors", lambda: [])+ monkeypatch.setattr("jarvis.cu.target_guard.foreground_matches", lambda _: False)++ with pytest.raises(RuntimeError, match="foreground window changed"):+ _scroll_with_verified_target(+ _Actuator(),+ "down",+ 2,+ 640,+ 480,+ expected_window_signature=("handle", 7, (0, 0, 800, 600)),+ )++ assert calls == [("move", 640, 480), ("cursor",)]++def test_struct_size_is_40_on_windows() -> None:"""Guard the cbSize bug class: INPUT must be 40 bytes on x64 Windows."""if os.name != "nt":diff --git a/tests/unit/plugins/tool/test_switch_window.py b/tests/unit/plugins/tool/test_switch_window.pyindex 96a0cf703e..b10a05d767 100644--- a/tests/unit/plugins/tool/test_switch_window.py+++ b/tests/unit/plugins/tool/test_switch_window.py@@ -1,14 +1,14 @@-"""H2: switch_window must work on macOS (osascript) and Linux/X11 (wmctrl),+"""H2: switch_window must work on macOS (Quartz/AppKit/AX) and Linux/X11,degrade cleanly on Wayland / headless / missing-tool with a clear Englishmessage, and leave the Windows ctypes path untouched (AD-7).-Seam-level only: the platform is forced via detect_platform/probes and the-osascript/wmctrl subprocesses are faked — this proves the dispatch + parsing,-NOT that real osascript/wmctrl behave as assumed on real hardware.+Seam-level only: platform APIs and subprocesses are faked. This proves the+dispatch and parsing, not behavior on real hardware."""from __future__ import annotationsimport subprocess+import sysimport typesfrom jarvis.core.protocols import ExecutionContext@@ -30,75 +30,154 @@ def _ctx() -> ExecutionContext:)-# --- macOS (osascript) -----------------------------------------------------+# --- macOS (Quartz/AppKit/AX) ----------------------------------------------+++def _install_fake_macos_apis(monkeypatch, *, trusted=True, minimized=False):+ from jarvis.platform.permissions import PermissionState++ ax_window = object()+ ax_root = object()+ calls: list[tuple] = []++ class _App:+ def activateWithOptions_(self, options):+ calls.append(("activate", options))+ return True++ appkit = types.SimpleNamespace(+ NSApplicationActivateAllWindows=1,+ NSApplicationActivateIgnoringOtherApps=2,+ NSRunningApplication=types.SimpleNamespace(+ runningApplicationWithProcessIdentifier_=lambda pid: _App(),+ ),+ )++ def copy_attr(element, attribute, _out):+ if element is ax_root and attribute == "AXWindows":+ return 0, [ax_window]+ if element is ax_window and attribute == "AXTitle":+ return 0, "My Editor"+ if element is ax_window and attribute == "AXMinimized":+ return 0, minimized+ return 1, None++ services = types.SimpleNamespace(+ AXIsProcessTrusted=lambda: trusted,+ AXUIElementCreateApplication=lambda pid: ax_root,+ AXUIElementCopyAttributeValue=copy_attr,+ AXUIElementPerformAction=lambda element, action: calls.append(+ ("perform", action)+ ) or 0,+ AXUIElementSetAttributeValue=lambda element, attr, value: calls.append(+ ("set", attr)+ ) or 0,+ )+ monkeypatch.setitem(sys.modules, "AppKit", appkit)+ monkeypatch.setitem(sys.modules, "ApplicationServices", services)+ permission_port = types.SimpleNamespace(+ runtime_access_granted=lambda _permission_id: trusted,+ state=lambda _permission_id: (+ PermissionState.GRANTED+ if trusted+ else PermissionState.NOT_GRANTED+ ),+ )+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: permission_port,+ )+ return calls+++def _mac_window(title="My Editor", *, on_screen=True):+ return {+ "kCGWindowLayer": 0,+ "kCGWindowName": title,+ "kCGWindowOwnerName": "Editor",+ "kCGWindowOwnerPID": 42,+ "kCGWindowNumber": 7,+ "kCGWindowIsOnscreen": on_screen,+ }def test_macos_focus_success(monkeypatch):- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- monkeypatch.setattr(subprocess, "run", lambda *a, **k: _cp(0, stdout="My Editor\n"))+ calls = _install_fake_macos_apis(monkeypatch)+ monkeypatch.setattr(+ "jarvis.platform.window_state._quartz_window_list",+ lambda **_kwargs: [_mac_window()],+ )found, msg = _find_and_focus_macos("Editor")assert found is Trueassert msg == "My Editor"+ assert ("set", "AXFocusedWindow") in calls+ assert ("perform", "AXRaise") in calls+++def test_macos_focus_restores_minimized_window_from_all_window_catalog(monkeypatch):+ calls = _install_fake_macos_apis(monkeypatch, minimized=True)+ catalog_requests: list[bool] = []++ def catalog(*, on_screen_only=True):+ catalog_requests.append(on_screen_only)+ return [_mac_window(on_screen=False)]++ monkeypatch.setattr(+ "jarvis.platform.window_state._quartz_window_list",+ catalog,+ )+ found, msg = _find_and_focus_macos("Editor")++ assert found is True+ assert msg == "My Editor"+ assert catalog_requests == [False]+ assert ("set", "AXMinimized") in calls+ assert ("perform", "AXRaise") in calls+ assert calls.index(("set", "AXMinimized")) < calls.index(("perform", "AXRaise"))+ assert calls.index(("perform", "AXRaise")) < calls.index(("set", "AXFocusedWindow"))def test_macos_accessibility_denied_message(monkeypatch):- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- err = "System Events got an error: osascript is not allowed assistive access. (-1719)"- monkeypatch.setattr(subprocess, "run", lambda *a, **k: _cp(1, stderr=err))+ _install_fake_macos_apis(monkeypatch, trusted=False)+ monkeypatch.setattr(+ "jarvis.platform.window_state._quartz_window_list",+ lambda **_kwargs: [_mac_window()],+ )found, msg = _find_and_focus_macos("Editor")assert found is Falseassert "Accessibility" in msg-def test_macos_missing_osascript(monkeypatch):- monkeypatch.setattr("shutil.which", lambda n: None)+def test_macos_missing_native_frameworks(monkeypatch):+ monkeypatch.setattr(+ "jarvis.platform.window_state._quartz_window_list",+ lambda **_kwargs: [_mac_window()],+ )+ monkeypatch.setitem(sys.modules, "AppKit", None)+ monkeypatch.setitem(sys.modules, "ApplicationServices", None)found, msg = _find_and_focus_macos("Editor")assert found is False- assert "osascript" in msg.lower()+ assert "unavailable" in msg.lower()def test_macos_no_match(monkeypatch):- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- monkeypatch.setattr(subprocess, "run", lambda *a, **k: _cp(0, stdout="\n"))+ monkeypatch.setattr(+ "jarvis.platform.window_state._quartz_window_list", lambda **_kwargs: [],+ )found, msg = _find_and_focus_macos("Nope")assert found is Falseassert "Nope" in msg-def test_macos_escapes_applescript_injection(monkeypatch):- # A crafted title with a newline must NOT break out of the contains "..."- # literal and inject a new AppleScript statement (review HIGH).- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- captured: dict[str, str] = {}-- def fake_run(cmd, *a, **k):- captured["script"] = cmd[2] # ["osascript", "-e", <script>]- return _cp(0, stdout="")-- monkeypatch.setattr(subprocess, "run", fake_run)- _find_and_focus_macos('x"\ndo shell script "evil"')- script = captured["script"]- # No raw newline may precede the injected statement — it must be escaped.- assert "\ndo shell script" not in script- # The substring is still present, only as an escaped literal (not dropped).- assert "do shell script" in script--def test_macos_matching_is_case_insensitive(monkeypatch):- # Parity with the Linux path: the generated AppleScript lowercases both- # sides so "editor" matches "My Editor" (review MEDIUM).- monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")- captured: dict[str, str] = {}-- def fake_run(cmd, *a, **k):- captured["script"] = cmd[2]- return _cp(0, stdout="My Editor\n")-- monkeypatch.setattr(subprocess, "run", fake_run)- _find_and_focus_macos("EdItOr")- script = captured["script"]- assert "lowercase of" in script- assert '"editor"' in script # needle lowercased before interpolation+ _install_fake_macos_apis(monkeypatch)+ monkeypatch.setattr(+ "jarvis.platform.window_state._quartz_window_list",+ lambda **_kwargs: [_mac_window()],+ )+ found, msg = _find_and_focus_macos("EdItOr")+ assert found is True+ assert msg == "My Editor"# --- Linux (wmctrl) --------------------------------------------------------diff --git a/tests/unit/plugins/tool/test_type_text.py b/tests/unit/plugins/tool/test_type_text.pyindex 6f07def9e1..ec01e31789 100644--- a/tests/unit/plugins/tool/test_type_text.py+++ b/tests/unit/plugins/tool/test_type_text.py@@ -78,6 +78,32 @@ async def test_empty_text_is_rejected(monkeypatch):assert res.success is False+async def test_screenshot_bound_typing_refuses_changed_foreground(monkeypatch):+ typed: list[str] = []++ class _Actuator:+ name = "fake-macos"++ def type_text(self, text, *, delay_s=0.02):+ typed.append(text)++ monkeypatch.setattr(tt.os, "name", "posix")+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", lambda: _Actuator())+ monkeypatch.setattr("jarvis.cu.target_guard.foreground_matches", lambda _: False)++ result = await TypeTextTool().execute(+ {+ "text": "secret target text",+ "_expected_window_signature": ("handle", 7, (0, 0, 800, 600)),+ },+ _Ctx(),+ )++ assert result.success is False+ assert "foreground window changed" in (result.error or "")+ assert typed == []++# ---------------------------------------------------------------------------# RC#1 regression (Google-Flights typing bug, 2026-06-22): the SendInput INPUT# union must be sized to its LARGEST member (MOUSEINPUT). If it only carriesdiff --git a/tests/unit/plugins/tool/test_verify_localhost.py b/tests/unit/plugins/tool/test_verify_localhost.pyindex cc2d400331..79f32adcae 100644--- a/tests/unit/plugins/tool/test_verify_localhost.py+++ b/tests/unit/plugins/tool/test_verify_localhost.py@@ -103,3 +103,29 @@ async def test_http_call_is_offloaded_via_to_thread(assert result.success is Trueassert len(recorder.calls) == 1assert recorder.calls[0][0] is httpx.get+++async def test_screenshot_refuses_capture_when_screen_recording_is_blocked(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A wallpaper-only macOS capture must never be reported as evidence."""+ import httpx++ monkeypatch.setattr(+ httpx, "get", lambda *_a, **_k: _FakeResponse(status_code=200, text="hi")+ )+ monkeypatch.setattr(+ "jarvis.vision.screenshot.warn_if_screen_recording_denied",+ lambda: True,+ )++ tool = VerifyLocalhostTool()+ result = await tool.execute(+ {"port": 5173, "take_screenshot": True}, ctx=None+ )++ assert result.success is True+ assert result.artifacts+ error = result.artifacts[0]["screenshot_error"]+ assert "Screen Recording permission is not granted" in errordiff --git a/tests/unit/vision/test_ax_tree.py b/tests/unit/vision/test_ax_tree.pyindex 8ad39b00d7..cb89066ac5 100644--- a/tests/unit/vision/test_ax_tree.py+++ b/tests/unit/vision/test_ax_tree.py@@ -8,10 +8,13 @@ logic coverage below.from __future__ import annotations+import sys+import types+import pytestfrom jarvis.core.protocols import Observation, VisionSource-from jarvis.vision.ax_tree import AXTreeSource+from jarvis.vision.ax_tree import AXTreeSource, _ax_flatten, _ax_point, _ax_sizefrom tests.fakes.fake_ax_api import (FakeAXElement,build_fake_ax_traverser,@@ -86,6 +89,120 @@ async def test_textfield_carries_value_and_automation_id() -> None:assert edit.bounds == (10, 50, 200, 24)+def test_axvalue_manual_wrapper_contract_decodes_position_and_size(monkeypatch) -> None:+ class _GeneratedStruct:+ """PyObjC-style sequence slots without Sequence ABC registration."""++ def __init__(self, first: float, second: float) -> None:+ self._items = (first, second)++ def __len__(self) -> int:+ return 2++ def __getitem__(self, index: int) -> float:+ return self._items[index]++ position = object()+ size = object()+ module = types.SimpleNamespace(+ kAXValueCGPointType=1,+ kAXValueCGSizeType=2,+ AXValueGetType=lambda value: 1 if value is position else 2,+ AXValueGetValue=lambda value, kind, _out: (+ (True, _GeneratedStruct(120.5, -40.25)) if value is position and kind == 1+ else (True, _GeneratedStruct(800.0, 600.0)) if value is size and kind == 2+ else (False, None)+ ),+ )+ monkeypatch.setitem(sys.modules, "HIServices", module)++ assert _ax_point(position) == (120, -40)+ assert _ax_size(size) == (800, 600)++[email protected](sys.platform != "darwin", reason="requires macOS PyObjC")+def test_real_pyobjc_axvalue_round_trip_without_tcc() -> None:+ """Exercise the actual manual wrapper on both macOS CI architectures."""+ import HIServices # type: ignore[import-not-found]++ from jarvis.platform.macos_ax import decode_ax_point, decode_ax_size++ point_type = HIServices.kAXValueCGPointType+ size_type = HIServices.kAXValueCGSizeType+ position = HIServices.AXValueCreate(point_type, (120.5, -40.25))+ size = HIServices.AXValueCreate(size_type, (800.0, 600.0))++ point_ok, point = HIServices.AXValueGetValue(position, point_type, None)+ size_ok, dimensions = HIServices.AXValueGetValue(size, size_type, None)++ assert point_ok is True+ assert point == (120.5, -40.25)+ assert size_ok is True+ assert dimensions == (800.0, 600.0)+ assert decode_ax_point(position) == (120.5, -40.25)+ assert decode_ax_size(size) == (800.0, 600.0)+ assert _ax_point(position) == (120, -40)+ assert _ax_size(size) == (800, 600)+++def test_ax_permission_uses_unified_runtime_identity_gate(monkeypatch) -> None:+ from jarvis.platform.permissions import PermissionId++ seen = []+ port = types.SimpleNamespace(+ runtime_access_granted=lambda permission: seen.append(permission) or False,+ )+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: port,+ )++ assert AXTreeSource._ax_is_process_trusted() is False+ assert seen == [PermissionId.ACCESSIBILITY]+++def test_ax_permission_reprobes_live_revocation(monkeypatch) -> None:+ outcomes = iter((True, False))+ port = types.SimpleNamespace(+ runtime_access_granted=lambda _permission: next(outcomes),+ )+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: port,+ )++ assert AXTreeSource._ax_is_process_trusted() is True+ assert AXTreeSource._ax_is_process_trusted() is False+++def test_secure_ax_field_redacts_value_and_preserves_focus() -> None:+ class _SecureField:+ values = {+ "AXRole": "AXTextField",+ "AXSubrole": "AXSecureTextField",+ "AXTitle": "Password",+ "AXValue": "must-not-leak",+ "AXPosition": {"x": 20, "y": 30},+ "AXSize": {"w": 200, "h": 24},+ "AXEnabled": True,+ "AXFocused": True,+ "AXChildren": [],+ }++ def copy_attribute_value(self, attribute):+ return self.values.get(attribute)++ nodes = []+ _ax_flatten(+ _SecureField(), depth=0, max_depth=2, parent_index=-1, out=nodes,+ )++ assert nodes[0].is_password is True+ assert nodes[0].focused is True+ assert nodes[0].value == ""+ assert "must-not-leak" not in nodes[0].name++@pytest.mark.asyncioasync def test_permission_denied_degrades_to_empty_screenshot_only() -> None:# AD-13: AXIsProcessTrusted()==False -> empty nodes, source=screenshot_only,diff --git a/tests/unit/vision/test_element_at_point.py b/tests/unit/vision/test_element_at_point.pyindex d1dc47f4fe..9ec19eae83 100644--- a/tests/unit/vision/test_element_at_point.py+++ b/tests/unit/vision/test_element_at_point.py@@ -40,7 +40,17 @@ def test_resolver_returns_injected_element() -> None:@pytest.mark.parametrize("cls", _OS_RESOLVERS)-def test_resolver_swallows_query_errors(cls) -> None:+def test_resolver_swallows_query_errors(cls, monkeypatch) -> None:+ if cls is eap.AXPointerResolver:+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: type(+ "GrantedPermissionPort",+ (),+ {"runtime_access_granted": lambda self, permission: True},+ )(),+ )+def boom(x: int, y: int) -> PointerElement:raise RuntimeError("native query failed")@@ -48,7 +58,17 @@ def test_resolver_swallows_query_errors(cls) -> None:@pytest.mark.parametrize("cls", _OS_RESOLVERS)-def test_resolver_passes_coords_to_query(cls) -> None:+def test_resolver_passes_coords_to_query(cls, monkeypatch) -> None:+ if cls is eap.AXPointerResolver:+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: type(+ "GrantedPermissionPort",+ (),+ {"runtime_access_granted": lambda self, permission: True},+ )(),+ )+seen: dict[str, tuple[int, int]] = {}def q(x: int, y: int) -> None:@@ -59,6 +79,52 @@ def test_resolver_passes_coords_to_query(cls) -> None:assert seen["xy"] == (42, 99)+ "blocked_reason",+ ("unstable_identity", "pending_restart", "revoked_grant"),+)+def test_macos_resolver_fails_closed_when_runtime_access_is_blocked(+ monkeypatch,+ blocked_reason: str,+) -> None:+ calls: list[tuple[int, int]] = []+ port = type(+ "BlockedPermissionPort",+ (),+ {"runtime_access_granted": lambda self, permission: False},+ )()+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: port,+ )++ resolver = eap.AXPointerResolver(query=lambda x, y: calls.append((x, y)))++ assert resolver.at(42, 99) is None, blocked_reason+ assert calls == []+++def test_macos_resolver_queries_when_runtime_access_is_granted(monkeypatch) -> None:+ sentinel = PointerElement(name="Allowed", role="Button", bounds=(1, 2, 3, 4))+ seen: list[object] = []+ port = type(+ "GrantedPermissionPort",+ (),+ {+ "runtime_access_granted": (+ lambda self, permission: seen.append(permission) or True+ ),+ },+ )()+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: port,+ )++ assert eap.AXPointerResolver(query=lambda x, y: sentinel).at(4, 5) is sentinel+ assert [permission.value for permission in seen] == ["accessibility"]++def test_factory_windows(monkeypatch) -> None:monkeypatch.setattr(eap, "detect_platform", lambda: "win32")monkeypatch.setattr(eap, "detect_capabilities", fake_windows_capabilities)diff --git a/tests/unit/vision/test_screen_recording_warning.py b/tests/unit/vision/test_screen_recording_warning.pyindex f374cc914c..15fc704833 100644--- a/tests/unit/vision/test_screen_recording_warning.py+++ b/tests/unit/vision/test_screen_recording_warning.py@@ -2,9 +2,9 @@onboarding message at the screenshot capture point, instead of silentlycapturing the desktop wallpaper (which would make Computer-Use click blind).-These force the grant state via the platform probe seam — no real macOS needed.-Seam-level only: this proves the warn-once decision logic, NOT that the real-CGPreflightScreenCaptureAccess call behaves as assumed on a real Mac.+These force the grant state via the permission-port seam — no real macOS+needed. Seam-level only: this proves uncached fail-closed behavior, not the+native CGPreflightScreenCaptureAccess implementation."""from __future__ import annotations@@ -15,35 +15,78 @@ from jarvis.vision import screenshot_MSG = "Screen Recording permission not granted"+def _permission_port(monkeypatch, states):+ remaining = list(states)++ class _Port:+ current = None++ def state(self, _permission_id):+ return self.current++ def runtime_access_granted(self, _permission_id):+ from jarvis.platform.permissions import PermissionState++ self.current = remaining.pop(0)+ return self.current in {+ PermissionState.GRANTED,+ PermissionState.NOT_REQUIRED,+ }++ port = _Port()+ monkeypatch.setattr(+ "jarvis.platform.permissions.get_system_permission_port",+ lambda: port,+ )+ return remaining++def test_warns_once_when_screen_recording_denied(monkeypatch, caplog):+ from jarvis.platform.permissions import PermissionState+monkeypatch.setattr(screenshot, "_screen_recording_warned", False)- monkeypatch.setattr(- "jarvis.platform.probes.screen_recording_granted", lambda: False+ remaining = _permission_port(+ monkeypatch,+ [PermissionState.NOT_GRANTED, PermissionState.NOT_GRANTED],)with caplog.at_level(logging.WARNING):- # darwin + explicitly denied -> capture will be blank: returns True.assert screenshot.warn_if_screen_recording_denied() is True- # Called again (every frame) -> still blank, but warns only ONCE.assert screenshot.warn_if_screen_recording_denied() is Trueassert caplog.text.count(_MSG) == 1+ assert remaining == [], "the native state must be probed on both calls"def test_no_warning_when_granted(monkeypatch, caplog):+ from jarvis.platform.permissions import PermissionState+monkeypatch.setattr(screenshot, "_screen_recording_warned", False)- monkeypatch.setattr(- "jarvis.platform.probes.screen_recording_granted", lambda: True- )+ _permission_port(monkeypatch, [PermissionState.GRANTED])with caplog.at_level(logging.WARNING):assert screenshot.warn_if_screen_recording_denied() is Falseassert _MSG not in caplog.text-def test_no_warning_when_unknown(monkeypatch, caplog):- # None = pyobjc-Quartz absent: we cannot prove denial, so do NOT nag.+def test_unavailable_native_probe_fails_closed(monkeypatch, caplog):+ from jarvis.platform.permissions import PermissionState+monkeypatch.setattr(screenshot, "_screen_recording_warned", False)- monkeypatch.setattr(- "jarvis.platform.probes.screen_recording_granted", lambda: None- )+ _permission_port(monkeypatch, [PermissionState.UNAVAILABLE])with caplog.at_level(logging.WARNING):+ assert screenshot.warn_if_screen_recording_denied() is True+ assert _MSG in caplog.text+++def test_permission_recovery_is_observed_without_restart(monkeypatch, caplog):+ from jarvis.platform.permissions import PermissionState++ monkeypatch.setattr(screenshot, "_screen_recording_warned", False)+ _permission_port(+ monkeypatch,+ [PermissionState.NOT_GRANTED, PermissionState.GRANTED],+ )++ with caplog.at_level(logging.INFO):+ assert screenshot.warn_if_screen_recording_denied() is Trueassert screenshot.warn_if_screen_recording_denied() is False- assert _MSG not in caplog.text++ assert "available again" in caplog.textdiff --git a/tests/unit/vision/test_select_capture_monitor.py b/tests/unit/vision/test_select_capture_monitor.pyindex 672411bb60..26ff511f2a 100644--- a/tests/unit/vision/test_select_capture_monitor.py+++ b/tests/unit/vision/test_select_capture_monitor.py@@ -55,6 +55,32 @@ def test_foreground_strategy_follows_the_window_monitor(monkeypatch) -> None:assert select_capture_monitor(_MONITORS, strategy="foreground") is _LEFT+def test_foreground_uses_largest_overlap_when_window_center_is_in_gap(+ monkeypatch,+) -> None:+ from jarvis.platform.window_state import WindowInfo++ # L-shaped layout: the window center is in dead space, but most of the+ # window is on the left display.+ virtual = _mon(0, 0, 2200, 1800)+ left = _mon(0, 800, 1000, 1000)+ upper = _mon(1000, 0, 1200, 800)+ monkeypatch.setattr(+ "jarvis.platform.window_state.foreground_window",+ lambda: WindowInfo(title="App", handle=9),+ )+ monkeypatch.setattr(+ "jarvis.platform.window_state.window_frame_rect",+ lambda _window: (700, 600, 800, 600),+ )++ selected = select_capture_monitor(+ [virtual, left, upper], strategy="foreground",+ )++ assert selected is left++def test_explicit_is_primary_flag_still_wins() -> None:flagged = {**_LEFT, "is_primary": True}mons = [_VIRTUAL, flagged, _MAIN]