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): platform actuators with landed-position read-back (wave 2)
Ruben Lütke10e4b4f1b8b9
diff --git a/jarvis/cu/actuate/__init__.py b/jarvis/cu/actuate/__init__.pynew file mode 100644index 0000000000..5c12d26300--- /dev/null+++ b/jarvis/cu/actuate/__init__.py@@ -0,0 +1,32 @@+"""Platform-native input actuation for Computer-Use v2.++One primitive vocabulary (`move / click / drag / scroll / key_combo /+type_text` + `cursor_pos` read-back) with a backend per platform:++* Windows — ``SendInput`` with absolute virtual-desktop positioning+ (negative-origin monitors included) and ``KEYEVENTF_UNICODE`` typing.+* macOS / Linux-X11 — ``pynput`` (Quartz points / X11 pixels, no+ primary-screen clamping), with a best-effort ``pyautogui`` fallback.+* Wayland / headless — honest refusal with an actionable message.++The backends are pure input dispatch: no overlay, no risk gating. The CU+tools remain the ToolExecutor-gated choke points (AP-3) and delegate their+raw input to this package.+"""+from jarvis.cu.actuate.base import (+ ActResult,+ ActuationUnavailable,+ Actuator,+ LANDING_TOLERANCE,+ get_actuator,+ verified_move,+)++__all__ = [+ "ActResult",+ "ActuationUnavailable",+ "Actuator",+ "LANDING_TOLERANCE",+ "get_actuator",+ "verified_move",+]diff --git a/jarvis/cu/actuate/base.py b/jarvis/cu/actuate/base.pynew file mode 100644index 0000000000..a88931d045--- /dev/null+++ b/jarvis/cu/actuate/base.py@@ -0,0 +1,171 @@+"""Actuator protocol, landed-position verification, backend selection.++Design contract (CU v2): a silent miss is worse than a loud failure. Every+pointer action therefore goes through :func:`verified_move` — position the+cursor, read it back, and refuse to press the button when the cursor did not+land within :data:`LANDING_TOLERANCE` of the target. A DPI mis-mapping or a+clamped multi-monitor move then surfaces as a diagnosable error string+instead of a click on the wrong control.++Backend selection is a runtime capability probe (never an OS allowlist in+callers): Windows -> native SendInput; macOS / Linux-X11 -> pynput (pyautogui+fallback); Wayland / headless -> :class:`ActuationUnavailable` with an+actionable message.+"""+from __future__ import annotations++import abc+import logging+import os+import sys+from dataclasses import dataclass++logger = logging.getLogger(__name__)++#: Max |cursor - target| in input units after a move before we refuse to act.+#: 2 units absorbs sub-pixel rounding; a real mapping bug is off by 10s-100s.+LANDING_TOLERANCE = 2+++class ActuationUnavailable(RuntimeError):+ """No input backend can act on this host (headless, Wayland, deps absent).++ The message is user-actionable and English (artifact rule); the spoken+ readback localizes separately.+ """+++@dataclass(frozen=True)+class ActResult:+ """Outcome of one actuation primitive."""++ ok: bool+ detail: str = ""+ landed: tuple[int, int] | None = None+++class Actuator(abc.ABC):+ """Platform input backend. Coordinates are input units on the virtual+ desktop (physical px on Windows/X11, points on macOS) — exactly the space+ :class:`jarvis.cu.geometry.CoordinateMapper` maps into."""++ name: str = "abstract"++ @abc.abstractmethod+ def cursor_pos(self) -> tuple[int, int] | None:+ """Current cursor position, or ``None`` when unreadable."""++ @abc.abstractmethod+ def move(self, x: int, y: int) -> None:+ """Position the cursor at ``(x, y)`` (no button activity)."""++ @abc.abstractmethod+ def click(+ self, x: int, y: int, *, button: str = "left", double: bool = False,+ ) -> None:+ """Press+release ``button`` at ``(x, y)``."""++ @abc.abstractmethod+ def drag(+ self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,+ ) -> None:+ """Press at start, move to end, release."""++ @abc.abstractmethod+ def scroll(+ self, direction: str, notches: int,+ *, x: int | None = None, y: int | None = None,+ ) -> None:+ """Wheel-scroll ``up/down/left/right``; optionally target ``(x, y)``."""++ @abc.abstractmethod+ def key_combo(self, keys: list[str]) -> None:+ """Press a key combination (modifiers first), release in reverse."""++ @abc.abstractmethod+ def type_text(self, text: str, *, delay_s: float = 0.02) -> None:+ """Type Unicode text into the focused control."""+++def verified_move(+ actuator: Actuator, x: int, y: int, *, tolerance: int = LANDING_TOLERANCE,+) -> ActResult:+ """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.+ """+ last: tuple[int, int] | None = None+ for attempt in (1, 2):+ actuator.move(int(x), int(y))+ last = actuator.cursor_pos()+ if last is None:+ return ActResult(+ ok=True,+ detail="cursor position unreadable — move unverified",+ landed=None,+ )+ if 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,+ )+ return ActResult(+ ok=False,+ detail=(+ f"cursor was positioned to ({x},{y}) but landed at {last} — "+ "coordinate-space mismatch (DPI/monitor mapping); refusing to act"+ ),+ landed=last,+ )+++# ---------------------------------------------------------------------------+# Backend selection+# ---------------------------------------------------------------------------++_WAYLAND_MSG = (+ "Cannot control mouse/keyboard on a Wayland session: Wayland blocks "+ "synthetic input for security. Log into an X11 session, or run Jarvis on "+ "a host with X11/Windows/macOS."+)+_HEADLESS_MSG = (+ "Cannot control mouse/keyboard: no display is present on this host "+ "(headless). Computer-Use needs a desktop session."+)+_NO_BACKEND_MSG = (+ "Cannot control mouse/keyboard: no input backend is installed. "+ "Install the desktop extras (pip install 'personal-jarvis[desktop]') "+ "to get pynput/pyautogui."+)+++def get_actuator() -> Actuator:+ """Resolve the platform input backend by runtime capability.++ Raises :class:`ActuationUnavailable` with an actionable English message+ when the host cannot receive synthetic input. Never returns a backend+ that is known-broken for the session type.+ """+ if os.name == "nt":+ from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415++ return WindowsActuator()++ from jarvis.platform.probes import display_present, is_wayland # noqa: PLC0415++ if sys.platform != "darwin":+ if is_wayland():+ raise ActuationUnavailable(_WAYLAND_MSG)+ if not display_present():+ raise ActuationUnavailable(_HEADLESS_MSG)++ from jarvis.cu.actuate.posix import PosixActuator # noqa: PLC0415++ try:+ return PosixActuator()+ except ActuationUnavailable:+ raise+ except Exception as exc: # noqa: BLE001 — import/init of pynput/pyautogui+ raise ActuationUnavailable(f"{_NO_BACKEND_MSG} ({exc})") from excdiff --git a/jarvis/cu/actuate/posix.py b/jarvis/cu/actuate/posix.pynew file mode 100644index 0000000000..d91dee4590--- /dev/null+++ b/jarvis/cu/actuate/posix.py@@ -0,0 +1,222 @@+"""macOS / Linux-X11 input backend — pynput preferred, pyautogui fallback.++Why pynput first: it drives Quartz (macOS) and XTest/Xlib (Linux) directly,+positions in the SAME units the OS reports (logical points on macOS — which+matches the mss capture rects the CoordinateMapper is built from — and X11+root pixels on Linux), and does NOT clamp coordinates to the primary screen.+pyautogui is kept as a fallback because it is already a desktop-extra+dependency, but it clamps moves to the primary monitor on multi-monitor+setups (upstream issue #413) — a warning is logged once when the fallback is+active so a misbehaving multi-monitor Linux/macOS setup is diagnosable.++Wayland is refused upstream in ``get_actuator`` (synthetic input is blocked+there); this module only ever runs on X11 or macOS.+"""+from __future__ import annotations++import logging+import time+from typing import Any++from jarvis.cu.actuate.base import ActuationUnavailable, Actuator++logger = logging.getLogger(__name__)++_NO_BACKEND_MSG = (+ "No input backend importable on this host: neither pynput nor pyautogui "+ "is installed. Install the desktop extras "+ "(pip install 'personal-jarvis[desktop]')."+)+++def _pynput_key_table(keyboard: Any) -> dict[str, Any]:+ """Map the CU key vocabulary onto pynput ``Key`` members.++ Built dynamically because some members are platform-dependent+ (``Key.insert`` is absent on macOS) — a missing member simply drops out+ of the table and surfaces as a clean "Unknown key" error.+ """+ key = keyboard.Key+ names = {+ "ctrl": "ctrl", "control": "ctrl",+ "shift": "shift",+ "alt": "alt", "menu": "alt",+ # "win" is the Super/Command key off-Windows.+ "win": "cmd", "windows": "cmd", "lwin": "cmd", "cmd": "cmd",+ "command": "cmd", "super": "cmd",+ "esc": "esc", "escape": "esc",+ "enter": "enter", "return": "enter",+ "tab": "tab",+ "space": "space", "spacebar": "space",+ "backspace": "backspace", "back": "backspace",+ "delete": "delete", "del": "delete",+ "insert": "insert", "ins": "insert",+ "home": "home", "end": "end",+ "pageup": "page_up", "pgup": "page_up",+ "pagedown": "page_down", "pgdn": "page_down",+ "left": "left", "up": "up", "right": "right", "down": "down",+ "capslock": "caps_lock",+ **{f"f{i}": f"f{i}" for i in range(1, 13)},+ }+ table: dict[str, Any] = {}+ for alias, member in names.items():+ target = getattr(key, member, None)+ if target is not None:+ table[alias] = target+ return table+++class PosixActuator(Actuator):+ """pynput-based backend (pyautogui fallback) for macOS and Linux/X11."""++ name = "posix-pynput"++ def __init__(self) -> None:+ self._mouse: Any = None+ self._keyboard: Any = None+ self._keys: dict[str, Any] = {}+ self._buttons: dict[str, Any] = {}+ self._pyautogui: Any = None+ try:+ from pynput import keyboard, mouse # noqa: PLC0415++ self._mouse = mouse.Controller()+ self._keyboard = keyboard.Controller()+ self._keys = _pynput_key_table(keyboard)+ self._buttons = {+ "left": mouse.Button.left,+ "right": mouse.Button.right,+ "middle": mouse.Button.middle,+ }+ return+ except Exception as exc: # noqa: BLE001 — pynput missing/unusable here+ logger.debug("pynput unavailable, trying pyautogui: %s", exc)+ try:+ import pyautogui # noqa: PLC0415++ # CU runs its own perceive->verify loop; pyautogui's corner+ # failsafe would abort a legitimate top-left click mid-mission.+ pyautogui.FAILSAFE = False+ self._pyautogui = pyautogui+ self.name = "posix-pyautogui"+ logger.warning(+ "[cu] input backend is pyautogui (pynput unavailable) — "+ "multi-monitor coordinates may clamp to the primary screen; "+ "install pynput for full multi-monitor support.",+ )+ except Exception as exc: # noqa: BLE001+ raise ActuationUnavailable(_NO_BACKEND_MSG) from exc++ # -- Actuator API -------------------------------------------------------++ def cursor_pos(self) -> tuple[int, int] | None:+ try:+ if self._mouse is not None:+ x, y = self._mouse.position+ else:+ pos = self._pyautogui.position()+ x, y = pos.x, pos.y+ return (int(x), int(y))+ except Exception: # noqa: BLE001 — read-back is best-effort+ logger.debug("cursor_pos failed", exc_info=True)+ return None++ def move(self, x: int, y: int) -> None:+ if self._mouse is not None:+ self._mouse.position = (int(x), int(y))+ else:+ self._pyautogui.moveTo(int(x), int(y))++ def click(+ self, x: int, y: int, *, button: str = "left", double: bool = False,+ ) -> None:+ 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)+ if 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,+ )++ def drag(+ self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,+ ) -> None:+ if 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",+ )+ return+ steps = 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):+ mx = x1 + (x2 - x1) * i / steps+ my = y1 + (y2 - y1) * i / steps+ self._mouse.position = (int(mx), int(my))+ if pause:+ time.sleep(pause)+ finally:+ # Never leave the button pressed — a stuck drag wedges the desktop.+ self._mouse.release(self._buttons["left"])++ def scroll(+ self, direction: str, notches: int,+ *, x: int | None = None, y: int | None = None,+ ) -> None:+ d = direction.lower()+ if d not in ("up", "down", "left", "right"):+ raise ValueError(+ f"Unknown direction: {direction!r}. Allowed: up/down/left/right",+ )+ n = abs(int(notches))+ if x is not None and y is not None:+ self.move(int(x), int(y))+ dx = n if d == "right" else -n if d == "left" else 0+ dy = n if d == "up" else -n if d == "down" else 0+ if self._mouse is not None:+ self._mouse.scroll(dx, dy)+ elif dx:+ self._pyautogui.hscroll(dx)+ else:+ self._pyautogui.scroll(dy)++ def key_combo(self, keys: list[str]) -> None:+ # Accept "ctrl+t" combined tokens like the Windows backend.+ from jarvis.cu.actuate.windows import expand_combo_keys # noqa: PLC0415++ expanded = expand_combo_keys([str(k) for k in keys])+ if self._keyboard is None:+ self._pyautogui.hotkey(*[k.lower() for k in expanded])+ return+ resolved: list[Any] = []+ for k in expanded:+ kl = k.strip().lower()+ if kl in self._keys:+ resolved.append(self._keys[kl])+ elif len(kl) == 1:+ resolved.append(kl)+ else:+ raise ValueError(f"Unknown key: {k!r}")+ for r in resolved:+ self._keyboard.press(r)+ for r in reversed(resolved):+ self._keyboard.release(r)++ def type_text(self, text: str, *, delay_s: float = 0.02) -> None:+ if self._keyboard is None:+ self._pyautogui.typewrite(text, interval=delay_s)+ return+ if delay_s <= 0:+ self._keyboard.type(text)+ return+ for char in text:+ self._keyboard.type(char)+ time.sleep(delay_s)diff --git a/jarvis/cu/actuate/windows.py b/jarvis/cu/actuate/windows.pynew file mode 100644index 0000000000..2ba619136d--- /dev/null+++ b/jarvis/cu/actuate/windows.py@@ -0,0 +1,341 @@+"""Windows input backend — SendInput, absolute virtual-desktop positioning.++Consolidates the proven Win32 primitives that previously lived duplicated+across the click/type_text/hotkey/scroll tools, with two hard rules learned+from live bugs:++* Every INPUT union declares MOUSEINPUT (the largest member) so+ ``sizeof(INPUT)`` is 40 bytes on x64 — an undersized struct makes+ ``SendInput`` reject every event with ERROR_INVALID_PARAMETER (the+ Google-Flights silent-typing bug, 2026-06-22).+* Pointer positioning uses ``MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK``+ (0..65535 normalized over the whole virtual desktop), never+ ``SetCursorPos`` — SetCursorPos returns unreliable results and misplaces+ across the primary boundary onto negative-origin monitors (the "CU clicks+ void on the left monitor" bug).++All calls run inside :func:`jarvis.cu.geometry.input_space` so metrics,+cursor read-back and event normalization share one per-monitor-DPI-aware+coordinate space even after pywebview flips the process awareness.+"""+from __future__ import annotations++import logging+import time+from types import SimpleNamespace++from jarvis.cu.actuate.base import Actuator+from jarvis.cu.geometry import input_space++logger = logging.getLogger(__name__)++_INPUT_MOUSE = 0+_INPUT_KEYBOARD = 1++_MOUSEEVENTF_MOVE = 0x0001+_MOUSEEVENTF_ABSOLUTE = 0x8000+_MOUSEEVENTF_VIRTUALDESK = 0x4000+_ABS_MOVE_FLAGS = _MOUSEEVENTF_MOVE | _MOUSEEVENTF_ABSOLUTE | _MOUSEEVENTF_VIRTUALDESK+_MOUSEEVENTF_WHEEL = 0x0800+_MOUSEEVENTF_HWHEEL = 0x01000+_WHEEL_DELTA = 120++_KEYEVENTF_KEYUP = 0x0002+_KEYEVENTF_UNICODE = 0x0004+_KEYEVENTF_EXTENDEDKEY = 0x0001++_MOUSE_FLAGS_DOWN: dict[str, int] = {+ "left": 0x0002, "right": 0x0008, "middle": 0x0020,+}+_MOUSE_FLAGS_UP: dict[str, int] = {+ "left": 0x0004, "right": 0x0010, "middle": 0x0040,+}++# Virtual-key codes (Microsoft "Virtual Key Codes"); lowercase aliases included.+_VK_TABLE: dict[str, int] = {+ "ctrl": 0x11, "control": 0x11,+ "shift": 0x10,+ "alt": 0x12, "menu": 0x12,+ "win": 0x5B, "windows": 0x5B, "lwin": 0x5B, "rwin": 0x5C,+ "esc": 0x1B, "escape": 0x1B,+ "enter": 0x0D, "return": 0x0D,+ "tab": 0x09,+ "space": 0x20, "spacebar": 0x20,+ "backspace": 0x08, "back": 0x08,+ "delete": 0x2E, "del": 0x2E,+ "insert": 0x2D, "ins": 0x2D,+ "home": 0x24, "end": 0x23,+ "pageup": 0x21, "pgup": 0x21,+ "pagedown": 0x22, "pgdn": 0x22,+ "left": 0x25, "up": 0x26, "right": 0x27, "down": 0x28,+ "capslock": 0x14,+ **{f"f{i}": 0x6F + i for i in range(1, 13)},+ "numpad0": 0x60, "numpad1": 0x61, "numpad2": 0x62, "numpad3": 0x63,+ "numpad4": 0x64, "numpad5": 0x65, "numpad6": 0x66, "numpad7": 0x67,+ "numpad8": 0x68, "numpad9": 0x69,+ "multiply": 0x6A, "add": 0x6B, "subtract": 0x6D,+ "decimal": 0x6E, "divide": 0x6F,+}++# Extended keys (E0 prefix) — without KEYEVENTF_EXTENDEDKEY a standalone tap+# is rejected or misrouted.+_EXTENDED_VKS = frozenset({+ 0x5B, 0x5C, 0x25, 0x26, 0x27, 0x28, 0x2D, 0x2E,+ 0x24, 0x23, 0x21, 0x22, 0x6F,+})+++def resolve_vk(key: str) -> int | None:+ """Virtual-key code for a key name, or ``None`` for an unknown key."""+ k = key.strip().lower()+ if not k:+ return None+ if k in _VK_TABLE:+ return _VK_TABLE[k]+ if len(k) == 1:+ if "a" <= k <= "z":+ return ord(k.upper())+ if "0" <= k <= "9":+ return ord(k)+ return None+++def expand_combo_keys(keys: list[str]) -> list[str]:+ """Split combined tokens like ``"ctrl+v"`` into ``["ctrl", "v"]``.++ LLM callers constantly emit whole shortcuts as one token. A token is only+ split when every part resolves to a known key, so a literal '+' key still+ errors loudly instead of vanishing.+ """+ out: list[str] = []+ for token in keys:+ 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):+ out.extend(parts)+ continue+ out.append(str(token))+ return out+++def normalize_virtualdesk(+ x: int, y: int, vx: int, vy: int, vw: int, vh: int,+) -> tuple[int, int]:+ """Map an absolute virtual-desktop pixel to the 0..65535 space+ ``MOUSEEVENTF_ABSOLUTE | VIRTUALDESK`` expects. The virtual origin+ ``(vx, vy)`` may be negative; folding it into the normalization is what+ makes a left-of-primary monitor come out as a valid coordinate."""+ dw = max(1, vw - 1)+ dh = max(1, vh - 1)+ nx = min(65535, max(0, round((int(x) - vx) * 65535 / dw)))+ ny = min(65535, max(0, round((int(y) - vy) * 65535 / dh)))+ return nx, ny+++def _structs() -> SimpleNamespace:+ """ctypes INPUT structs, built lazily so the module imports off-Windows."""+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ ULONG_PTR = wintypes.WPARAM++ class KEYBDINPUT(ctypes.Structure):+ _fields_ = (+ ("wVk", wintypes.WORD),+ ("wScan", wintypes.WORD),+ ("dwFlags", wintypes.DWORD),+ ("time", wintypes.DWORD),+ ("dwExtraInfo", ULONG_PTR),+ )++ class MOUSEINPUT(ctypes.Structure):+ _fields_ = (+ ("dx", wintypes.LONG),+ ("dy", wintypes.LONG),+ ("mouseData", wintypes.DWORD),+ ("dwFlags", wintypes.DWORD),+ ("time", wintypes.DWORD),+ ("dwExtraInfo", ULONG_PTR),+ )++ class INPUT_UNION(ctypes.Union):+ # MOUSEINPUT is the largest member and MUST be present — it sizes the+ # union so SendInput's cbSize check passes (see module docstring).+ _fields_ = (("mi", MOUSEINPUT), ("ki", KEYBDINPUT))++ class INPUT(ctypes.Structure):+ _fields_ = (("type", wintypes.DWORD), ("union", INPUT_UNION))++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ send_input = user32.SendInput+ send_input.argtypes = (wintypes.UINT, ctypes.POINTER(INPUT), ctypes.c_int)+ send_input.restype = wintypes.UINT++ return SimpleNamespace(+ ctypes=ctypes, wintypes=wintypes, user32=user32,+ send_input=send_input, ULONG_PTR=ULONG_PTR,+ KEYBDINPUT=KEYBDINPUT, MOUSEINPUT=MOUSEINPUT,+ INPUT_UNION=INPUT_UNION, INPUT=INPUT,+ )+++class WindowsActuator(Actuator):+ """SendInput-based backend. All coordinates: physical virtual-desktop px."""++ name = "windows-sendinput"++ def __init__(self) -> None:+ self._t = _structs()++ # -- helpers ----------------------------------------------------------++ def _virtual_bounds(self) -> tuple[int, int, int, int]:+ gsm = self._t.user32.GetSystemMetrics+ # SM_XVIRTUALSCREEN=76, SM_YVIRTUALSCREEN=77, SM_CX=78, SM_CY=79+ return (gsm(76), gsm(77), gsm(78), gsm(79))++ def _mouse_input(self, dx: int, dy: int, data: int, flags: int):+ t = self._t+ return t.INPUT(+ type=_INPUT_MOUSE,+ union=t.INPUT_UNION(+ mi=t.MOUSEINPUT(dx, dy, data, flags, 0, t.ULONG_PTR(0)),+ ),+ )++ def _key_input(self, vk: int, scan: int, flags: int):+ t = self._t+ return t.INPUT(+ type=_INPUT_KEYBOARD,+ union=t.INPUT_UNION(+ ki=t.KEYBDINPUT(vk, scan, flags, 0, t.ULONG_PTR(0)),+ ),+ )++ def _send(self, events: list) -> None:+ t = self._t+ arr = (t.INPUT * len(events))(*events)+ sent = t.send_input(len(events), arr, t.ctypes.sizeof(t.INPUT))+ if sent != len(events):+ err = t.ctypes.get_last_error()+ raise t.ctypes.WinError(err if err else None)++ def _abs_move_event(self, x: int, y: int):+ vx, vy, vw, vh = self._virtual_bounds()+ nx, ny = normalize_virtualdesk(int(x), int(y), vx, vy, vw, vh)+ return self._mouse_input(nx, ny, 0, _ABS_MOVE_FLAGS)++ # -- Actuator API -------------------------------------------------------++ def cursor_pos(self) -> tuple[int, int] | None:+ t = self._t+ pt = t.wintypes.POINT()+ with input_space():+ if not t.user32.GetCursorPos(t.ctypes.byref(pt)):+ return None+ return (int(pt.x), int(pt.y))++ def move(self, x: int, y: int) -> None:+ with input_space():+ self._send([self._abs_move_event(x, y)])++ def click(+ self, x: int, y: int, *, button: str = "left", double: bool = False,+ ) -> None:+ b = button.lower()+ if b not in _MOUSE_FLAGS_DOWN:+ raise ValueError(+ f"Unknown mouse button: {button!r}. Allowed: left/right/middle",+ )+ with input_space():+ events = [self._abs_move_event(x, y)]+ for _ in range(2 if double else 1):+ events.append(self._mouse_input(0, 0, 0, _MOUSE_FLAGS_DOWN[b]))+ events.append(self._mouse_input(0, 0, 0, _MOUSE_FLAGS_UP[b]))+ self._send(events)++ def drag(+ self, x1: int, y1: int, x2: int, y2: int, *, duration_s: float = 0.4,+ ) -> None:+ steps = max(2, min(40, int(duration_s * 60)))+ pause = max(0.0, duration_s) / steps+ with 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):+ mx = x1 + (x2 - x1) * i / steps+ my = y1 + (y2 - y1) * i / steps+ self._send([self._abs_move_event(int(mx), int(my))])+ if pause:+ time.sleep(pause)+ finally:+ # The button must come back up even if a mid-drag move fails —+ # a stuck pressed button makes the whole desktop unusable.+ self._send([self._mouse_input(0, 0, 0, _MOUSE_FLAGS_UP["left"])])++ def scroll(+ self, direction: str, notches: int,+ *, x: int | None = None, y: int | None = None,+ ) -> None:+ d = direction.lower()+ if d not in ("up", "down", "left", "right"):+ raise ValueError(+ f"Unknown direction: {direction!r}. Allowed: up/down/left/right",+ )+ delta = abs(int(notches)) * _WHEEL_DELTA+ if d in ("down", "left"):+ delta = -delta+ flag = _MOUSEEVENTF_HWHEEL if d in ("left", "right") else _MOUSEEVENTF_WHEEL+ data = delta & 0xFFFFFFFF # two's-complement DWORD+ with input_space():+ events = []+ if x is not None and y is not None:+ events.append(self._abs_move_event(int(x), int(y)))+ events.append(self._mouse_input(0, 0, data, flag))+ self._send(events)++ def key_combo(self, keys: list[str]) -> None:+ expanded = expand_combo_keys([str(k) for k in keys])+ vk_codes: list[int] = []+ for k in expanded:+ vk = resolve_vk(k)+ if vk is None:+ raise ValueError(f"Unknown key: {k!r}")+ vk_codes.append(vk)++ def flags(vk: int, *, keyup: bool) -> int:+ f = _KEYEVENTF_KEYUP if keyup else 0+ if vk in _EXTENDED_VKS:+ f |= _KEYEVENTF_EXTENDEDKEY+ return f++ events = [+ self._key_input(vk, 0, flags(vk, keyup=False)) for vk in vk_codes+ ] + [+ self._key_input(vk, 0, flags(vk, keyup=True))+ for vk in reversed(vk_codes)+ ]+ with input_space():+ self._send(events)++ def type_text(self, text: str, *, delay_s: float = 0.02) -> None:+ with input_space():+ for char in text:+ # KEYEVENTF_UNICODE takes UTF-16 code UNITS; astral-plane+ # characters (emoji) need their surrogate pair sent as two+ # events each — a bare ord() overflows the WORD wScan field.+ units = char.encode("utf-16-le")+ events = []+ for i in range(0, len(units), 2):+ code = int.from_bytes(units[i:i + 2], "little")+ events.append(self._key_input(0, code, _KEYEVENTF_UNICODE))+ events.append(+ self._key_input(+ 0, code, _KEYEVENTF_UNICODE | _KEYEVENTF_KEYUP,+ ),+ )+ self._send(events)+ if delay_s > 0:+ time.sleep(delay_s)diff --git a/tests/unit/cu/test_actuate.py b/tests/unit/cu/test_actuate.pynew file mode 100644index 0000000000..9326d2528b--- /dev/null+++ b/tests/unit/cu/test_actuate.py@@ -0,0 +1,174 @@+"""Actuator contract tests — landed-position verification and pure mapping.++No test here dispatches real input (clicks/keys would hit the developer's+desktop); real-input behaviour is exercised by scripts/cu_test_rig.py.+"""+from __future__ import annotations++import os++import pytest++from jarvis.cu.actuate.base import (+ ActResult,+ ActuationUnavailable,+ Actuator,+ verified_move,+)+from jarvis.cu.actuate.windows import (+ expand_combo_keys,+ normalize_virtualdesk,+ resolve_vk,+)+++class FakeActuator(Actuator):+ """Scriptable fake: lands where told to, records calls."""++ name = "fake"++ def __init__(self, landings: list[tuple[int, int] | None]) -> None:+ self.landings = list(landings)+ self.moves: list[tuple[int, int]] = []++ def cursor_pos(self):+ return self.landings.pop(0) if self.landings else None++ def move(self, x: int, y: int) -> None:+ self.moves.append((x, y))++ def click(self, x, y, *, button="left", double=False): # pragma: no cover+ raise NotImplementedError++ def drag(self, x1, y1, x2, y2, *, duration_s=0.4): # pragma: no cover+ raise NotImplementedError++ def scroll(self, direction, notches, *, x=None, y=None): # pragma: no cover+ raise NotImplementedError++ def key_combo(self, keys): # pragma: no cover+ raise NotImplementedError++ def type_text(self, text, *, delay_s=0.02): # pragma: no cover+ raise NotImplementedError+++# ---------------------------------------------------------------------------+# verified_move — the anti-silent-miss contract+# ---------------------------------------------------------------------------++def test_verified_move_accepts_exact_landing():+ fake = FakeActuator(landings=[(100, 200)])+ res = verified_move(fake, 100, 200)+ assert res.ok and res.landed == (100, 200)+ assert fake.moves == [(100, 200)]+++def test_verified_move_accepts_within_tolerance():+ fake = FakeActuator(landings=[(101, 198)])+ res = verified_move(fake, 100, 200)+ assert res.ok+++def test_verified_move_retries_once_then_fails_loudly():+ # Both attempts land 500px off (a DPI mis-mapping) -> refuse to act.+ fake = FakeActuator(landings=[(600, 200), (600, 200)])+ res = verified_move(fake, 100, 200)+ assert not res.ok+ assert len(fake.moves) == 2+ assert "coordinate-space mismatch" in res.detail+ assert res.landed == (600, 200)+++def test_verified_move_retry_recovers():+ fake = FakeActuator(landings=[(600, 200), (100, 200)])+ res = verified_move(fake, 100, 200)+ assert res.ok and len(fake.moves) == 2+++def test_verified_move_trusts_unreadable_cursor():+ fake = FakeActuator(landings=[None])+ res = verified_move(fake, 50, 60)+ assert res.ok and res.landed is None+ assert "unverified" in res.detail+++def test_act_result_is_frozen():+ res = ActResult(ok=True)+ with pytest.raises(Exception):+ res.ok = False # type: ignore[misc]+++# ---------------------------------------------------------------------------+# Windows pure mapping helpers (importable and testable on every OS)+# ---------------------------------------------------------------------------++def test_normalize_virtualdesk_folds_negative_origin():+ # Virtual desktop: left monitor at -3840, total 6400x2160.+ vx, vy, vw, vh = -3840, 0, 6400, 2160+ assert normalize_virtualdesk(-3840, 0, vx, vy, vw, vh) == (0, 0)+ nx, ny = normalize_virtualdesk(vx + vw - 1, vh - 1, vx, vy, vw, vh)+ assert (nx, ny) == (65535, 65535)+ # The live-log click target (-1398, 1147) maps strictly inside.+ nx, ny = normalize_virtualdesk(-1398, 1147, vx, vy, vw, vh)+ assert 0 < nx < 65535 and 0 < ny < 65535+++def test_normalize_virtualdesk_clamps_outside_points():+ assert normalize_virtualdesk(-9999, -9999, 0, 0, 1920, 1080) == (0, 0)+ assert normalize_virtualdesk(99999, 99999, 0, 0, 1920, 1080) == (65535, 65535)+++def test_resolve_vk_letters_digits_and_names():+ assert resolve_vk("a") == ord("A")+ assert resolve_vk("Z") == ord("Z")+ assert resolve_vk("7") == ord("7")+ assert resolve_vk("enter") == 0x0D+ assert resolve_vk("Ctrl") == 0x11+ assert resolve_vk("f12") == 0x7B+ assert resolve_vk("bogus") is None+ assert resolve_vk("") is None+++def test_expand_combo_keys_splits_known_combos_only():+ assert expand_combo_keys(["ctrl+v"]) == ["ctrl", "v"]+ assert expand_combo_keys(["ctrl+shift+t"]) == ["ctrl", "shift", "t"]+ assert expand_combo_keys(["ctrl", "v"]) == ["ctrl", "v"]+ # Unknown part -> token kept verbatim so it errors loudly downstream.+ assert expand_combo_keys(["ctrl+bogus"]) == ["ctrl+bogus"]+ assert expand_combo_keys(["+"]) == ["+"]+++# ---------------------------------------------------------------------------+# Backend selection on the current host (read-only construction)+# ---------------------------------------------------------------------------++def test_get_actuator_on_this_host():+ from jarvis.cu.actuate import get_actuator++ if os.name == "nt":+ actuator = get_actuator()+ assert actuator.name == "windows-sendinput"+ # Read-only: cursor read-back must work on a real desktop session.+ pos = actuator.cursor_pos()+ assert pos is None or (isinstance(pos[0], int) and isinstance(pos[1], int))+ else:+ # Non-Windows CI can be headless/Wayland — both must surface the+ # honest refusal instead of a broken backend.+ try:+ actuator = get_actuator()+ except ActuationUnavailable as exc:+ assert str(exc)+ else:+ assert actuator.name.startswith("posix-")+++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_table++ table = _pynput_key_table(keyboard)+ for name in ("ctrl", "shift", "alt", "enter", "tab", "esc", "left", "f5"):+ assert name in table+ # Off-Windows "win" must resolve to the platform super/command key.+ assert "win" in table