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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-02 18:47)

Ruben Lütkee0f510fea76e
diff --git a/jarvis/core/win32_dpi.py b/jarvis/core/win32_dpi.py
index 75d8e8b427..827f2511b9 100644
--- a/jarvis/core/win32_dpi.py
+++ b/jarvis/core/win32_dpi.py
@@ -23,15 +23,58 @@ logger = logging.getLogger(__name__)
_DPI_AWARENESS_SET: bool = False
+# DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (winuser.h). V2 additionally
+# covers non-client areas and child windows and is the declaration
+# window-centric Computer-Use relies on: window rects, monitor metrics and
+# SendInput normalization all read the SAME physical-pixel virtual desktop.
+_DPI_CTX_PER_MONITOR_V2 = -4
+_E_ACCESSDENIED = -2147024891 # 0x80070005 — awareness already set: fine
+
+
+def _apply_process_awareness(windll) -> str:
+ """Declare process DPI awareness, most capable tier first.
+
+ Returns which tier landed: ``"per_monitor_v2"`` | ``"per_monitor"`` |
+ ``"system"`` | ``"none"``. Takes the ``ctypes.windll`` namespace injected
+ so the ladder is testable on any OS. Never raises.
+
+ 1. ``user32.SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2)``
+ (Windows 10 1703+) — the declaration the multi-monitor window
+ pipeline requires.
+ 2. ``shcore.SetProcessDpiAwareness(2)`` (Windows 8.1+, per-monitor V1).
+ 3. ``user32.SetProcessDPIAware()`` (system-aware last resort).
+ """
+ import ctypes # noqa: PLC0415
+
+ try:
+ set_ctx = windll.user32.SetProcessDpiAwarenessContext
+ if set_ctx(ctypes.c_void_p(_DPI_CTX_PER_MONITOR_V2)):
+ return "per_monitor_v2"
+ except (OSError, AttributeError):
+ logger.debug("SetProcessDpiAwarenessContext unavailable", exc_info=True)
+ try:
+ # PROCESS_PER_MONITOR_DPI_AWARE = 2; E_ACCESSDENIED = already set.
+ res = windll.shcore.SetProcessDpiAwareness(2)
+ if res in (0, _E_ACCESSDENIED):
+ return "per_monitor"
+ logger.debug("SetProcessDpiAwareness returned 0x%x", res & 0xFFFFFFFF)
+ except (OSError, AttributeError):
+ logger.debug("SetProcessDpiAwareness unavailable", exc_info=True)
+ try:
+ if windll.user32.SetProcessDPIAware():
+ return "system"
+ except (OSError, AttributeError):
+ logger.warning("Could not set DPI awareness", exc_info=True)
+ return "none"
+
+
def ensure_dpi_awareness() -> None:
- """Sets PER_MONITOR_AWARE_V2 via shcore (or user32 fallback).
+ """Declare the process PER_MONITOR_AWARE_V2 (with graceful fallbacks).
Idempotent — safe to call multiple times without side effects. Non-Windows
is a no-op; under Win32 the first call sets the awareness level,
- all subsequent calls are no-ops.
-
- - ``shcore.SetProcessDpiAwareness(2)`` is the modern API (Windows 8.1+).
- - ``user32.SetProcessDPIAware()`` as fallback for older systems.
+ all subsequent calls are no-ops. See :func:`_apply_process_awareness`
+ for the exact ladder (V2 context -> shcore per-monitor -> system-aware).
"""
global _DPI_AWARENESS_SET
if _DPI_AWARENESS_SET:
@@ -42,18 +85,10 @@ def ensure_dpi_awareness() -> None:
try:
import ctypes # noqa: PLC0415
- # PROCESS_PER_MONITOR_DPI_AWARE = 2
- res = ctypes.windll.shcore.SetProcessDpiAwareness(2)
- # S_OK == 0; E_ACCESSDENIED is returned when already set — that is OK.
- if res not in (0, -2147024891): # 0x80070005 = E_ACCESSDENIED
- logger.debug("SetProcessDpiAwareness returned 0x%x", res & 0xFFFFFFFF)
- except (OSError, AttributeError):
- try:
- import ctypes # noqa: PLC0415
-
- ctypes.windll.user32.SetProcessDPIAware()
- except Exception: # noqa: BLE001
- logger.warning("Could not set DPI awareness", exc_info=True)
+ tier = _apply_process_awareness(ctypes.windll)
+ logger.debug("process DPI awareness declared: %s", tier)
+ except Exception: # noqa: BLE001 — declaration is best-effort
+ logger.warning("Could not set DPI awareness", exc_info=True)
finally:
_DPI_AWARENESS_SET = True
diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.py
index a99091727b..d7fb515cd8 100644
--- a/jarvis/platform/window_state.py
+++ b/jarvis/platform/window_state.py
@@ -662,13 +662,23 @@ def window_rect(win: WindowInfo) -> tuple[int, int, int, int] | None:
def foreground_window() -> WindowInfo | None:
- """The current foreground window as a :class:`WindowInfo` (carrying the hwnd
- on Windows), or ``None``. Best-effort; never raises. macOS/Linux return a
- title-only WindowInfo (no handle), which the move path treats as "can't move"
- rather than acting blind."""
+ """The current foreground window as a :class:`WindowInfo`, or ``None``.
+
+ Carries the platform window id in ``handle`` on ALL three platforms
+ (Win32 hwnd; macOS CGWindowID via Quartz; X11 window id via xdotool) —
+ the id the window-centric capture pipeline resolves rects and native
+ grabs through. Hosts without the native backend (no Quartz, no xdotool,
+ Wayland) degrade to a title-only WindowInfo or ``None``. Best-effort;
+ never raises.
+ """
try:
- if detect_platform() == "win32":
+ plat = detect_platform()
+ if plat == "win32":
return _foreground_window_windows()
+ if plat == "darwin":
+ return _foreground_window_macos()
+ if plat == "linux":
+ return _foreground_window_linux()
title = get_foreground_title()
return WindowInfo(title=title) if title else None
except Exception: # noqa: BLE001
diff --git a/tests/unit/core/test_win32_dpi_declaration.py b/tests/unit/core/test_win32_dpi_declaration.py
new file mode 100644
index 0000000000..2460291b19
--- /dev/null
+++ b/tests/unit/core/test_win32_dpi_declaration.py
@@ -0,0 +1,106 @@
+"""Process DPI-awareness declaration ladder — Per-Monitor Aware V2 first.
+
+Window-centric Computer-Use requires the process to be declared
+PER_MONITOR_AWARE_V2 on Windows: without it, window rects and monitor
+metrics are DPI-virtualized per thread and the capture disagrees with the
+input space on mixed-DPI desktops. The ladder must try, in order:
+
+1. ``user32.SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2)`` (1703+),
+2. ``shcore.SetProcessDpiAwareness(2)`` (8.1+, V1),
+3. ``user32.SetProcessDPIAware()`` (system-aware last resort).
+
+The ladder is tested with an injected fake ``windll`` so it runs on any OS.
+"""
+from __future__ import annotations
+
+import ctypes
+
+from jarvis.core import win32_dpi
+
+
+class _Fn:
+ """Callable recording its calls; attribute-assignable like a ctypes fn."""
+
+ def __init__(self, result=1, raises: type[Exception] | None = None):
+ self.result = result
+ self.raises = raises
+ self.calls: list[tuple] = []
+
+ def __call__(self, *args):
+ self.calls.append(args)
+ if self.raises is not None:
+ raise self.raises("unavailable")
+ return self.result
+
+
+class _NS:
+ def __init__(self, **kw):
+ self.__dict__.update(kw)
+
+
+def _windll(*, v2=None, shcore=None, aware=None):
+ user32 = _NS(
+ SetProcessDpiAwarenessContext=v2 if v2 is not None else _Fn(),
+ SetProcessDPIAware=aware if aware is not None else _Fn(),
+ )
+ if v2 is None:
+ user32.SetProcessDpiAwarenessContext = _Fn()
+ shc = _NS(SetProcessDpiAwareness=shcore if shcore is not None else _Fn(0))
+ return _NS(user32=user32, shcore=shc)
+
+
+def test_v2_context_is_declared_first():
+ v2 = _Fn(result=1)
+ shcore = _Fn(result=0)
+ fake = _windll(v2=v2, shcore=shcore)
+ assert win32_dpi._apply_process_awareness(fake) == "per_monitor_v2"
+ assert len(v2.calls) == 1
+ (arg,) = v2.calls[0]
+ assert arg.value == ctypes.c_void_p(-4).value
+ assert shcore.calls == []
+
+
+def test_falls_back_to_shcore_per_monitor_v1():
+ v2 = _Fn(result=0) # refused (e.g. already set differently)
+ shcore = _Fn(result=0)
+ fake = _windll(v2=v2, shcore=shcore)
+ assert win32_dpi._apply_process_awareness(fake) == "per_monitor"
+ assert len(shcore.calls) == 1
+
+
+def test_shcore_access_denied_counts_as_already_per_monitor():
+ fake = _windll(v2=_Fn(result=0), shcore=_Fn(result=-2147024891))
+ assert win32_dpi._apply_process_awareness(fake) == "per_monitor"
+
+
+def test_missing_v2_symbol_falls_through_cleanly():
+ fake = _windll(v2=_Fn(raises=AttributeError), shcore=_Fn(result=0))
+ assert win32_dpi._apply_process_awareness(fake) == "per_monitor"
+
+
+def test_last_resort_is_system_aware():
+ aware = _Fn(result=1)
+ fake = _windll(
+ v2=_Fn(raises=AttributeError),
+ shcore=_Fn(raises=OSError),
+ aware=aware,
+ )
+ fake.user32.SetProcessDPIAware = aware
+ assert win32_dpi._apply_process_awareness(fake) == "system"
+ assert len(aware.calls) == 1
+
+
+def test_total_failure_reports_none():
+ fake = _windll(
+ v2=_Fn(raises=AttributeError),
+ shcore=_Fn(raises=OSError),
+ aware=_Fn(raises=OSError),
+ )
+ fake.user32.SetProcessDPIAware = _Fn(raises=OSError)
+ assert win32_dpi._apply_process_awareness(fake) == "none"
+
+
+def test_ensure_dpi_awareness_is_idempotent_and_safe():
+ # Behavioural contract only: repeated calls never raise on any host.
+ win32_dpi.ensure_dpi_awareness()
+ win32_dpi.ensure_dpi_awareness()
diff --git a/tests/unit/cu/test_window_roundtrip.py b/tests/unit/cu/test_window_roundtrip.py
new file mode 100644
index 0000000000..c812609c31
--- /dev/null
+++ b/tests/unit/cu/test_window_roundtrip.py
@@ -0,0 +1,279 @@
+"""Window-centric position-translation roundtrip — the multi-monitor contract.
+
+The product promise under test: Jarvis looks at the TARGET WINDOW, works with
+window-relative positions, and translates them into global screen positions
+via window origin + scale — through ONE central translation
+(:class:`jarvis.cu.geometry.CoordinateMapper`), no matter which monitor the
+window sits on and no matter the monitor's size or scale factor.
+
+Every case simulates a real platform layout end-to-end through the actual
+capture path (``capture_stable_frame`` with an injected grabber, real
+downscale/encode, real mapper):
+
+ known point in the window -> image position (what the model sees)
+ -> CoordinateMapper -> global position == window origin + point
+
+Also under test here:
+* window targets carry the platform window handle (native per-window capture),
+* ``grabber_for`` prefers the native per-window grab and falls back to the
+ rect grab,
+* the zoom-refine crop translation resolves through the SAME central mapper
+ (``_crop_norm_to_screen``) instead of hand-rolled math,
+* element snapping can never push a click outside the capture rect.
+"""
+from __future__ import annotations
+
+import math
+
+import pytest
+
+from jarvis.cu import capture as capture_mod
+from jarvis.cu.capture import capture_stable_frame, grabber_for, mss_grab
+from jarvis.cu.geometry import MonitorInfo
+
+# Each case: (id, window rect in input units, grab scale (pixels per input
+# unit — 1.0 everywhere except macOS Retina), probe points relative to the
+# window origin).
+LAYOUTS = [
+ pytest.param(
+ # Windows mixed-DPI: 150%-scaled 4K left of the primary — physical-px
+ # virtual desktop with a negative origin (the live 2026-06-27 bug).
+ MonitorInfo(left=-2000, top=100, width=1890, height=1040,
+ name="window:chrome-on-left-4k", window_handle=7),
+ 1.0,
+ [(1, 1), (945, 520), (1888, 1038), (378, 346)],
+ id="windows-left-4k-negative-origin",
+ ),
+ pytest.param(
+ # Windows stacked layout: monitor ABOVE the primary (negative Y).
+ MonitorInfo(left=300, top=-1800, width=800, height=600,
+ name="window:stacked-above", window_handle=11),
+ 1.0,
+ [(1, 1), (400, 300), (798, 598)],
+ id="windows-stacked-above-negative-y",
+ ),
+ pytest.param(
+ # macOS Retina: window rect in POINTS on a secondary display, capture
+ # backed at 2x PIXELS (ScreenCaptureKit / CG capture convention).
+ MonitorInfo(left=1728, top=-200, width=1200, height=800,
+ name="window:safari-retina", window_handle=42),
+ 2.0,
+ [(1, 1), (600, 400), (1198, 798), (240, 267)],
+ id="macos-retina-secondary-points",
+ ),
+ pytest.param(
+ # Linux/X11: root-pixel space, window on a 4K screen right of primary.
+ MonitorInfo(left=2400, top=300, width=1000, height=700,
+ name="window:firefox-x11", window_handle=123456),
+ 1.0,
+ [(1, 1), (500, 350), (998, 698)],
+ id="linux-x11-right-4k",
+ ),
+ pytest.param(
+ # Fallback scope: no target window (desktop/taskbar action) — the
+ # whole monitor runs through the SAME translation.
+ MonitorInfo(left=-3840, top=0, width=3840, height=2160,
+ name="left-4k-monitor"),
+ 1.0,
+ [(10, 10), (1920, 1080), (3830, 2150)],
+ id="monitor-fallback-same-translation",
+ ),
+]
+
+
+def _synthetic_grab(scale: float):
+ """Grabber returning a black frame of ``bbox size * scale`` pixels."""
+
+ def grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
+ gw = round(bbox["width"] * scale)
+ gh = round(bbox["height"] * scale)
+ return ((gw, gh), bytes(gw * gh * 3))
+
+ return grab
+
+
[email protected](("target", "scale", "probes"), LAYOUTS)
+def test_window_point_roundtrips_to_global_hit(target, scale, probes):
+ frame = capture_stable_frame(
+ target, grab=_synthetic_grab(scale), stability_timeout_s=0.0,
+ )
+ m = frame.mapper
+ # One image pixel expressed in window units — the quantization floor.
+ tol = math.ceil(target.width / frame.image_width)
+ for wx, wy in probes:
+ expected = (target.left + wx, target.top + wy)
+
+ # Pixel convention (Claude/OpenAI): the model points at the image
+ # pixel showing the window point.
+ ix = wx * frame.image_width / target.width
+ iy = wy * frame.image_height / target.height
+ gx, gy = m.image_to_screen(ix, iy)
+ assert abs(gx - expected[0]) <= tol, (target.name, (wx, wy), (gx, gy))
+ assert abs(gy - expected[1]) <= tol
+ assert m.contains_screen(gx, gy)
+
+ # Normalized convention (Gemini): 0..1000 grid over the same image.
+ nx = wx / target.width * 1000.0
+ ny = wy / target.height * 1000.0
+ gx2, gy2 = m.normalized_to_screen(nx, ny)
+ assert abs(gx2 - expected[0]) <= tol + 1
+ assert abs(gy2 - expected[1]) <= tol + 1
+ assert m.contains_screen(gx2, gy2)
+
+ # Inverse direction (verification crops) returns to the same pixel.
+ ix2, iy2 = m.screen_to_image(gx, gy)
+ assert abs(ix2 - ix) <= 1
+ assert abs(iy2 - iy) <= 1
+
+
[email protected](("target", "scale", "probes"), LAYOUTS)
+def test_model_coordinates_can_never_escape_the_capture_rect(
+ target, scale, probes,
+):
+ frame = capture_stable_frame(
+ target, grab=_synthetic_grab(scale), stability_timeout_s=0.0,
+ )
+ m = frame.mapper
+ for x, y in [(-50, -50), (0, 0), (10_000, 10_000)]:
+ assert m.contains_screen(*m.image_to_screen(x, y))
+ for nx, ny in [(0, 0), (1000, 1000), (1400, -3)]:
+ assert m.contains_screen(*m.normalized_to_screen(nx, ny))
+
+
+# ---------------------------------------------------------------------------
+# Window identity on the capture target + native-grab fallback chain
+# ---------------------------------------------------------------------------
+
+def test_window_target_carries_the_platform_window_handle(monkeypatch):
+ from jarvis.platform import window_state as ws
+ from jarvis.platform.window_state import WindowInfo
+
+ monitor = MonitorInfo(left=-2560, top=0, width=2560, height=1440,
+ name="left")
+ monkeypatch.setattr(
+ capture_mod, "select_monitor", lambda policy, main_monitor: monitor,
+ )
+ monkeypatch.setattr(
+ ws, "foreground_window", lambda: WindowInfo(title="App", handle=4242),
+ )
+ monkeypatch.setattr(ws, "is_shell_window", lambda w: False)
+ monkeypatch.setattr(
+ ws, "window_frame_rect", lambda w: (-2000, 100, 800, 600),
+ )
+ got = capture_mod.select_capture_target("foreground", scope="window")
+ assert got.window_handle == 4242
+ assert got.name.startswith("window:")
+
+
+def test_monitor_fallback_target_has_no_window_handle(monkeypatch):
+ from jarvis.platform import window_state as ws
+
+ monitor = MonitorInfo(left=0, top=0, width=1920, height=1080)
+ monkeypatch.setattr(
+ capture_mod, "select_monitor", lambda policy, main_monitor: monitor,
+ )
+ monkeypatch.setattr(ws, "foreground_window", lambda: None)
+ got = capture_mod.select_capture_target("foreground", scope="window")
+ assert got.window_handle is None
+
+
+def test_grabber_for_plain_monitor_is_the_rect_grab():
+ assert grabber_for(MonitorInfo(0, 0, 800, 600)) is mss_grab
+
+
+def test_grabber_for_window_uses_native_grab_when_available(monkeypatch):
+ from jarvis.platform import window_capture
+
+ native = ((80, 60), bytes(80 * 60 * 3))
+ monkeypatch.setattr(
+ window_capture, "grab_window", lambda handle, bbox: native,
+ )
+ monkeypatch.setattr(
+ capture_mod, "mss_grab",
+ lambda bbox: (_ for _ in ()).throw(AssertionError("mss must not run")),
+ )
+ target = MonitorInfo(0, 0, 80, 60, name="window:x", window_handle=9)
+ assert grabber_for(target)({"left": 0, "top": 0, "width": 80,
+ "height": 60}) == native
+
+
+def test_grabber_for_window_falls_back_to_rect_grab(monkeypatch):
+ from jarvis.platform import window_capture
+
+ fallback = ((80, 60), b"\x01" * (80 * 60 * 3))
+ monkeypatch.setattr(window_capture, "grab_window",
+ lambda handle, bbox: None)
+ monkeypatch.setattr(capture_mod, "mss_grab", lambda bbox: fallback)
+ target = MonitorInfo(0, 0, 80, 60, name="window:x", window_handle=9)
+ grab = grabber_for(target)
+ bbox = {"left": 0, "top": 0, "width": 80, "height": 60}
+ assert grab(bbox) == fallback
+ # The unavailable verdict sticks — the native probe is not repeated on
+ # every stability re-grab.
+ calls = {"n": 0}
+
+ def count_native(handle, bbox):
+ calls["n"] += 1
+ return None
+
+ monkeypatch.setattr(window_capture, "grab_window", count_native)
+ grab2 = grabber_for(target)
+ grab2(bbox)
+ grab2(bbox)
+ assert calls["n"] == 1
+
+
+# ---------------------------------------------------------------------------
+# Zoom-refine translation goes through the central mapper
+# ---------------------------------------------------------------------------
+
+def test_refine_crop_translation_resolves_through_central_mapper():
+ from jarvis.cu.engine import _crop_norm_to_screen
+
+ bbox = {"left": -2440, "top": 200, "width": 440, "height": 440}
+ assert _crop_norm_to_screen(bbox, (440, 440), 500, 500) == (-2220, 420)
+ # Retina: the crop image is 2x the bbox units — the normalized grid must
+ # still resolve against the bbox rect, not the pixel image.
+ assert _crop_norm_to_screen(bbox, (880, 880), 500, 500) == (-2220, 420)
+ # The extreme edge stays INSIDE the crop rect (the old hand-rolled math
+ # produced left+width — one unit outside).
+ x, y = _crop_norm_to_screen(bbox, (440, 440), 1000, 1000)
+ assert (x, y) == (-2440 + 439, 200 + 439)
+
+
+# ---------------------------------------------------------------------------
+# Element snapping stays inside the capture rect
+# ---------------------------------------------------------------------------
+
+def test_snap_never_leaves_the_capture_rect():
+ from jarvis.cu.verify import snap_point_to_element
+
+ # Element sticks out of the window capture on the right: its center lies
+ # OUTSIDE the rect. Snapping there would click outside the window.
+ clickables = [("Wide toolbar button", "Button", (950, 100, 200, 30))]
+ rect = (0, 0, 1000, 800)
+ hit = snap_point_to_element(
+ 960, 110, clickables, capture_area=1000 * 800, capture_rect=rect,
+ )
+ assert hit is None
+ # A fully inside element still snaps normally.
+ clickables = [("Save", "Button", (900, 100, 60, 30))]
+ hit = snap_point_to_element(
+ 920, 110, clickables, capture_area=1000 * 800, capture_rect=rect,
+ )
+ assert hit == (930, 115, "Save")
+
+
+# ---------------------------------------------------------------------------
+# Wayland: detect cleanly, refuse with an actionable X11/XWayland message
+# ---------------------------------------------------------------------------
+
+def test_wayland_refusal_points_to_x11_and_xwayland(monkeypatch):
+ import jarvis.platform.probes as probes
+ from jarvis.cu.engine import _wayland_refusal
+
+ monkeypatch.setattr(probes, "is_wayland", lambda: True)
+ msg = _wayland_refusal()
+ assert msg is not None
+ assert "X11" in msg
+ assert "XWayland" in msg
diff --git a/tests/unit/platform/test_window_state_rects.py b/tests/unit/platform/test_window_state_rects.py
new file mode 100644
index 0000000000..cd212b7efa
--- /dev/null
+++ b/tests/unit/platform/test_window_state_rects.py
@@ -0,0 +1,189 @@
+"""Cross-platform window identity + frame rect — every OS is first-class.
+
+The multi-monitor Computer-Use fix stands on reading the TARGET WINDOW's
+frame rect in the platform's input units on ALL three platforms:
+
+* Windows — DWM extended frame bounds by hwnd (existing, DPI-pinned caller),
+* macOS — Quartz ``CGWindowListCopyWindowInfo`` bounds (global points,
+ top-left origin: the SAME space Quartz mouse events and mss rects use),
+* Linux/X11 — ``xdotool`` geometry by window id (root pixels); Wayland
+ degrades to ``None`` (callers fall back to monitor scope + the engine's
+ clear X11/XWayland message).
+
+All native backends are faked — these tests run on any host.
+"""
+from __future__ import annotations
+
+import subprocess
+import sys
+import types
+
+import pytest
+
+from jarvis.platform import window_state as ws
+from jarvis.platform.window_state import WindowInfo
+
+
+# ---------------------------------------------------------------------------
+# macOS (fake Quartz)
+# ---------------------------------------------------------------------------
+
+def _fake_quartz(entries: list[dict]) -> types.ModuleType:
+ mod = types.ModuleType("Quartz")
+ mod.kCGWindowListOptionOnScreenOnly = 1 << 0
+ mod.kCGWindowListExcludeDesktopElements = 1 << 4
+ mod.kCGNullWindowID = 0
+ mod.CGWindowListCopyWindowInfo = lambda options, relative_to: entries
+ return mod
+
+
+_MAIL_WINDOW = {
+ "kCGWindowNumber": 7,
+ "kCGWindowLayer": 0,
+ "kCGWindowBounds": {"X": 1728.0, "Y": -200.0,
+ "Width": 1200.0, "Height": 800.0},
+ "kCGWindowName": "Inbox",
+ "kCGWindowOwnerName": "Mail",
+}
+_OVERLAY = {
+ "kCGWindowNumber": 3,
+ "kCGWindowLayer": 25, # status-bar layer — never a capture target
+ "kCGWindowBounds": {"X": 0.0, "Y": 0.0, "Width": 3456.0, "Height": 24.0},
+ "kCGWindowName": "Item-0",
+ "kCGWindowOwnerName": "SystemUIServer",
+}
+
+
+def test_macos_frame_rect_resolves_by_window_number(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ monkeypatch.setitem(
+ sys.modules, "Quartz", _fake_quartz([_OVERLAY, _MAIL_WINDOW]),
+ )
+ rect = ws.window_frame_rect(WindowInfo(title="Inbox", handle=7))
+ assert rect == (1728, -200, 1200, 800)
+
+
+def test_macos_foreground_window_is_first_normal_layer_window(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ monkeypatch.setitem(
+ sys.modules, "Quartz", _fake_quartz([_OVERLAY, _MAIL_WINDOW]),
+ )
+ win = ws.foreground_window()
+ assert win is not None
+ assert win.handle == 7
+ assert win.title == "Inbox"
+
+
+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.setattr(ws, "get_foreground_title", lambda: "Inbox")
+ win = ws.foreground_window()
+ assert win == WindowInfo(title="Inbox")
+ assert ws.window_frame_rect(WindowInfo(title="Inbox", handle=7)) is None
+
+
+# ---------------------------------------------------------------------------
+# Linux / X11 (fake xdotool)
+# ---------------------------------------------------------------------------
+
+def _wire_x11(monkeypatch, responses: dict[str, str]) -> list[list[str]]:
+ """Fake ``subprocess.run`` keyed by the xdotool subcommand."""
+ calls: list[list[str]] = []
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: False)
+ monkeypatch.setattr(ws, "display_present", lambda: True)
+ monkeypatch.setattr(ws.shutil, "which", lambda name: f"/usr/bin/{name}")
+
+ def fake_run(cmd, **kwargs):
+ calls.append(list(cmd))
+ key = cmd[1] if len(cmd) > 1 else ""
+ out = responses.get(key)
+ if out is None:
+ return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="")
+ return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr="")
+
+ monkeypatch.setattr(ws.subprocess, "run", fake_run)
+ return calls
+
+
+def test_linux_frame_rect_resolves_by_window_id(monkeypatch):
+ calls = _wire_x11(monkeypatch, {
+ "getwindowgeometry":
+ "WINDOW=123456\nX=2400\nY=300\nWIDTH=1000\nHEIGHT=700\nSCREEN=0\n",
+ })
+ rect = ws.window_frame_rect(WindowInfo(title="Firefox", handle=123456))
+ assert rect == (2400, 300, 1000, 700)
+ assert any("123456" in c for call in calls for c in call)
+
+
+def test_linux_foreground_window_carries_the_x11_id(monkeypatch):
+ _wire_x11(monkeypatch, {
+ "getactivewindow": "123456\n",
+ })
+ win = ws.foreground_window()
+ assert win is not None
+ assert win.handle == 123456
+
+
+def test_wayland_frame_rect_is_none_without_probing(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: True)
+
+ def boom(cmd, **kwargs): # pragma: no cover - must never run
+ raise AssertionError("no subprocess may run under Wayland")
+
+ monkeypatch.setattr(ws.subprocess, "run", boom)
+ assert ws.window_frame_rect(WindowInfo(title="App", handle=1)) is None
+
+
+def test_linux_without_xdotool_degrades_to_none(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: False)
+ monkeypatch.setattr(ws, "display_present", lambda: True)
+ monkeypatch.setattr(ws.shutil, "which", lambda name: None)
+ assert ws.window_frame_rect(WindowInfo(title="App", handle=1)) is None
+
+
+# ---------------------------------------------------------------------------
+# Windows dispatch stays intact
+# ---------------------------------------------------------------------------
+
+def test_windows_frame_rect_without_handle_is_none(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ assert ws.window_frame_rect(WindowInfo(title="App")) is None
+
+
+# ---------------------------------------------------------------------------
+# Native per-window capture seam (jarvis.platform.window_capture)
+# ---------------------------------------------------------------------------
+
+def test_grab_window_returns_none_on_windows(monkeypatch):
+ # Windows' native path IS the DPI-pinned rect grab (GDI) — no separate
+ # per-window bitmap; callers keep the rect grabber.
+ from jarvis.platform import window_capture as wc
+
+ monkeypatch.setattr(wc, "detect_platform", lambda: "win32")
+ assert wc.grab_window(1234, {"left": 0, "top": 0,
+ "width": 100, "height": 100}) is None
+
+
+def test_grab_window_macos_degrades_without_frameworks(monkeypatch):
+ from jarvis.platform import window_capture as wc
+
+ monkeypatch.setattr(wc, "detect_platform", lambda: "darwin")
+ monkeypatch.setitem(sys.modules, "ScreenCaptureKit", None)
+ monkeypatch.setitem(sys.modules, "Quartz", None)
+ assert wc.grab_window(7, {"left": 0, "top": 0,
+ "width": 100, "height": 100}) is None
+
+
+def test_grab_window_never_raises(monkeypatch):
+ from jarvis.platform import window_capture as wc
+
+ def boom():
+ raise RuntimeError("platform probe exploded")
+
+ monkeypatch.setattr(wc, "detect_platform", boom)
+ assert wc.grab_window(7, {"left": 0, "top": 0,
+ "width": 100, "height": 100}) is None