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(awareness): real macOS/Linux backends for idle + window-focus watchers
Ruben Lütke74ad13129a3d
diff --git a/jarvis/awareness/watchers/idle.py b/jarvis/awareness/watchers/idle.pyindex 61e474069e..be2ddf8a3f 100644--- a/jarvis/awareness/watchers/idle.py+++ b/jarvis/awareness/watchers/idle.py@@ -1,9 +1,10 @@-"""IdleDetector — polls ``GetLastInputInfo`` on a 1 s tick.+"""IdleDetector — polls the OS idle-time counter on a 1 s tick.Plan §5 explicitly permits polling for idle detection (as opposed to the-foreground window, which uses hooks). Rationale: ``GetLastInputInfo`` is-an O(1) ctypes call with no hook lifecycle. Mouse/KB WinEventHooks would-be a privacy risk (capturing all input) and have a UAC-proximity aspect.+foreground window, which uses hooks). Rationale: a single idle-seconds+read is an O(1) call with no hook lifecycle. Mouse/KB WinEventHooks (or+their macOS/Linux equivalents) would be a privacy risk (capturing all+input) and have a UAC-proximity aspect.Idle transition: Active → Idle when ``idle_seconds >= threshold_s``,Idle → Active on the first input afterwards. Both transitions emit an@@ -11,19 +12,43 @@ event and sync ``manager.state.is_idle`` plus``current_frame.idle_since_ns`` (via ``dataclasses.replace`` becauseFrameSnapshot is frozen).-Lazy imports: ``ctypes`` is only loaded inside ``_get_idle_seconds``.-On non-Windows the detector is functionally a no-op (returns 0 idle).+Per-OS idle-seconds backend, resolved ONCE in ``start()`` (never+re-probed per tick):+ * Windows — ``GetLastInputInfo`` via ctypes. Always available.+ * macOS — Quartz ``CGEventSourceSecondsSinceLastEventType``, lazily+ imported (optional ``pyobjc-framework-Quartz`` extra).+ * Linux — the ``xprintidle`` binary (X11 XScreenSaver extension), only+ when a real X11 display is present; unavailable on Wayland (no+ global idle-time query by OS design) and on headless hosts.++No backend available: ``start()`` logs ONE clear line and returns+WITHOUT starting the tick loop — mirrors ``WindowFocusWatcher``'s+honest degradation, instead of the previous behavior of spinning+forever and reporting "never idle" off Windows.++A backend that starts failing at runtime (binary uninstalled, native+call breaking) disables itself after ``_MAX_CONSECUTIVE_FAILURES``+consecutive failures instead of spamming the log or polling a dead+probe forever.++Lazy imports (AP-26): ``ctypes``, ``Quartz`` and the ``xprintidle``+subprocess call are all imported/spawned only inside their respective+backend methods, never at module scope."""from __future__ import annotationsimport asyncioimport logging-import os+import shutil+import subprocessimport timefrom dataclasses import replacefrom typing import TYPE_CHECKINGfrom jarvis.core.events import IdleEntered, IdleExited+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.platform import detect_platform+from jarvis.platform.probes import display_present, is_waylandif TYPE_CHECKING:from jarvis.awareness.manager import AwarenessManager@@ -33,10 +58,11 @@ logger = logging.getLogger(__name__)_TICK_SECONDS: float = 1.0_STOP_TIMEOUT_S: float = 1.0+_MAX_CONSECUTIVE_FAILURES: int = 5 # runtime probe failures before self-disablingclass IdleDetector:- """Polls ``GetLastInputInfo``. Emits idle transitions."""+ """Polls the OS idle-time counter. Emits idle transitions."""def __init__(self,@@ -52,13 +78,29 @@ class IdleDetector:self._stopped: bool = Falseself._is_idle: bool = Falseself._became_idle_at_ns: int = 0+ # Resolved once in start() — one of "win32"/"macos"/"linux", or+ # None if start() never ran / no backend is usable on this host.+ self._backend: str | None = None+ self._consecutive_failures: int = 0# ---- Lifecycle -----------------------------------------------------------async def start(self) -> None:- """Start the 1 s tick loop. Idempotent."""+ """Resolve the idle-seconds backend once, then start the 1 s tick+ loop. Idempotent.++ No usable backend (headless Linux, Wayland, missing xprintidle,+ missing pyobjc-Quartz): logs one clear line and returns without+ starting the loop.+ """if self._task is not None:return+ backend, reason = self._resolve_backend()+ if backend is None:+ logger.info("idle detection unavailable on this platform: %s", reason)+ return+ self._backend = backend+ self._consecutive_failures = 0self._stopped = Falseloop = asyncio.get_running_loop()self._task = loop.create_task(self._run(), name="awareness-idle")@@ -78,6 +120,40 @@ class IdleDetector:except Exception: # noqa: BLE001logger.debug("IdleDetector task ended with exception", exc_info=True)+ # ---- Backend resolution ---------------------------------------------------++ @staticmethod+ def _resolve_backend() -> tuple[str | None, str]:+ """Pick the idle-seconds backend for this OS, once.++ Returns ``(backend, reason)``. ``backend`` is one of+ ``"win32"``/``"macos"``/``"linux"``, or ``None`` when nothing usable+ was found; ``reason`` is a short human-readable explanation, only+ meaningful when ``backend`` is ``None``.+ """+ plat = detect_platform()+ if plat == "win32":+ return "win32", ""+ if plat == "darwin":+ try:+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ _ = Quartz.CGEventSourceSecondsSinceLastEventType+ except Exception: # noqa: BLE001+ return None, "pyobjc-framework-Quartz is not installed"+ return "macos", ""+ if plat == "linux":+ if is_wayland():+ return None, (+ "Wayland has no global idle-time query (X11-only via xprintidle)"+ )+ if not display_present():+ return None, "no graphical display detected (headless session)"+ if shutil.which("xprintidle") is None:+ return None, "xprintidle is not installed (e.g. `apt install xprintidle`)"+ return "linux", ""+ return None, f"unsupported platform ({plat})"+# ---- Tick-Loop -----------------------------------------------------------async def _run(self) -> None:@@ -101,12 +177,28 @@ class IdleDetector:Independently testable — tests call ``_tick_once()`` directly,without the ``_run()`` loop and therefore without waiting 1 s.++ A backend that raises is counted as a failure rather than crashing+ the loop; after ``_MAX_CONSECUTIVE_FAILURES`` in a row it disables+ idle detection for the rest of the session (one log line) instead+ of repeatedly polling a dead probe."""try:idle_seconds = await asyncio.to_thread(self._get_idle_seconds)except Exception: # noqa: BLE001- logger.debug("GetLastInputInfo failed", exc_info=True)+ self._consecutive_failures += 1+ logger.debug(+ "idle-seconds probe failed (backend=%s)", self._backend, exc_info=True,+ )+ if self._consecutive_failures >= _MAX_CONSECUTIVE_FAILURES:+ logger.info(+ "idle detection: %d consecutive probe failures on backend "+ "'%s' — disabling idle detection for this session",+ self._consecutive_failures, self._backend,+ )+ self._stopped = Truereturn+ self._consecutive_failures = 0now_ns = time.time_ns()should_be_idle = idle_seconds >= self._threshold_s@@ -135,21 +227,38 @@ class IdleDetector:self._manager.state.current_frame = replace(cur, idle_since_ns=None)await self._bus.publish(IdleExited(was_idle_for_ms=was_idle_for_ms))+ # ---- Idle-seconds dispatch -------------------------------------------------++ def _get_idle_seconds(self) -> float:+ """Idle seconds via the backend resolved once in ``start()``.++ Dispatches on ``self._backend`` (set by ``start()`` /+ ``_resolve_backend``). Each backend method is best-effort in its+ own right for expected conditions; unexpected failures propagate+ to ``_tick_once``'s failure counter instead of being swallowed+ here, so a persistently broken backend actually disables itself.+ """+ if self._backend == "win32":+ return self._get_idle_seconds_win32()+ if self._backend == "macos":+ return self._get_idle_seconds_macos()+ if self._backend == "linux":+ return self._get_idle_seconds_linux()+ return 0.0+# ---- Win32 ---------------------------------------------------------------@staticmethod- def _get_idle_seconds() -> float:+ def _get_idle_seconds_win32() -> float:"""``GetLastInputInfo`` + ``GetTickCount`` → idle seconds.Lazy-imports ``ctypes`` so the module can be imported on Linux/Mac- without a Win32 stack. On non-Windows: returns 0.0.+ without a Win32 stack.``GetTickCount`` returns ms-since-boot and wraps after ~49.7 days— the wrap is handled by 64-bit extension when``current_tick < info.dwTime``."""- if os.name != "nt":- return 0.0import ctypes # noqa: PLC0415from ctypes import wintypes # noqa: PLC0415@@ -169,3 +278,47 @@ class IdleDetector:current_tick += 0x100000000idle_ms = current_tick - info.dwTimereturn idle_ms / 1000.0++ # ---- macOS -----------------------------------------------------------------++ @staticmethod+ def _get_idle_seconds_macos() -> float:+ """``CGEventSourceSecondsSinceLastEventType`` — combined session+ state, any input event type. Lazy ``Quartz`` import (optional+ ``pyobjc-framework-Quartz`` extra).++ Raises if Quartz is unavailable or the native call fails — the+ caller (``_tick_once``) counts this as a probe failure rather than+ silently reporting "never idle".+ """+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415++ return float(Quartz.CGEventSourceSecondsSinceLastEventType(+ Quartz.kCGEventSourceStateCombinedSessionState,+ Quartz.kCGAnyInputEventType,+ ))++ # ---- Linux -----------------------------------------------------------------++ @staticmethod+ def _get_idle_seconds_linux() -> float:+ """``xprintidle`` prints idle milliseconds on stdout (X11+ XScreenSaver extension). Uses the shared ``NO_WINDOW_CREATIONFLAGS``+ convention (a no-op off Windows).++ Raises on a missing binary, non-zero exit, or timeout — the caller+ counts it as a probe failure rather than silently reporting "never+ idle".+ """+ result = subprocess.run(+ ["xprintidle"],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=2.0,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ if result.returncode != 0:+ raise RuntimeError(f"xprintidle exited with code {result.returncode}")+ return int((result.stdout or "").strip()) / 1000.0diff --git a/jarvis/awareness/watchers/window.py b/jarvis/awareness/watchers/window.pyindex d2d899e491..73f35e6fe6 100644--- a/jarvis/awareness/watchers/window.py+++ b/jarvis/awareness/watchers/window.py@@ -15,9 +15,24 @@ Architecture (binding):``PrivacyFilter`` + ``bus.publish`` of ``FrameUpdated`` or``AwarenessCaptureBlocked``.-Platform guard: ``os.name != "nt"`` makes ``start()`` a no-op (tests-run without a Win32 stack). Lazy imports of ``ctypes``, ``win32event``-and ``psutil`` INSIDE the methods (Plan §5 Hard-Negative HN3).+Platform guard: ``detect_platform() != "win32"`` routes ``start()`` to the+POSIX polling fallback below instead of the Win32 hook path. Lazy imports+of ``ctypes``, ``win32event`` and ``psutil`` INSIDE the methods (Plan §5+Hard-Negative HN3).++POSIX polling fallback (macOS/Linux): no OS-level foreground-change hook+is used there, so ``WindowFocusWatcher`` instead polls+``jarvis.platform.window_state.foreground_window()`` on a+``_POSIX_POLL_INTERVAL_S`` cadence and calls the SAME ``_emit_frame`` tail+the Win32 drain loop uses, so both platforms publish identical+``FrameUpdated`` / ``AwarenessCaptureBlocked`` events. macOS always has a+display (no TCC/Accessibility grant is needed just to read the frontmost+application — ``window_state.foreground_window()`` already degrades to+``None`` without the optional Screen-Recording grant or without pyobjc, and+that "no usable window" case feeds the same consecutive-failure counter+that disables the fallback rather than spinning forever). Headless Linux+and Wayland sessions are gated up front (mirrors ``IdleDetector``): one+honest log line, no polling task, no crash.Lifecycle order in ``stop()`` (subagent Q4, 6 phases):P1: cancel drain task (asyncio side first, so no ``bus.publish``@@ -35,18 +50,24 @@ from __future__ import annotationsimport asyncioimport loggingimport os+import shutil+import subprocessimport threadingimport timefrom typing import TYPE_CHECKINGfrom jarvis.awareness.state import FrameSnapshotfrom jarvis.core.events import AwarenessCaptureBlocked, FrameUpdated+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.core.win32_dpi import ensure_dpi_awareness+from jarvis.platform import detect_platform, window_state+from jarvis.platform.probes import display_present, is_waylandif TYPE_CHECKING:from jarvis.awareness.manager import AwarenessManagerfrom jarvis.awareness.privacy import PrivacyFilterfrom jarvis.core.bus import EventBus+ from jarvis.platform.window_state import WindowInfologger = logging.getLogger(__name__)@@ -63,6 +84,13 @@ _DRAIN_CANCEL_TIMEOUT_S: float = 0.5 # Stop-Phase 1_HWND_DEDUPE_NS: int = 50_000_000 # 50ms — schluckt Win32-Doppel-Events_PUMP_READY_TIMEOUT_S: float = 2.0 # start() wait-bis-Hook-gesetzt+# POSIX polling fallback (macOS/Linux) — no OS-level focus-change hook is+# used there, so we poll at a modest cadence instead. 2 s balances staying+# off the voice hot path against noticing an app switch reasonably fast.+_POSIX_POLL_INTERVAL_S: float = 2.0+_POSIX_POLL_MAX_FAILURES: int = 5 # consecutive empty probes before giving up+_POSIX_POLL_STOP_TIMEOUT_S: float = 1.5+class WindowFocusWatcher:"""Responds to foreground window changes via a Win32 hook."""@@ -92,6 +120,12 @@ class WindowFocusWatcher:# GC'd, the C pointer dangles, and Win32 calls invalid memory.self._wineventproc_ref: object | None = None+ # POSIX polling side (macOS/Linux fallback — no hook available)+ self._poll_task: asyncio.Task[None] | None = None+ self._poll_stop: asyncio.Event = asyncio.Event()+ self._poll_last_handle: int | None = None+ self._poll_last_title: str = ""+# Stateself._started: bool = Falseself._stopping: bool = False@@ -110,13 +144,16 @@ class WindowFocusWatcher:# ---- Lifecycle ----------------------------------------------------------async def start(self) -> None:- """Start pump thread and drain task. Idempotent.+ """Start the Win32 pump thread and drain task, or the POSIX polling+ fallback on macOS/Linux. Idempotent.- On Linux/Mac: no-op (tests run without Win32).+ Headless Linux / Wayland: logs one honest line and starts no task+ (mirrors ``IdleDetector``)."""if self._started:return- if os.name != "nt":+ if detect_platform() != "win32":+ self._start_posix_polling()self._started = Truereturn@@ -146,13 +183,22 @@ class WindowFocusWatcher:self._started = Trueasync def stop(self) -> None:- """Clean shutdown <2 s. Idempotent. 6-phase sequence."""+ """Clean shutdown <2 s. Idempotent. 6-phase sequence on Windows;+ a 2-phase cancel-and-join on the POSIX polling fallback."""if self._stopping:returnif not self._started:returnself._stopping = True+ if detect_platform() != "win32":+ try:+ await self._stop_posix_polling()+ finally:+ self._started = False+ self._stopping = False+ return+try:# P1: Drain-Task cancellen (asyncio-side)self._drain_stop.set()@@ -407,7 +453,27 @@ class WindowFocusWatcher:logger.debug("Window-meta lookup failed for hwnd=%d", hwnd, exc_info=True)return- # PrivacyFilter — on the asyncio thread, not the Win32 thread.+ await self._emit_frame(+ ts_ns=ts_ns, handle=hwnd, window_title=window_title,+ pid=pid, process_name=process_name,+ )++ async def _emit_frame(+ self, *, ts_ns: int, handle: int, window_title: str, pid: int, process_name: str,+ ) -> None:+ """Privacy-filter + probe + publish one resolved frame.++ Shared tail of both frame sources — the Win32 drain loop (hwnd+ events dequeued from the WinEventHook callback) and the POSIX+ polling fallback (macOS/Linux, see below) — so every platform+ builds and publishes the identical ``FrameUpdated`` /+ ``AwarenessCaptureBlocked`` event through one code path. Callers+ are responsible for their own change-detection/dedupe before+ calling this (the Win32 path dedupes by hwnd+timestamp in+ ``_drain_once``; the POSIX path dedupes by handle+title in+ ``_poll_once``).+ """+ # PrivacyFilter — on the asyncio thread, not a native callback.allowed, reason = self._privacy.is_allowed(window_title=window_title,process_name=process_name,@@ -426,8 +492,10 @@ class WindowFocusWatcher:probe_data = {}# Build FrameSnapshot and set AwarenessState.current_frame.- # Single-writer pattern: only this drain loop writes- # current_frame. Readers are synchronous in the same loop, no race.+ # Single-writer pattern: only this method writes current_frame+ # (the Win32 drain loop and the POSIX poll loop never run at the+ # same time — start() branches to exactly one of them). Readers+ # are synchronous in the same loop, no race.cur_frame = self._manager.state.current_frameidle_since_ns = cur_frame.idle_since_ns if cur_frame is not None else Nonesnap = FrameSnapshot(@@ -441,7 +509,7 @@ class WindowFocusWatcher:idle_since_ns=idle_since_ns,)self._manager.state.current_frame = snap- self._last_hwnd = hwnd+ self._last_hwnd = handleself._last_emit_ns = ts_ns# Publish bus event. allowed → FrameUpdated, blocked →@@ -493,3 +561,189 @@ class WindowFocusWatcher:return (title, pid_int, proc_name)except Exception: # noqa: BLE001return ("", 0, "")++ # ---- POSIX polling fallback (macOS/Linux) --------------------------------++ def _start_posix_polling(self) -> None:+ """Start the polling fallback, or degrade honestly.++ macOS always has a display (``probes.display_present()`` is+ unconditional there) and needs no permission just to read the+ frontmost application, so it always starts polling; a session+ that genuinely cannot be read (no pyobjc, or later a revoked+ grant) is discovered per-tick by ``_poll_once`` and disables the+ loop via the consecutive-failure counter instead of being gated+ here. Linux needs a real X11 session — headless hosts and Wayland+ compositors (no global foreground-window query by OS design, the+ same reason ``probes.has_hotkey``/``has_cursor`` refuse there) are+ rejected up front instead of polling a backend that can never work.+ """+ plat = detect_platform()+ if plat not in ("darwin", "linux"):+ logger.info(+ "window-focus tracking unavailable on this platform (%s)", plat,+ )+ return+ if plat == "linux" and (is_wayland() or not display_present()):+ logger.info(+ "window-focus tracking unavailable on this platform: "+ "no usable X11 display (headless session or Wayland)",+ )+ return++ self._poll_stop.clear()+ loop = asyncio.get_running_loop()+ self._poll_task = loop.create_task(+ self._poll_loop(), name="awareness-window-poll",+ )++ async def _stop_posix_polling(self) -> None:+ """Cancel the polling task, wait <1.5 s. Idempotent."""+ self._poll_stop.set()+ task = self._poll_task+ self._poll_task = None+ if task is None:+ return+ task.cancel()+ try:+ await asyncio.wait_for(task, timeout=_POSIX_POLL_STOP_TIMEOUT_S)+ except (TimeoutError, asyncio.CancelledError):+ pass+ except Exception: # noqa: BLE001+ logger.debug("POSIX poll task ended with exception", exc_info=True)++ async def _poll_loop(self) -> None:+ """Call ``_poll_once`` every ``_POSIX_POLL_INTERVAL_S`` until stopped.++ Stops itself after ``_POSIX_POLL_MAX_FAILURES`` consecutive probes+ that returned no usable window (missing pyobjc/xdotool, or a+ session that genuinely cannot be queried) instead of polling a+ dead backend forever. Waits on ``_poll_stop`` rather than a plain+ sleep so ``stop()`` wakes the loop immediately instead of waiting+ out the interval.+ """+ consecutive_failures = 0+ while not self._poll_stop.is_set():+ try:+ ok = await self._poll_once()+ except asyncio.CancelledError:+ break++ if ok:+ consecutive_failures = 0+ else:+ consecutive_failures += 1+ if consecutive_failures >= _POSIX_POLL_MAX_FAILURES:+ logger.info(+ "window-focus polling produced no usable window info "+ "for %d consecutive attempts — stopping (missing "+ "pyobjc/xdotool, or the session cannot be probed)",+ consecutive_failures,+ )+ return++ try:+ await asyncio.wait_for(+ self._poll_stop.wait(), timeout=_POSIX_POLL_INTERVAL_S,+ )+ except TimeoutError:+ pass+ except asyncio.CancelledError:+ break++ async def _poll_once(self) -> bool:+ """One polling iteration: probe the foreground window, emit a frame+ via :meth:`_emit_frame` if focus actually changed.++ Returns ``True`` when the probe returned usable window info+ (whether or not focus changed — an unchanged focus is still a+ healthy probe), ``False`` when it returned nothing usable (feeds+ the consecutive-failure counter in :meth:`_poll_loop`).+ Independently testable — tests call this directly instead of+ waiting out the real polling interval.+ """+ try:+ win = await asyncio.to_thread(self._posix_foreground_window)+ except Exception: # noqa: BLE001+ logger.debug("POSIX foreground-window probe failed", exc_info=True)+ return False++ if win is None or not (win.title or "").strip():+ return False++ changed = (win.handle, win.title) != (self._poll_last_handle, self._poll_last_title)+ if not changed:+ return True++ self._poll_last_handle = win.handle+ self._poll_last_title = win.title+ try:+ pid, process_name = await asyncio.to_thread(+ self._resolve_posix_focus_meta, win,+ )+ await self._emit_frame(+ ts_ns=time.time_ns(),+ handle=win.handle or 0,+ window_title=win.title,+ pid=pid,+ process_name=process_name,+ )+ except Exception: # noqa: BLE001+ logger.debug("POSIX frame emit failed", exc_info=True)+ return True++ @staticmethod+ def _posix_foreground_window() -> WindowInfo | None:+ """Thin seam over ``window_state.foreground_window`` — tests patch+ this directly to simulate macOS/Linux without a real display."""+ return window_state.foreground_window()++ @staticmethod+ def _resolve_posix_focus_meta(win: WindowInfo) -> tuple[int, str]:+ """Best-effort ``(pid, process_name)`` for a foreground ``WindowInfo``.++ macOS: the frontmost application via ``NSWorkspace`` — the same+ source ``window_state`` uses internally to resolve the foreground+ title, so pid and title stay consistent even without the+ Screen-Recording grant and without any Accessibility permission+ (NSWorkspace's frontmost-application query needs neither). Linux:+ ``xdotool`` resolves the owning pid from the X11 window id.+ ``psutil`` resolves the process name from the pid on both. Never+ raises — a missing pyobjc/xdotool or a transient lookup error+ degrades to ``(0, "")``; the frame still publishes and title-based+ privacy filtering still applies.+ """+ pid = 0+ try:+ plat = detect_platform()+ if plat == "darwin":+ from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415++ app = NSWorkspace.sharedWorkspace().frontmostApplication()+ if app is not None:+ pid = int(app.processIdentifier())+ elif plat == "linux" and win.handle and shutil.which("xdotool"):+ proc = subprocess.run(+ ["xdotool", "getwindowpid", str(int(win.handle))],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=5,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ if proc.returncode == 0:+ pid = int((proc.stdout or "").strip() or "0")+ except Exception: # noqa: BLE001+ logger.debug("POSIX focus pid resolution failed", exc_info=True)+ pid = 0++ process_name = ""+ if pid > 0:+ try:+ import psutil # noqa: PLC0415++ process_name = psutil.Process(pid).name()+ except Exception: # noqa: BLE001+ process_name = ""+ return pid, process_namediff --git a/tests/unit/awareness/test_idle_detector.py b/tests/unit/awareness/test_idle_detector.pyindex 06a507df5e..83b0024428 100644--- a/tests/unit/awareness/test_idle_detector.py+++ b/tests/unit/awareness/test_idle_detector.py@@ -13,11 +13,13 @@ Architecture assumptions that the wave-2 implementation is bound to:"""from __future__ import annotations+import sysimport timefrom unittest.mock import patchimport pytest+import jarvis.awareness.watchers.idle as idle_modfrom jarvis.awareness.config import AwarenessConfigfrom jarvis.awareness.manager import AwarenessManagerfrom jarvis.awareness.state import FrameSnapshot@@ -160,3 +162,168 @@ async def test_stop_idempotent_and_fast() -> None:await detector.stop()elapsed = time.perf_counter() - t0assert elapsed < 1.5+++# ---- Backend resolution (macOS/Linux) ----------------------------------------+# Platform behavior is simulated by monkeypatching the resolvers idle.py+# imports (detect_platform / display_present / is_wayland) so these tests run+# deterministically on any host, including this Windows dev machine.+++def test_resolve_backend_windows() -> None:+ with patch.object(idle_mod, "detect_platform", lambda: "win32"):+ backend, reason = IdleDetector._resolve_backend()+ assert backend == "win32"+ assert reason == ""+++def test_resolve_backend_macos_without_quartz(monkeypatch) -> None:+ """No pyobjc-Quartz importable → backend=None with a clear reason.++ Forced via ``sys.modules["Quartz"] = None`` (the standard "known+ unimportable" sentinel) so this is deterministic regardless of whether+ the host actually has pyobjc installed.+ """+ monkeypatch.setattr(idle_mod, "detect_platform", lambda: "darwin")+ monkeypatch.setitem(sys.modules, "Quartz", None)+ backend, reason = IdleDetector._resolve_backend()+ assert backend is None+ assert "Quartz" in reason+++def test_resolve_backend_linux_wayland(monkeypatch) -> None:+ monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(idle_mod, "is_wayland", lambda: True)+ backend, reason = IdleDetector._resolve_backend()+ assert backend is None+ assert "Wayland" in reason+++def test_resolve_backend_linux_headless(monkeypatch) -> None:+ monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)+ monkeypatch.setattr(idle_mod, "display_present", lambda: False)+ backend, reason = IdleDetector._resolve_backend()+ assert backend is None+ assert "headless" in reason+++def test_resolve_backend_linux_missing_xprintidle(monkeypatch) -> None:+ monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)+ monkeypatch.setattr(idle_mod, "display_present", lambda: True)+ monkeypatch.setattr(idle_mod.shutil, "which", lambda name: None)+ backend, reason = IdleDetector._resolve_backend()+ assert backend is None+ assert "xprintidle" in reason+++def test_resolve_backend_linux_available(monkeypatch) -> None:+ monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)+ monkeypatch.setattr(idle_mod, "display_present", lambda: True)+ monkeypatch.setattr(idle_mod.shutil, "which", lambda name: "/usr/bin/xprintidle")+ backend, reason = IdleDetector._resolve_backend()+ assert backend == "linux"+ assert reason == ""+++async def test_start_degrades_honestly_when_no_backend(monkeypatch, caplog) -> None:+ """No usable backend: start() logs one line and never creates the task+ (mirrors WindowFocusWatcher's honest degradation), instead of spinning+ the 1 s loop forever reporting "never idle"."""+ monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)+ monkeypatch.setattr(idle_mod, "display_present", lambda: False)++ detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)+ with caplog.at_level("INFO"):+ await detector.start()++ assert detector._task is None+ assert any("idle detection unavailable" in r.message for r in caplog.records)+ await detector.stop() # no crash on stop-without-start+++async def test_tick_disables_after_max_consecutive_failures() -> None:+ """A backend that always raises stops the loop after N failures, not+ before, and never crashes the tick."""+ detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)+ detector._backend = "linux"++ def _raise() -> float:+ raise RuntimeError("xprintidle vanished")++ with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(_raise)):+ for _ in range(idle_mod._MAX_CONSECUTIVE_FAILURES - 1):+ await detector._tick_once()+ assert detector._stopped is False+ await detector._tick_once()++ assert detector._stopped is True+ assert detector._consecutive_failures == idle_mod._MAX_CONSECUTIVE_FAILURES+++async def test_tick_resets_failure_counter_on_success() -> None:+ """A single successful tick after failures resets the counter to zero."""+ detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)+ detector._backend = "linux"+ detector._consecutive_failures = idle_mod._MAX_CONSECUTIVE_FAILURES - 1++ with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 0.0)):+ await detector._tick_once()++ assert detector._consecutive_failures == 0+ assert detector._stopped is False+++def test_get_idle_seconds_macos_backend(monkeypatch) -> None:+ """The macOS backend calls CGEventSourceSecondsSinceLastEventType and+ converts the result to a float."""+ import types++ fake_quartz = types.SimpleNamespace(+ CGEventSourceSecondsSinceLastEventType=lambda state, event_type: 12.5,+ kCGEventSourceStateCombinedSessionState=object(),+ kCGAnyInputEventType=object(),+ )+ monkeypatch.setitem(sys.modules, "Quartz", fake_quartz)++ detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)+ detector._backend = "macos"+ assert detector._get_idle_seconds() == 12.5+++def test_get_idle_seconds_linux_backend(monkeypatch) -> None:+ """The Linux backend parses xprintidle's stdout (milliseconds) to seconds."""+ class _FakeCompleted:+ returncode = 0+ stdout = "4200\n"++ monkeypatch.setattr(+ idle_mod.subprocess, "run", lambda *a, **kw: _FakeCompleted(),+ )++ detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)+ detector._backend = "linux"+ assert detector._get_idle_seconds() == 4.2+++def test_get_idle_seconds_linux_backend_raises_on_nonzero_exit(monkeypatch) -> None:+ """A non-zero xprintidle exit raises — the tick-level failure counter+ is what disables the backend, not a silent 0.0 here."""+ class _FakeCompleted:+ returncode = 1+ stdout = ""++ monkeypatch.setattr(+ idle_mod.subprocess, "run", lambda *a, **kw: _FakeCompleted(),+ )++ detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)+ detector._backend = "linux"+ with pytest.raises(RuntimeError):+ detector._get_idle_seconds()diff --git a/tests/unit/awareness/test_window_watcher.py b/tests/unit/awareness/test_window_watcher.pyindex 5e68f35ec4..a12d3f63d7 100644--- a/tests/unit/awareness/test_window_watcher.py+++ b/tests/unit/awareness/test_window_watcher.py@@ -20,12 +20,14 @@ from unittest.mock import patchimport pytest+import jarvis.awareness.watchers.window as window_modfrom jarvis.awareness.config import AwarenessConfigfrom jarvis.awareness.manager import AwarenessManagerfrom jarvis.awareness.privacy import PrivacyFilterfrom jarvis.awareness.watchers.window import WindowFocusWatcherfrom jarvis.core.bus import EventBusfrom jarvis.core.events import AwarenessCaptureBlocked, FrameUpdated+from jarvis.platform.window_state import WindowInfodef _make_components() -> tuple[EventBus, AwarenessManager, PrivacyFilter]:@@ -203,3 +205,194 @@ async def test_resolve_meta_failure_skips_frame_no_crash() -> None:await watcher._drain_once()assert len(received) == 0+++# ---- POSIX polling fallback (macOS/Linux) -----------------------------------+# Platform behavior is simulated by monkeypatching the resolvers window.py+# imports (detect_platform / display_present / is_wayland) so these tests run+# deterministically on any host, including this Windows dev machine.+++async def test_posix_start_degrades_honestly_on_headless_linux(monkeypatch) -> None:+ """start() on a headless Linux host logs one line and starts no poll task."""+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(window_mod, "display_present", lambda: False)+ monkeypatch.setattr(window_mod, "is_wayland", lambda: False)++ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ await watcher.start()++ assert watcher._poll_task is None+ await watcher.stop() # idempotent no-op, no crash, no hang+++async def test_posix_start_degrades_honestly_on_wayland(monkeypatch) -> None:+ """start() on a Wayland session logs one line and starts no poll task."""+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(window_mod, "display_present", lambda: True)+ monkeypatch.setattr(window_mod, "is_wayland", lambda: True)++ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ await watcher.start()++ assert watcher._poll_task is None+ await watcher.stop()+++async def test_posix_start_polls_on_macos(monkeypatch) -> None:+ """macOS always has a display — start() always starts the poll task."""+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")++ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window", staticmethod(lambda: None),+ ):+ await watcher.start()+ assert watcher._poll_task is not None+ await watcher.stop()++ assert watcher._poll_task is None+++async def test_posix_poll_once_emits_on_focus_change() -> None:+ """A changed foreground window publishes exactly one FrameUpdated."""+ bus, manager, privacy = _make_components()+ received: list[FrameUpdated] = []+ bus.subscribe(FrameUpdated, _async_collect(received))++ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window",+ staticmethod(lambda: WindowInfo(title="Terminal", handle=42)),+ ), patch.object(+ WindowFocusWatcher, "_resolve_posix_focus_meta",+ staticmethod(lambda win: (123, "Terminal.app")),+ ):+ ok_first = await watcher._poll_once()+ ok_second = await watcher._poll_once() # unchanged focus — no re-emit++ assert ok_first is True+ assert ok_second is True+ assert len(received) == 1+ assert received[0].process_name == "Terminal.app"+ assert received[0].pid == 123+ assert manager.state.current_frame is not None+ assert manager.state.current_frame.active_window_title == "Terminal"+++async def test_posix_poll_once_detects_a_second_focus_change() -> None:+ """Two distinct focus changes publish two distinct events."""+ bus, manager, privacy = _make_components()+ received: list[FrameUpdated] = []+ bus.subscribe(FrameUpdated, _async_collect(received))++ windows = iter([+ WindowInfo(title="Terminal", handle=1),+ WindowInfo(title="Browser", handle=2),+ ])++ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window",+ staticmethod(lambda: next(windows)),+ ), patch.object(+ WindowFocusWatcher, "_resolve_posix_focus_meta",+ staticmethod(lambda win: (1, "some.app")),+ ):+ await watcher._poll_once()+ await watcher._poll_once()++ assert len(received) == 2+ assert received[0].window_title == "Terminal"+ assert received[1].window_title == "Browser"+++async def test_posix_poll_once_routes_blocked_title_to_capture_blocked() -> None:+ """A privacy-blocked title publishes AwarenessCaptureBlocked, not FrameUpdated."""+ bus, manager, privacy = _make_components()+ blocked: list[AwarenessCaptureBlocked] = []+ updated: list[FrameUpdated] = []+ bus.subscribe(AwarenessCaptureBlocked, _async_collect(blocked))+ bus.subscribe(FrameUpdated, _async_collect(updated))++ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window",+ staticmethod(lambda: WindowInfo(title="Sparkasse Online-Banking", handle=9)),+ ), patch.object(+ WindowFocusWatcher, "_resolve_posix_focus_meta",+ staticmethod(lambda win: (55, "firefox")),+ ):+ await watcher._poll_once()++ assert len(blocked) == 1+ assert len(updated) == 0+++async def test_posix_poll_once_returns_false_on_no_window() -> None:+ """No usable window info → _poll_once reports a failure, no crash."""+ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window", staticmethod(lambda: None),+ ):+ ok = await watcher._poll_once()+ assert ok is False+++async def test_posix_poll_once_returns_false_on_probe_exception() -> None:+ """A raising probe is a failure too, not a crash."""+ def _raises() -> WindowInfo | None:+ raise RuntimeError("simulated Quartz failure")++ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window", staticmethod(_raises),+ ):+ ok = await watcher._poll_once()+ assert ok is False+++async def test_posix_poll_loop_stops_after_max_consecutive_failures(monkeypatch) -> None:+ """The poll loop self-disables after consecutive empty probes instead of+ spinning forever."""+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")+ monkeypatch.setattr(window_mod, "display_present", lambda: True)+ monkeypatch.setattr(window_mod, "is_wayland", lambda: False)+ monkeypatch.setattr(window_mod, "_POSIX_POLL_INTERVAL_S", 0.0)++ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ with patch.object(+ WindowFocusWatcher, "_posix_foreground_window", staticmethod(lambda: None),+ ):+ await watcher.start()+ assert watcher._poll_task is not None+ await asyncio.wait_for(watcher._poll_task, timeout=5.0)++ # The loop returned on its own (self-disabled) rather than being cancelled.+ assert watcher._poll_task.done()+ assert not watcher._poll_task.cancelled()+ await watcher.stop() # idempotent cleanup, no crash+++async def test_posix_stop_without_start_is_noop() -> None:+ """stop() without a prior start() is a no-op on the POSIX path too."""+ bus, manager, privacy = _make_components()+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)+ await watcher.stop()+ await watcher.stop()