Skip to content

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.

fix(cu): stop macOS foreground-signature churn from refusing batched actions + cut per-action permission overhead

Personal Jarvis Maintainerbbef133ca623
diff --git a/jarvis/cu/actuate/base.py b/jarvis/cu/actuate/base.py
index 725699039b..aaba08a5bb 100644
--- a/jarvis/cu/actuate/base.py
+++ b/jarvis/cu/actuate/base.py
@@ -389,19 +389,31 @@ def _require_macos_input_permissions() -> None:
)
+#: Process-wide backend instance. Building a PosixActuator constructs pynput
+#: Controllers (keycode tables, layout snapshot) — doing that once per ACTION
+#: was pure per-click overhead. The desktop lock serializes missions, and the
+#: backends hold no per-action state, so one instance serves the process.
+_ACTUATOR_CACHE: Actuator | None = None
+
+
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.
+ that is known-broken for the session type. The permission and session
+ probes run on EVERY call (revocation must fail closed); only the backend
+ construction is reused.
"""
+ global _ACTUATOR_CACHE
_require_macos_input_permissions()
if os.name == "nt":
from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415
- return WindowsActuator()
+ if not isinstance(_ACTUATOR_CACHE, WindowsActuator):
+ _ACTUATOR_CACHE = WindowsActuator()
+ return _ACTUATOR_CACHE
from jarvis.platform.probes import display_present, is_wayland # noqa: PLC0415
@@ -413,9 +425,17 @@ def get_actuator() -> Actuator:
from jarvis.cu.actuate.posix import PosixActuator # noqa: PLC0415
+ if isinstance(_ACTUATOR_CACHE, PosixActuator):
+ return _ACTUATOR_CACHE
try:
- return PosixActuator()
+ actuator = PosixActuator()
except ActuationUnavailable:
raise
except Exception as exc: # noqa: BLE001 — import/init of pynput/pyautogui
raise ActuationUnavailable(f"{_NO_BACKEND_MSG} ({exc})") from exc
+ # Only the full pynput backend is retained: a pyautogui-fallback instance
+ # (e.g. the keyboard-layout cache was not primed yet at first use) must
+ # keep retrying pynput on later actions instead of being frozen in.
+ if actuator.name == "posix-pynput":
+ _ACTUATOR_CACHE = actuator
+ return actuator
diff --git a/jarvis/cu/capture.py b/jarvis/cu/capture.py
index 919b77933e..47f9748094 100644
--- a/jarvis/cu/capture.py
+++ b/jarvis/cu/capture.py
@@ -407,6 +407,11 @@ def capture_stable_frame(
return raw
deadline = time.monotonic() + max(0.0, stability_timeout_s)
+ # One permission probe per FRAME, not per re-grab: the stability loop can
+ # re-grab ~8 times inside 1.2 s, and a grant cannot plausibly be revoked
+ # and matter within that window — the engine independently re-probes
+ # before every dispatched action, which is the check that prevents blind
+ # input after a revocation.
_require_macos_screen_recording_permission()
current = guarded_grab()
stable = False
@@ -415,7 +420,6 @@ def capture_stable_frame(
if remaining <= 0:
break
sleep(min(max(0.01, stability_interval_s), remaining))
- _require_macos_screen_recording_permission()
nxt = guarded_grab()
if not frames_differ(current, nxt):
current = nxt
diff --git a/jarvis/cu/target_guard.py b/jarvis/cu/target_guard.py
index 939e9d8bd5..bea153c35e 100644
--- a/jarvis/cu/target_guard.py
+++ b/jarvis/cu/target_guard.py
@@ -20,6 +20,19 @@ def window_signature(
) -> tuple[Any, ...]:
if window is None:
return ("none",)
+ pid = getattr(window, "pid", None)
+ if pid:
+ # App-level identity. Only the macOS foreground probe fills ``pid``:
+ # there the per-window handle is the CGWindowID of the frontmost
+ # layer-0 window, which churns on focus changes INSIDE the same app
+ # (an address-bar suggestions dropdown is its own layer-0 window, and
+ # frame rects move with it). Comparing on the owning app keeps the
+ # guard's purpose — catching a cross-app focus steal between the
+ # screenshot and the action — without refusing every click->type
+ # batch (live incident 2026-07-20: 9 REFUSED actions in two runs).
+ # Windows/Linux probes leave ``pid`` unset and keep the stable
+ # per-window handle+rect identity.
+ return ("app", int(pid))
handle = getattr(window, "handle", None)
if handle:
return ("handle", int(handle), rect)
diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.py
index ab346012c2..c6051c36a1 100644
--- a/jarvis/platform/permissions.py
+++ b/jarvis/platform/permissions.py
@@ -233,6 +233,10 @@ class SystemPermissionPort:
# only for the current process and therefore clears exactly when the
# required app restart has happened.
self._restart_required: set[PermissionId] = set()
+ # Static per process: the main bundle and its on-disk path cannot
+ # change while this process runs. Caching it is NOT a cached
+ # permission probe — every TCC state read in _state() stays live.
+ self._bundle_identity_cache: tuple[str | None, str | None, bool, bool] | None = None
@property
def platform(self) -> PlatformName:
@@ -245,23 +249,18 @@ class SystemPermissionPort:
log.debug("Native permission framework %s is unavailable.", module, exc_info=True)
return None
- def _app_identity(self) -> tuple[AppIdentity, bool]:
- if self.platform != "darwin":
- from .probes import display_present
-
- return (
- AppIdentity(
- app_name=APP_NAME,
- expected_bundle_id=EXPECTED_BUNDLE_ID,
- bundle_id=None,
- bundle_path=None,
- launched_as_bundle=False,
- stable=False,
- foreground=False,
- ),
- not display_present(),
- )
+ def _bundle_identity(self) -> tuple[str | None, str | None, bool, bool]:
+ """``(bundle_id, bundle_path, launched_as_bundle, stable)``, cached.
+ Computed once per process: NSBundle metadata and the two
+ ``Path.resolve`` calls cannot change for a running process, and the
+ hot Computer-Use path probes permissions before every grab and every
+ input action — recomputing this each time cost two filesystem
+ resolutions plus ObjC bridge round trips per probe. The live TCC
+ grant states are deliberately NOT cached (see :meth:`_state`).
+ """
+ if self._bundle_identity_cache is not None:
+ return self._bundle_identity_cache
bundle_id: str | None = None
bundle_path: str | None = None
foundation = self._load("Foundation")
@@ -284,6 +283,31 @@ class SystemPermissionPort:
except (OSError, ValueError):
canonical_path = False
stable = bundle_id == EXPECTED_BUNDLE_ID and launched_as_bundle and canonical_path
+ self._bundle_identity_cache = (bundle_id, bundle_path, launched_as_bundle, stable)
+ return self._bundle_identity_cache
+
+ def _stable_identity(self) -> bool:
+ """The cached static half of the runtime-access gate (darwin only)."""
+ return self._bundle_identity()[3]
+
+ def _app_identity(self) -> tuple[AppIdentity, bool]:
+ if self.platform != "darwin":
+ from .probes import display_present
+
+ return (
+ AppIdentity(
+ app_name=APP_NAME,
+ expected_bundle_id=EXPECTED_BUNDLE_ID,
+ bundle_id=None,
+ bundle_path=None,
+ launched_as_bundle=False,
+ stable=False,
+ foreground=False,
+ ),
+ not display_present(),
+ )
+
+ bundle_id, bundle_path, launched_as_bundle, stable = self._bundle_identity()
foreground = False
headless = True
appkit = self._load("AppKit")
@@ -417,9 +441,11 @@ class SystemPermissionPort:
resolved = PermissionId(permission_id)
if self.platform != "darwin":
return self._state(resolved) in _READY_STATES
- identity, _headless = self._app_identity()
+ # Only the STATIC identity half gates runtime access — skip the
+ # AppKit foreground probe _app_identity() also performs; its result
+ # was never consulted here and it costs a window-server round trip.
return (
- identity.stable
+ self._stable_identity()
and resolved not in self._restart_required
and self._state(resolved) is PermissionState.GRANTED
)
@@ -429,8 +455,7 @@ class SystemPermissionPort:
requirements = FEATURE_REQUIREMENTS[feature]
if self.platform != "darwin":
return all(self._state(item) in _READY_STATES for item in requirements)
- identity, _headless = self._app_identity()
- return identity.stable and all(
+ return self._stable_identity() and all(
item not in self._restart_required and self._state(item) is PermissionState.GRANTED
for item in requirements
)
diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.py
index f7582bc9db..f9ca5193e7 100644
--- a/jarvis/platform/window_state.py
+++ b/jarvis/platform/window_state.py
@@ -63,6 +63,11 @@ class WindowInfo:
title: str
minimized: bool = False
handle: int | None = None
+ #: Owning process id, when the platform probe knows it. Only the macOS
+ #: foreground path fills this today; it lets the CU foreground guard use
+ #: app-level identity where per-window handles churn (see
+ #: ``jarvis.cu.target_guard.window_signature``).
+ pid: int | None = None
# ----------------------------------------------------------------------
@@ -942,11 +947,16 @@ def _foreground_window_macos() -> WindowInfo | None:
or entry.get("kCGWindowOwnerName")
or ""
)
- return WindowInfo(title=title, handle=number or None)
+ owner_pid = front_pid or _macos_window_pid(entry)
+ return WindowInfo(
+ title=title, handle=number or None, pid=owner_pid or None,
+ )
except (TypeError, ValueError):
continue
title = get_foreground_title()
- return WindowInfo(title=title) if title else None
+ if not title:
+ return None
+ return WindowInfo(title=title, pid=front_pid or None)
def _foreground_window_linux() -> WindowInfo | None:
diff --git a/tests/unit/cu/test_capture.py b/tests/unit/cu/test_capture.py
index 9bd4b5b189..87424a10fd 100644
--- a/tests/unit/cu/test_capture.py
+++ b/tests/unit/cu/test_capture.py
@@ -112,15 +112,15 @@ def test_macos_screen_recording_denial_stops_before_grab(monkeypatch):
@pytest.mark.real_tcc_gate
-def test_macos_screen_recording_is_rechecked_before_each_grab(monkeypatch):
+def test_macos_screen_recording_revoked_fails_before_any_grab(monkeypatch):
from jarvis.platform.permissions import PermissionState
- states = [True, False]
- calls = {"grab": 0}
+ calls = {"grab": 0, "probe": 0}
class _RevokedPort:
def runtime_access_granted(self, _permission_id):
- return states.pop(0)
+ calls["probe"] += 1
+ return False
def state(self, _permission_id):
return PermissionState.NOT_GRANTED
@@ -138,8 +138,42 @@ def test_macos_screen_recording_is_rechecked_before_each_grab(monkeypatch):
with pytest.raises(RuntimeError, match="Screen Recording"):
capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)
- assert calls["grab"] == 1
- assert states == []
+ assert calls["grab"] == 0
+ assert calls["probe"] == 1
+
+
+def test_macos_screen_recording_is_probed_once_per_frame(monkeypatch):
+ # The stability loop can re-grab many times inside one frame; the
+ # permission probe must run once per FRAME, not per re-grab — the engine
+ # re-probes before every dispatched action, which is the revocation gate.
+ from jarvis.platform.permissions import PermissionState
+
+ calls = {"grab": 0, "probe": 0}
+
+ class _GrantedPort:
+ def runtime_access_granted(self, _permission_id):
+ calls["probe"] += 1
+ return True
+
+ def state(self, _permission_id):
+ return PermissionState.GRANTED
+
+ monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")
+ monkeypatch.setattr(
+ "jarvis.platform.permissions.get_system_permission_port",
+ lambda: _GrantedPort(),
+ )
+
+ def grab(_bbox):
+ calls["grab"] += 1
+ return _solid((192, 108), (10, 20, 30))
+
+ frame = capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)
+
+ assert frame.stable is True
+ assert calls["grab"] == 2
+ assert calls["probe"] == 1
def test_capture_guard_rechecks_window_identity_around_each_grab():
diff --git a/tests/unit/cu/test_target_guard.py b/tests/unit/cu/test_target_guard.py
index 1e15f91e39..38dcf479a6 100644
--- a/tests/unit/cu/test_target_guard.py
+++ b/tests/unit/cu/test_target_guard.py
@@ -3,10 +3,50 @@ from __future__ import annotations
from contextlib import contextmanager
-from jarvis.cu.target_guard import read_foreground_target
+from jarvis.cu.target_guard import read_foreground_target, window_signature
from jarvis.platform.window_state import WindowInfo
+class TestWindowSignature:
+ """App-level identity when the probe knows the owning pid (macOS)."""
+
+ def test_pid_wins_over_handle_and_rect(self):
+ window = WindowInfo("Google Chrome", handle=4021, pid=812)
+ assert window_signature(window, (0, 25, 1440, 875)) == ("app", 812)
+
+ def test_same_app_window_churn_keeps_signature_stable(self):
+ # A click into the address bar spawns a suggestions dropdown: new
+ # frontmost layer-0 CGWindowID, new rect, same owning app. The guard
+ # must NOT see a foreground change (live incident 2026-07-20).
+ before = window_signature(
+ WindowInfo("Google Chrome", handle=4021, pid=812), (0, 25, 1440, 875),
+ )
+ after = window_signature(
+ WindowInfo("", handle=5177, pid=812), (105, 60, 900, 340),
+ )
+ assert before == after
+
+ def test_cross_app_focus_steal_still_detected(self):
+ chrome = window_signature(WindowInfo("Google Chrome", pid=812), None)
+ stealer = window_signature(WindowInfo("Zoom Meeting", pid=990), None)
+ assert chrome != stealer
+
+ def test_no_pid_keeps_per_window_handle_identity(self):
+ # Windows/Linux probes never set pid — their stable hwnd/X11-id plus
+ # rect identity must stay byte-for-byte what it was.
+ window = WindowInfo("Editor", handle=77)
+ assert window_signature(window, (100, 50, 800, 600)) == (
+ "handle", 77, (100, 50, 800, 600),
+ )
+
+ def test_no_pid_no_handle_falls_back_to_title(self):
+ window = WindowInfo("Some App")
+ assert window_signature(window, None) == ("title", "some app", None)
+
+ def test_none_window_is_none_signature(self):
+ assert window_signature(None, None) == ("none",)
+
+
def test_foreground_target_reads_window_and_rect_inside_input_space(monkeypatch):
state = {"inside": False, "entered": 0, "exited": 0}
window = WindowInfo("Editor", handle=77)
diff --git a/tests/unit/platform/test_window_state_rects.py b/tests/unit/platform/test_window_state_rects.py
index f4920b680f..0013e6ac02 100644
--- a/tests/unit/platform/test_window_state_rects.py
+++ b/tests/unit/platform/test_window_state_rects.py
@@ -77,6 +77,7 @@ def test_macos_foreground_window_is_first_normal_layer_window(monkeypatch):
def test_macos_without_quartz_degrades_to_title_only(monkeypatch):
monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
monkeypatch.setitem(sys.modules, "Quartz", None) # import -> ImportError
+ monkeypatch.setitem(sys.modules, "AppKit", None) # no frontmost pid either
monkeypatch.setattr(ws, "get_foreground_title", lambda: "Inbox")
win = ws.foreground_window()
assert win == WindowInfo(title="Inbox")