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
fix: harden one-shot screen capture privacy
Ruben Lütkeba385d87d5c6
diff --git a/jarvis/core/win32_dpi.py b/jarvis/core/win32_dpi.pyindex 827f2511b9..86c34e540e 100644--- a/jarvis/core/win32_dpi.py+++ b/jarvis/core/win32_dpi.py@@ -14,6 +14,8 @@ from __future__ import annotationsimport loggingimport os+from collections.abc import Iterator+from contextlib import contextmanagerlogger = logging.getLogger(__name__)@@ -28,9 +30,58 @@ _DPI_AWARENESS_SET: bool = False# 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+_DPI_CTX_PER_MONITOR = -3_E_ACCESSDENIED = -2147024891 # 0x80070005 — awareness already set: fine+def _current_awareness_tier(windll) -> str:+ """Return the process DPI tier, with an effective-thread fallback."""+ import ctypes # noqa: PLC0415++ try:+ get_process_awareness = windll.shcore.GetProcessDpiAwareness+ get_process_awareness.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]+ get_process_awareness.restype = ctypes.c_long+ awareness = ctypes.c_int(-1)+ if int(get_process_awareness(None, ctypes.byref(awareness))) == 0:+ if awareness.value == 2:+ return "per_monitor"+ if awareness.value == 1:+ return "system"+ return "none"+ except (OSError, AttributeError, TypeError, ValueError):+ logger.debug("Could not query process DPI awareness", exc_info=True)++ try:+ get_context = windll.user32.GetThreadDpiAwarenessContext+ get_context.argtypes = []+ get_context.restype = ctypes.c_void_p+ context = get_context()+ if not context:+ return "none"++ contexts_equal = windll.user32.AreDpiAwarenessContextsEqual+ contexts_equal.argtypes = [ctypes.c_void_p, ctypes.c_void_p]+ contexts_equal.restype = ctypes.c_int+ if contexts_equal(+ ctypes.c_void_p(context), ctypes.c_void_p(_DPI_CTX_PER_MONITOR_V2)+ ):+ return "per_monitor_v2"++ get_awareness = windll.user32.GetAwarenessFromDpiAwarenessContext+ get_awareness.argtypes = [ctypes.c_void_p]+ get_awareness.restype = ctypes.c_int+ awareness = int(get_awareness(ctypes.c_void_p(context)))+ if awareness == 2:+ return "per_monitor"+ if awareness == 1:+ return "system"+ return "none"+ except (OSError, AttributeError, TypeError, ValueError):+ logger.debug("Could not query effective DPI awareness", exc_info=True)+ return "none"++def _apply_process_awareness(windll) -> str:"""Declare process DPI awareness, most capable tier first.@@ -48,20 +99,30 @@ def _apply_process_awareness(windll) -> str:try:set_ctx = windll.user32.SetProcessDpiAwarenessContext+ set_ctx.argtypes = [ctypes.c_void_p]+ set_ctx.restype = ctypes.c_intif 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):+ # PROCESS_PER_MONITOR_DPI_AWARE = 2.+ set_awareness = windll.shcore.SetProcessDpiAwareness+ set_awareness.argtypes = [ctypes.c_int]+ set_awareness.restype = ctypes.c_long+ res = int(set_awareness(2))+ if res == 0:return "per_monitor"+ if res == _E_ACCESSDENIED:+ return _current_awareness_tier(windll)logger.debug("SetProcessDpiAwareness returned 0x%x", res & 0xFFFFFFFF)except (OSError, AttributeError):logger.debug("SetProcessDpiAwareness unavailable", exc_info=True)try:- if windll.user32.SetProcessDPIAware():+ set_aware = windll.user32.SetProcessDPIAware+ set_aware.argtypes = []+ set_aware.restype = ctypes.c_int+ if set_aware():return "system"except (OSError, AttributeError):logger.warning("Could not set DPI awareness", exc_info=True)@@ -143,3 +204,35 @@ def pin_thread_dpi_per_monitor() -> bool:except (OSError, AttributeError):logger.debug("SetThreadDpiAwarenessContext unavailable", exc_info=True)return False+++@contextmanager+def per_monitor_dpi_context() -> Iterator[None]:+ """Temporarily pin the calling thread to physical per-monitor pixels."""+ if os.name != "nt":+ yield+ return++ previous = None+ set_context = None+ try:+ import ctypes # noqa: PLC0415++ set_context = ctypes.windll.user32.SetThreadDpiAwarenessContext+ set_context.argtypes = [ctypes.c_void_p]+ set_context.restype = ctypes.c_void_p+ for context in (_DPI_CTX_PER_MONITOR_V2, _DPI_CTX_PER_MONITOR):+ previous = set_context(ctypes.c_void_p(context))+ if previous:+ break+ except (OSError, AttributeError):+ logger.debug("SetThreadDpiAwarenessContext unavailable", exc_info=True)++ try:+ yield+ finally:+ if previous and set_context is not None:+ try:+ set_context(ctypes.c_void_p(previous))+ except (OSError, AttributeError):+ logger.debug("Could not restore thread DPI context", exc_info=True)diff --git a/jarvis/cu/indicator/win32.py b/jarvis/cu/indicator/win32.pyindex 05229417c0..5608fbc7fd 100644--- a/jarvis/cu/indicator/win32.py+++ b/jarvis/cu/indicator/win32.py@@ -30,12 +30,24 @@ _WDA_EXCLUDEFROMCAPTURE = 0x00000011CAPTURABLE_ENV = "JARVIS_CU_INDICATOR_CAPTURABLE"+def _configure_user32(user32, ctypes, wintypes) -> None:+ user32.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int]+ user32.GetWindowLongW.restype = ctypes.c_long+ user32.SetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_long]+ user32.SetWindowLongW.restype = ctypes.c_long+ user32.SetWindowDisplayAffinity.argtypes = [wintypes.HWND, wintypes.DWORD]+ user32.SetWindowDisplayAffinity.restype = wintypes.BOOL++def _user32():if os.name != "nt":return Noneimport ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415- return ctypes.windll.user32 # type: ignore[attr-defined]+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]+ _configure_user32(user32, ctypes, wintypes)+ return user32def harden_window(hwnd: int) -> bool:diff --git a/jarvis/platform/window_capture.py b/jarvis/platform/window_capture.pyindex 1ea9b33d74..21ba507fba 100644--- a/jarvis/platform/window_capture.py+++ b/jarvis/platform/window_capture.py@@ -11,12 +11,9 @@ rect in input units.Per platform:-* **Windows** — deliberately ``None``: the DPI-pinned GDI rect grab of the- DWM extended frame bounds IS the native path here (physical virtual-desktop- pixels under PER_MONITOR_AWARE_V2). ``PrintWindow`` would add- occluded-window capture at the cost of per-app quirks (GPU-composited- windows render black) — CU always raises its target first, so the rect- grab sees exactly the window.+* **Windows** — Pillow's HWND capture path captures only the requested+ window, so an overlapping window cannot leak into the result. A framing or+ DPI-size mismatch fails closed to ``None``.* **macOS** — ScreenCaptureKit by CGWindowID (``SCScreenshotManager``,macOS 14+; pyobjc ``[desktop-macos]`` extra): captures the window onwhatever display it sits, at native backing resolution, independent of@@ -36,6 +33,7 @@ frameworks are imported lazily inside the darwin path. Every failure returnsfrom __future__ import annotationsimport logging+import osfrom typing import Anyfrom jarvis.platform import detect_platform@@ -59,6 +57,8 @@ def grab_window("""try:plat = detect_platform()+ if plat == "win32":+ return _grab_window_windows(int(handle), bbox)if plat == "darwin":return _grab_window_macos(int(handle))return None@@ -67,6 +67,89 @@ def grab_window(return None+def _grab_window_windows(+ hwnd: int, bbox: dict[str, int],+) -> tuple[tuple[int, int], bytes] | None:+ """Capture exactly one HWND without desktop-compositing overlap."""+ if os.name != "nt" or not hwnd:+ return None++ from jarvis.core.win32_dpi import per_monitor_dpi_context # noqa: PLC0415++ try:+ from PIL import Image, ImageGrab # noqa: PLC0415+ except ImportError:+ log.debug("Pillow ImageGrab unavailable")+ return None++ expected = (int(bbox.get("width", 0)), int(bbox.get("height", 0)))+ if expected[0] <= 0 or expected[1] <= 0:+ return None+ with per_monitor_dpi_context():+ image = ImageGrab.grab(window=hwnd)+ if tuple(image.size) != expected:+ from jarvis.platform.window_state import ( # noqa: PLC0415+ _window_client_rect_windows,+ _window_rect_windows,+ )++ outer = _window_rect_windows(hwnd)+ client = _window_client_rect_windows(hwnd)+ crop_box = None+ if outer is not None and tuple(image.size) == outer[2:]:+ left = int(bbox.get("left", 0)) - outer[0]+ top = int(bbox.get("top", 0)) - outer[1]+ crop_box = (left, top, left + expected[0], top + expected[1])+ if (+ crop_box[0] < 0+ or crop_box[1] < 0+ or crop_box[2] > image.size[0]+ or crop_box[3] > image.size[1]+ ):+ crop_box = None+ if crop_box is not None:+ cropped = image.crop(crop_box)+ image.close()+ image = cropped+ elif client is not None and tuple(image.size) == client[2:]:+ client_left = client[0] - int(bbox.get("left", 0))+ client_top = client[1] - int(bbox.get("top", 0))+ if (+ client_left < 0+ or client_top < 0+ or client_left + image.size[0] > expected[0]+ or client_top + image.size[1] > expected[1]+ ):+ image.close()+ return None+ canvas = Image.new("RGB", expected, color=(0, 0, 0))+ client_image = image.convert("RGB")+ try:+ canvas.paste(client_image, (client_left, client_top))+ finally:+ if client_image is not image:+ client_image.close()+ image.close()+ image = canvas+ else:+ log.debug(+ "HWND capture size %s does not match frame bounds %s",+ image.size,+ expected,+ )+ image.close()+ return None+ try:+ rgb = image.convert("RGB")+ try:+ return (expected, rgb.tobytes())+ finally:+ if rgb is not image:+ rgb.close()+ finally:+ image.close()++def _grab_window_macos(window_id: int) -> tuple[tuple[int, int], bytes] | None:"""One ScreenCaptureKit screenshot of the window with ``window_id``.diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.pyindex 6e0d87b4d0..c131e73ba3 100644--- a/jarvis/platform/window_state.py+++ b/jarvis/platform/window_state.py@@ -35,6 +35,7 @@ import timefrom dataclasses import dataclassfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.core.win32_dpi import per_monitor_dpi_contextfrom jarvis.platform import detect_platformfrom jarvis.platform.macos_ax import decode_ax_point, decode_ax_sizefrom jarvis.platform.probes import display_present, is_wayland@@ -70,6 +71,92 @@ class WindowInfo:pid: int | None = None+def _configure_window_query_api(user32, ctypes, wintypes) -> None:+ """Bind pointer-sized Win32 window-query signatures."""+ user32.GetForegroundWindow.argtypes = []+ user32.GetForegroundWindow.restype = wintypes.HWND+ user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]+ user32.GetWindowTextLengthW.restype = ctypes.c_int+ user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]+ user32.GetWindowTextW.restype = ctypes.c_int+ user32.GetWindowThreadProcessId.argtypes = [+ wintypes.HWND,+ ctypes.POINTER(wintypes.DWORD),+ ]+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD+ user32.GetWindowRect.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.RECT)]+ user32.GetWindowRect.restype = wintypes.BOOL+ user32.GetClientRect.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.RECT)]+ user32.GetClientRect.restype = wintypes.BOOL+ user32.ClientToScreen.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.POINT)]+ user32.ClientToScreen.restype = wintypes.BOOL+ user32.IsWindowVisible.argtypes = [wintypes.HWND]+ user32.IsWindowVisible.restype = wintypes.BOOL+ user32.IsIconic.argtypes = [wintypes.HWND]+ user32.IsIconic.restype = wintypes.BOOL+ user32.GetSystemMetrics.argtypes = [ctypes.c_int]+ user32.GetSystemMetrics.restype = ctypes.c_int+ user32.GetClassNameW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]+ user32.GetClassNameW.restype = ctypes.c_int+ user32.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int]+ user32.GetWindowLongW.restype = ctypes.c_long+ user32.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]+ user32.ShowWindow.restype = wintypes.BOOL+ user32.SetForegroundWindow.argtypes = [wintypes.HWND]+ user32.SetForegroundWindow.restype = wintypes.BOOL+ user32.SetActiveWindow.argtypes = [wintypes.HWND]+ user32.SetActiveWindow.restype = wintypes.HWND+ user32.BringWindowToTop.argtypes = [wintypes.HWND]+ user32.BringWindowToTop.restype = wintypes.BOOL+ user32.AttachThreadInput.argtypes = [+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.BOOL,+ ]+ user32.AttachThreadInput.restype = wintypes.BOOL+ user32.GetWindowPlacement.argtypes = [wintypes.HWND, ctypes.c_void_p]+ user32.GetWindowPlacement.restype = wintypes.BOOL+ user32.SetWindowPos.argtypes = [+ wintypes.HWND,+ wintypes.HWND,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ wintypes.UINT,+ ]+ user32.SetWindowPos.restype = wintypes.BOOL+++def _rects_intersect(+ first: tuple[int, int, int, int], second: tuple[int, int, int, int],+) -> bool:+ left, top, width, height = first+ other_left, other_top, other_width, other_height = second+ return (+ width > 0+ and height > 0+ and other_width > 0+ and other_height > 0+ and left < other_left + other_width+ and other_left < left + width+ and top < other_top + other_height+ and other_top < top + height+ )+++def _virtual_desktop_rect_windows(user32) -> tuple[int, int, int, int] | None:+ rect = (+ int(user32.GetSystemMetrics(76)),+ int(user32.GetSystemMetrics(77)),+ int(user32.GetSystemMetrics(78)),+ int(user32.GetSystemMetrics(79)),+ )+ if rect[2] <= 0 or rect[3] <= 0:+ return None+ return rect++# ----------------------------------------------------------------------# Windows backend (ctypes) — focus path moved verbatim from switch_window (AD-7)# ----------------------------------------------------------------------@@ -84,15 +171,18 @@ def _find_and_focus_windows(title_contains: str) -> tuple[bool, str]:either the window title or a failure reason."""if os.name != "nt":- raise RuntimeError("Window switch is only available on Windows")+ return False, "Window switch is only available on Windows"- import ctypes- from ctypes import wintypes+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)EnumWindows = user32.EnumWindows- EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)+ EnumWindowsProc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)+ EnumWindows.argtypes = [EnumWindowsProc, wintypes.LPARAM]+ EnumWindows.restype = wintypes.BOOLGetWindowTextW = user32.GetWindowTextWGetWindowTextLengthW = user32.GetWindowTextLengthWIsWindowVisible = user32.IsWindowVisible@@ -157,11 +247,16 @@ def _force_foreground_windows(hwnd: int) -> bool:import-cleanliness, HN-7). Separate from ``_find_and_focus_windows`` so theverbatim ``switch_window`` path (AD-7) stays untouched."""- import ctypes- from ctypes import wintypes+ if os.name != "nt":+ return False+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415user32 = ctypes.windll.user32kernel32 = ctypes.windll.kernel32+ _configure_window_query_api(user32, ctypes, wintypes)+ kernel32.GetCurrentThreadId.argtypes = []+ kernel32.GetCurrentThreadId.restype = wintypes.DWORD_SW_RESTORE = 9get_thread = user32.GetWindowThreadProcessId@@ -203,12 +298,17 @@ def _force_foreground_windows(hwnd: int) -> bool:def _list_windows_windows() -> list[WindowInfo]:"""All identifiable visible top-level windows, including untitled ones."""- import ctypes- from ctypes import wintypes+ if os.name != "nt":+ return []+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)EnumWindows = user32.EnumWindows- EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)+ EnumWindowsProc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)+ EnumWindows.argtypes = [EnumWindowsProc, wintypes.LPARAM]+ EnumWindows.restype = wintypes.BOOLGetWindowTextW = user32.GetWindowTextWGetWindowTextLengthW = user32.GetWindowTextLengthWIsWindowVisible = user32.IsWindowVisible@@ -247,16 +347,21 @@ def _list_windows_windows() -> list[WindowInfo]:def _foreground_title_windows() -> str:- import ctypes+ if os.name != "nt":+ return ""+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415user32 = ctypes.windll.user32- hwnd = user32.GetForegroundWindow()- if not hwnd:- return ""- length = user32.GetWindowTextLengthW(hwnd)- buf = ctypes.create_unicode_buffer(length + 1)- user32.GetWindowTextW(hwnd, buf, length + 1)- return buf.value or ""+ _configure_window_query_api(user32, ctypes, wintypes)+ with per_monitor_dpi_context():+ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return ""+ length = user32.GetWindowTextLengthW(hwnd)+ buf = ctypes.create_unicode_buffer(length + 1)+ user32.GetWindowTextW(hwnd, buf, length + 1)+ return buf.value or ""# ----------------------------------------------------------------------@@ -959,21 +1064,25 @@ def foreground_window() -> WindowInfo | None:def _foreground_window_windows() -> WindowInfo | None:+ if os.name != "nt":+ return Noneimport ctypes # noqa: PLC0415from ctypes import wintypes # noqa: PLC0415user32 = ctypes.windll.user32- hwnd = user32.GetForegroundWindow()- if not hwnd:- return None- length = int(user32.GetWindowTextLengthW(hwnd))- buf = ctypes.create_unicode_buffer(length + 1)- user32.GetWindowTextW(hwnd, buf, length + 1)- pid = wintypes.DWORD()- user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))- return WindowInfo(- title=buf.value or "", handle=int(hwnd), pid=int(pid.value) or None- )+ _configure_window_query_api(user32, ctypes, wintypes)+ with per_monitor_dpi_context():+ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return None+ length = int(user32.GetWindowTextLengthW(hwnd))+ buf = ctypes.create_unicode_buffer(length + 1)+ user32.GetWindowTextW(hwnd, buf, length + 1)+ pid = wintypes.DWORD()+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))+ return WindowInfo(+ title=buf.value or "", handle=int(hwnd), pid=int(pid.value) or None+ )def _quartz_window_list(*, on_screen_only: bool = True) -> list:@@ -1144,13 +1253,44 @@ def move_window_to_primary(def _window_rect_windows(hwnd: int) -> tuple[int, int, int, int] | None:+ if os.name != "nt":+ return Noneimport ctypes # noqa: PLC0415from ctypes import wintypes # noqa: PLC0415- rect = wintypes.RECT()- if not ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)):+ user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)+ with per_monitor_dpi_context():+ rect = wintypes.RECT()+ if not user32.GetWindowRect(hwnd, ctypes.byref(rect)):+ return None+ result = (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top)+ virtual = _virtual_desktop_rect_windows(user32)+ if virtual is not None and not _rects_intersect(result, virtual):+ return None+ return result+++def _window_client_rect_windows(hwnd: int) -> tuple[int, int, int, int] | None:+ if os.name != "nt":return None- return (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top)+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)+ with per_monitor_dpi_context():+ rect = wintypes.RECT()+ origin = wintypes.POINT()+ if not user32.GetClientRect(hwnd, ctypes.byref(rect)):+ return None+ if not user32.ClientToScreen(hwnd, ctypes.byref(origin)):+ return None+ width = rect.right - rect.left+ height = rect.bottom - rect.top+ if width <= 0 or height <= 0:+ return None+ return (int(origin.x), int(origin.y), width, height)def _move_to_primary_windows(win: WindowInfo, primary: dict) -> tuple[bool, str]:@@ -1161,6 +1301,7 @@ def _move_to_primary_windows(win: WindowInfo, primary: dict) -> tuple[bool, str]from ctypes import wintypes # noqa: PLC0415user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)hwnd = int(win.handle)class _WINDOWPLACEMENT(ctypes.Structure):@@ -1208,10 +1349,15 @@ _SHELL_WINDOW_CLASSES = frozenset({def _window_class_windows(hwnd: int) -> str:+ if os.name != "nt":+ return ""import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415+ user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)buf = ctypes.create_unicode_buffer(256)- if not ctypes.windll.user32.GetClassNameW(hwnd, buf, 256):+ if not user32.GetClassNameW(hwnd, buf, 256):return ""return buf.value or ""@@ -1265,26 +1411,40 @@ def window_frame_rect(win: WindowInfo) -> tuple[int, int, int, int] | None:from ctypes import wintypes # noqa: PLC0415hwnd = int(win.handle)- rect = wintypes.RECT()- _DWMWA_EXTENDED_FRAME_BOUNDS = 9- try:- res = ctypes.windll.dwmapi.DwmGetWindowAttribute(- wintypes.HWND(hwnd),- ctypes.wintypes.DWORD(_DWMWA_EXTENDED_FRAME_BOUNDS),- ctypes.byref(rect),- ctypes.sizeof(rect),+ user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)+ with per_monitor_dpi_context():+ rect = wintypes.RECT()+ _DWMWA_EXTENDED_FRAME_BOUNDS = 9+ try:+ get_attribute = ctypes.windll.dwmapi.DwmGetWindowAttribute+ get_attribute.argtypes = [+ wintypes.HWND,+ wintypes.DWORD,+ ctypes.c_void_p,+ wintypes.DWORD,+ ]+ get_attribute.restype = ctypes.c_long+ res = get_attribute(+ wintypes.HWND(hwnd),+ wintypes.DWORD(_DWMWA_EXTENDED_FRAME_BOUNDS),+ ctypes.byref(rect),+ ctypes.sizeof(rect),+ )+ except (OSError, AttributeError):+ res = 1 # dwmapi missing — fall through to GetWindowRect+ if res != 0 and not user32.GetWindowRect(hwnd, ctypes.byref(rect)):+ return None+ result = (+ rect.left,+ rect.top,+ rect.right - rect.left,+ rect.bottom - rect.top,)- except (OSError, AttributeError):- res = 1 # dwmapi missing — fall through to GetWindowRect- if res != 0 and not ctypes.windll.user32.GetWindowRect(- hwnd, ctypes.byref(rect)- ):- return None- width = rect.right - rect.left- height = rect.bottom - rect.top- if width <= 0 or height <= 0:- return None- return (rect.left, rect.top, width, height)+ virtual = _virtual_desktop_rect_windows(user32)+ if virtual is not None and not _rects_intersect(result, virtual):+ return None+ return resultexcept Exception: # noqa: BLE001log.debug("window_frame_rect failed", exc_info=True)return None@@ -1457,9 +1617,9 @@ def window_is_maximized(win: WindowInfo) -> bool | None:_SW_SHOWMAXIMIZED = 3wp = _WINDOWPLACEMENT()wp.length = ctypes.sizeof(_WINDOWPLACEMENT)- if not ctypes.windll.user32.GetWindowPlacement(- int(win.handle), ctypes.byref(wp)- ):+ user32 = ctypes.windll.user32+ _configure_window_query_api(user32, ctypes, wintypes)+ if not user32.GetWindowPlacement(int(win.handle), ctypes.byref(wp)):return Nonereturn wp.showCmd == _SW_SHOWMAXIMIZEDexcept Exception: # noqa: BLE001@@ -1529,7 +1689,9 @@ def maximize_window(win: WindowInfo) -> tuple[bool, str]:hwnd = int(win.handle)_GWL_STYLE, _WS_MAXIMIZEBOX = -16, 0x00010000_SW_MAXIMIZE = 3- user32.GetWindowLongW.restype = ctypes.c_long+ from ctypes import wintypes # noqa: PLC0415++ _configure_window_query_api(user32, ctypes, wintypes)style = int(user32.GetWindowLongW(hwnd, _GWL_STYLE))if not style & _WS_MAXIMIZEBOX:return False, "window has no maximize box (fixed-size dialog)"diff --git a/jarvis/screen_context/ports.py b/jarvis/screen_context/ports.pyindex f301f23173..c5decb7f61 100644--- a/jarvis/screen_context/ports.py+++ b/jarvis/screen_context/ports.py@@ -26,6 +26,7 @@ the first capture, not at boot.from __future__ import annotationsimport logging+import osfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass@@ -383,11 +384,9 @@ class SurfaceCapturer(Protocol):class NativeSurfaceCapturer:"""Native per-window capture where the OS offers it, rect grab otherwise.- macOS ScreenCaptureKit can capture a window wherever it sits, at backing- resolution, so a window-scoped request uses it. Everywhere else the- DPI-pinned rect grab of the raised window IS the native path (see- ``jarvis.platform.window_capture`` for why ``PrintWindow`` is not used on- Windows), so both target kinds funnel into ``mss``.+ Window-scoped requests use a native window-only backend where available.+ On Windows, failure of that backend is a privacy refusal: composing the+ same rectangle from the desktop could photograph an overlapping app."""name = "native-capture"@@ -403,6 +402,7 @@ class NativeSurfaceCapturer:)if window_handle is not None:+ native = Nonetry:from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415indicator_suppressed,@@ -416,8 +416,16 @@ class NativeSurfaceCapturer:)if native is not None:return native- except Exception: # noqa: BLE001 — fall through to the rect grab- log.debug("native window capture failed; using rect grab", exc_info=True)+ except Exception: # noqa: BLE001 — platform policy below decides fallback+ log.debug("native window capture failed", exc_info=True)+ if os.name == "nt":+ raise CaptureUnavailable(+ "The focused Windows window could not be captured safely. "+ "A desktop-rectangle fallback was refused because another "+ "window could overlap it. Bring the window to the foreground and "+ "retry; some protected or GPU-rendered windows do not support "+ "window-only capture."+ )try:if _is_wayland():diff --git a/jarvis/screen_context/redaction.py b/jarvis/screen_context/redaction.pyindex c5dba2fbe9..10d40488ed 100644--- a/jarvis/screen_context/redaction.py+++ b/jarvis/screen_context/redaction.py@@ -44,6 +44,13 @@ from jarvis.screen_context.ports import Rectlog = logging.getLogger(__name__)+_UNSAFE_CUSTOM_REGEX_RE = re.compile(+ r"\\[1-9]|\(\?P=|"+ r"\((?:\\.|[^()])*(?:[+*]|\{\d*,?\d*\})(?:\\.|[^()])*\)"+ r"(?:[+*]|\{\d*,?\d*\})|"+ r"\((?:\\.|[^()])*\|(?:\\.|[^()])*\)(?:[+*]|\{\d*,?\d*\})"+)+@dataclass(frozen=True, slots=True)class SensitivePattern:@@ -57,13 +64,43 @@ class SensitivePattern:return f"[redacted:{self.label}]"-def _compile(label: str, source: str) -> SensitivePattern | None:+def validate_pattern_source(source: str) -> str | None:+ """Return a validation error for custom regexes that can stall a turn."""+ if len(source) > 500:+ return "the expression exceeds 500 characters"+ if _UNSAFE_CUSTOM_REGEX_RE.search(source):+ return (+ "nested repetition, repeated alternation, and backreferences are "+ "not allowed in Screen Context patterns"+ )+ try:+ re.compile(source, re.IGNORECASE)+ except re.error as exc:+ return str(exc)+ return None+++def _compile(+ label: str,+ source: str,+ *,+ validate_custom: bool = False,+) -> SensitivePattern | None:"""Compile one configured pattern; a bad regex is skipped, never fatal.A user-supplied pattern that fails to compile must not brick the wholefeature — but it must also not silently reduce protection, so it is loggedat WARNING with the label (AP-30)."""+ validation_error = validate_pattern_source(source) if validate_custom else None+ if validation_error is not None:+ log.warning(+ "screen_context: sensitive pattern %r was skipped because %s. "+ "Content matching it will NOT be redacted.",+ label,+ validation_error,+ )+ return Nonetry:return SensitivePattern(label=label, pattern=re.compile(source, re.IGNORECASE))except re.error as exc:@@ -121,7 +158,11 @@ def build_patterns(extra: Iterable[str] = (), *, include_defaults: bool = True):label, _, source = raw.partition(":")if not source:label, source = "custom", raw- compiled = _compile(label.strip() or "custom", source.strip())+ compiled = _compile(+ label.strip() or "custom",+ source.strip(),+ validate_custom=True,+ )if compiled is not None:patterns.append(compiled)return tuple(patterns)@@ -254,6 +295,35 @@ def apply_image_redactions(image: Any, regions) -> tuple[Any, tuple[RedactionHitreturn image, tuple(hits)+def local_text_regions_to_redact(+ regions: Iterable[Any],+ *,+ patterns: Iterable[SensitivePattern],+) -> tuple[tuple[Rect, RedactionRule, str], ...]:+ """Image-local OCR line rectangles whose text matches a privacy rule."""+ pattern_list = tuple(patterns)+ out: list[tuple[Rect, RedactionRule, str]] = []+ for region in regions:+ text = str(getattr(region, "text", "") or "")+ bounds = getattr(region, "bounds", None)+ if not text or not bounds or len(bounds) != 4:+ continue+ left, top, width, height = (int(value) for value in bounds)+ if width <= 0 or height <= 0:+ continue+ for pattern in pattern_list:+ if pattern.pattern.search(text):+ out.append(+ (+ (left, top, width, height),+ RedactionRule.SENSITIVE_PATTERN,+ pattern.label,+ )+ )+ break+ return tuple(out)++# --------------------------------------------------------------------------# Layer 3 — text# --------------------------------------------------------------------------@@ -297,7 +367,9 @@ __all__ = ["blocked_by_denylist","build_patterns","default_patterns",+ "local_text_regions_to_redact","merge_reports","regions_to_redact","scrub_text",+ "validate_pattern_source",]diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.pyindex 7810a7996d..b96d5b9419 100644--- a/jarvis/screen_context/service.py+++ b/jarvis/screen_context/service.py@@ -6,11 +6,10 @@ capture, grabs pixels exactly once, redacts them, and hands back a short-livedhandle. Every piece of platform knowledge lives below it in ``ports.py``, sothis module is fully unit-testable with fakes and needs no display.-**Single capture, by construction.** There is no loop, no timer, no cached-frame, and no "refresh". :meth:`ScreenContextService.capture` grabs once and-returns; the only way to get another capture is another explicit call. That is-not a policy the code merely follows — there is no code path here that could-capture twice.+**Single capture, by construction.** There is no capture loop, cached frame, or+"refresh". :meth:`ScreenContextService.capture` grabs once and returns; the+only way to get another capture is another explicit call. The only timer is a+destructive TTL callback for an unconsumed handle.**Retention.** A finished :class:`~jarvis.screen_context.models.ScreenContext`lives in a :class:`_Handle` in memory, keyed by an opaque id, and is removed on@@ -28,7 +27,9 @@ import asyncioimport contextlibimport ioimport logging+import mathimport secrets+import threadingimport timefrom dataclasses import dataclassfrom typing import Any, Literal@@ -74,6 +75,7 @@ _MIN_JPEG_QUALITY = 50#: degradation is recorded rather than the capture being abandoned._ANNOUNCE_TIMEOUT_S = 1.5_INDICATOR_DWELL_S = 0.12+_UI_TEXT_TIMEOUT_S = 2.0CaptureStatus = Literal["captured", "clarify", "refused", "not_requested"]@@ -180,8 +182,12 @@ class ScreenContextService:self._capturer = capturerself._ui_text_reader = ui_text_readerself._permission_probe = permission_probe or capture_permission_error- self._clock = clock or time.time_ns+ self._clock = clock or time.monotonic_ns+ self._wall_clock = time.time_nsself._handles: dict[str, _Handle] = {}+ self._expiry_timers: dict[str, asyncio.TimerHandle | threading.Timer] = {}+ self._handle_lock = threading.RLock()+ self._closed = Falseself._patterns = redaction.build_patterns(self._settings.extra_patterns,include_defaults=self._settings.include_default_patterns,@@ -316,6 +322,14 @@ class ScreenContextService:) -> CaptureOutcome:"""Take exactly one capture. Assumes intent is already established."""verdict = verdict or IntentVerdict(intent=VisualIntent.SCREEN)+ if self._closed:+ return CaptureOutcome(+ status="refused",+ verdict=verdict,+ reason_kind="technical",+ reason_code="capture_backend_unavailable",+ message="Screen Context settings changed before capture could start.",+ )permission_issue = await asyncio.to_thread(self._permission_probe)if permission_issue:@@ -568,7 +582,30 @@ class ScreenContextService:expected_window_handle=window_handle,)- handle_id = self.store(context)+ if self._closed:+ return CaptureOutcome(+ status="refused",+ verdict=verdict,+ reason_kind="technical",+ reason_code="capture_backend_unavailable",+ message=(+ "Screen Context settings changed during capture, so the "+ "image was discarded. Ask again to use the new settings."+ ),+ )+ try:+ handle_id = self.store(context)+ except RuntimeError:+ return CaptureOutcome(+ status="refused",+ verdict=verdict,+ reason_kind="technical",+ reason_code="capture_backend_unavailable",+ message=(+ "Screen Context settings changed during capture, so the "+ "image was discarded. Ask again to use the new settings."+ ),+ )await self._publish_completed(context, trace_id=event_trace_id)log.info("screen_context: %s", context.describe())return CaptureOutcome(@@ -640,17 +677,39 @@ class ScreenContextService:Degradation(code=DegradationCode.NO_UI_TEXT, message=access_error))else:- text, text_source, nodes, text_degradations = await uitext.read_ui_text(- self.ui_text_reader,- target_rect=target.bbox,- max_chars=self._settings.max_text_chars,- keep_unbounded_nodes=target.kind is TargetKind.WINDOW,- window_title_filter=(- target.window.title if target.kind is TargetKind.WINDOW else None- ),- expected_pid=target.window.pid,- expected_window_title=target.window.title,- )+ try:+ text, text_source, nodes, text_degradations = await asyncio.wait_for(+ uitext.read_ui_text(+ self.ui_text_reader,+ target_rect=target.bbox,+ max_chars=self._settings.max_text_chars,+ keep_unbounded_nodes=target.kind is TargetKind.WINDOW,+ window_title_filter=(+ target.window.title+ if target.kind is TargetKind.WINDOW+ else None+ ),+ expected_pid=target.window.pid,+ expected_window_title=target.window.title,+ ),+ timeout=_UI_TEXT_TIMEOUT_S,+ )+ except TimeoutError:+ text, text_source, nodes, text_degradations = "", "none", (), ()+ degradations.append(+ Degradation(+ code=DegradationCode.NO_UI_TEXT,+ message=(+ "On-screen text took too long to read, so this turn "+ "continued with the image only."+ ),+ )+ )+ log.warning(+ "screen_context: accessibility read exceeded %.1fs; "+ "continuing image-only",+ _UI_TEXT_TIMEOUT_S,+ )degradations.extend(text_degradations)if nodes and not await asyncio.to_thread(self._foreground_still_matches,@@ -683,22 +742,44 @@ class ScreenContextService:# -- text scrubbing --------------------------------------------------scrubbed_text, text_hits = redaction.scrub_text(text, self._patterns)- # -- OCR, only to fill a genuine gap ---------------------------------- if self._settings.ocr_enabled and uitext.text_is_sparse(scrubbed_text):- ocr_text, ocr_degradation = await asyncio.to_thread(- uitext.ocr_supplement, image- )- if ocr_degradation is not None:- degradations.append(ocr_degradation)- elif ocr_text:- ocr_scrubbed, ocr_hits = redaction.scrub_text(ocr_text, self._patterns)- scrubbed_text = (- f"{scrubbed_text}\n{ocr_scrubbed}".strip()- if scrubbed_text- else ocr_scrubbed+ # -- OCR -------------------------------------------------------------+ # When enabled, OCR always runs once so matches can be burned out of+ # pixels even when accessibility already returned enough model text.+ # OCR text itself supplements only genuinely sparse accessibility.+ ocr_region_hits = ()+ if self._settings.ocr_enabled:+ ocr_result = await asyncio.to_thread(+ uitext.ocr_supplement_with_regions,+ image,+ )+ if ocr_result.degradation is not None:+ degradations.append(ocr_result.degradation)+ else:+ ocr_regions = redaction.local_text_regions_to_redact(+ ocr_result.regions,+ patterns=self._patterns,)- text_hits = text_hits + ocr_hits- text_source = "ocr" if text_source == "none" else "accessibility+ocr"+ image, ocr_region_hits = redaction.apply_image_redactions(+ image,+ ocr_regions,+ )+ if ocr_result.text and uitext.text_is_sparse(+ scrubbed_text,+ image_size=raw_size,+ ):+ ocr_scrubbed, ocr_hits = redaction.scrub_text(+ ocr_result.text,+ self._patterns,+ )+ scrubbed_text = (+ f"{scrubbed_text}\n{ocr_scrubbed}".strip()+ if scrubbed_text+ else ocr_scrubbed+ )+ text_hits = text_hits + ocr_hits+ text_source = (+ "ocr" if text_source == "none" else "accessibility+ocr"+ )image_bytes, encoded_size = _encode(image)@@ -709,9 +790,13 @@ class ScreenContextService:target=target,ui_text=scrubbed_text,ui_text_source=text_source,- redactions=redaction.merge_reports(region_hits, text_hits),+ redactions=redaction.merge_reports(+ region_hits,+ ocr_region_hits,+ text_hits,+ ),degradations=tuple(degradations),- captured_at_ns=self._clock(),+ captured_at_ns=self._wall_clock(),)def _foreground_still_matches(@@ -745,13 +830,20 @@ class ScreenContextService:def store(self, context: ScreenContext) -> str:"""Park a context behind an opaque, single-use id."""- self.sweep()- handle_id = secrets.token_urlsafe(12)- self._handles[handle_id] = _Handle(- context=context,- expires_at_ns=self._clock() + int(self._settings.ttl_s * 1_000_000_000),- )- return handle_id+ with self._handle_lock:+ if self._closed:+ raise RuntimeError("Screen Context service is closed")+ self.sweep()+ handle_id = secrets.token_urlsafe(12)+ expires_at_ns = self._clock() + int(+ self._settings.ttl_s * 1_000_000_000+ )+ self._handles[handle_id] = _Handle(+ context=context,+ expires_at_ns=expires_at_ns,+ )+ self._schedule_expiry(handle_id, expires_at_ns)+ return handle_iddef consume(self, handle_id: str) -> ScreenContext | None:"""Take a context out. A second call for the same id gets ``None``.@@ -760,36 +852,117 @@ class ScreenContextService:hold an id and re-fetch the picture later, and nothing has to rememberto clean up."""- self.sweep()- handle = self._handles.pop(handle_id, None)- return handle.context if handle is not None else None+ with self._handle_lock:+ self.sweep()+ handle = self._handles.pop(handle_id, None)+ self._cancel_expiry(handle_id)+ return handle.context if handle is not None else Nonedef peek(self, handle_id: str) -> ScreenContext | None:"""Metadata read WITHOUT consuming — used by the receipt endpoint."""- self.sweep()- handle = self._handles.get(handle_id)- return handle.context if handle is not None else None+ with self._handle_lock:+ self.sweep()+ handle = self._handles.get(handle_id)+ return handle.context if handle is not None else None++ def discard(self, handle_id: str) -> bool:+ """Remove one held capture without returning its pixels."""+ with self._handle_lock:+ removed = self._handles.pop(handle_id, None) is not None+ self._cancel_expiry(handle_id)+ return removeddef sweep(self) -> int:"""Drop expired handles. Returns how many were dropped."""- now = self._clock()- expired = [k for k, h in self._handles.items() if h.expires_at_ns <= now]- for key in expired:- self._handles.pop(key, None)+ with self._handle_lock:+ now = self._clock()+ expired = [+ key+ for key, handle in self._handles.items()+ if handle.expires_at_ns <= now+ ]+ for key in expired:+ self._handles.pop(key, None)+ self._cancel_expiry(key)if expired:log.debug("screen_context: dropped %d expired capture(s)", len(expired))return len(expired)+ def _schedule_expiry(+ self,+ handle_id: str,+ expires_at_ns: int,+ *,+ delay_s: float | None = None,+ ) -> None:+ """Own the TTL lifecycle instead of waiting for another API call."""+ delay_s = max(+ 0.0,+ self._settings.ttl_s if delay_s is None else delay_s,+ )+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ timer = threading.Timer(+ delay_s,+ self._expire_handle,+ args=(handle_id, expires_at_ns),+ )+ timer.daemon = True+ self._expiry_timers[handle_id] = timer+ timer.start()+ else:+ self._expiry_timers[handle_id] = loop.call_later(+ delay_s,+ self._expire_handle,+ handle_id,+ expires_at_ns,+ )++ def _expire_handle(self, handle_id: str, expires_at_ns: int) -> None:+ with self._handle_lock:+ handle = self._handles.get(handle_id)+ if handle is None or handle.expires_at_ns != expires_at_ns:+ return+ if handle.expires_at_ns > self._clock():+ # A fake or adjusted clock has not reached the deadline yet.+ remaining_s = (handle.expires_at_ns - self._clock()) / 1_000_000_000+ self._schedule_expiry(+ handle_id,+ expires_at_ns,+ delay_s=remaining_s,+ )+ return+ self._handles.pop(handle_id, None)+ self._expiry_timers.pop(handle_id, None)+ log.debug("screen_context: expired capture %s", handle_id)++ def _cancel_expiry(self, handle_id: str) -> None:+ timer = self._expiry_timers.pop(handle_id, None)+ if timer is not None:+ timer.cancel()+def discard_all(self) -> int:"""Drop every held capture immediately (the panic button)."""- count = len(self._handles)- self._handles.clear()- return count+ with self._handle_lock:+ count = len(self._handles)+ self._handles.clear()+ for timer in self._expiry_timers.values():+ timer.cancel()+ self._expiry_timers.clear()+ return count++ def close(self) -> int:+ """Reject in-flight stores and remove every pixel held by this instance."""+ with self._handle_lock:+ self._closed = True+ return self.discard_all()@propertydef held_count(self) -> int:- self.sweep()- return len(self._handles)+ with self._handle_lock:+ self.sweep()+ return len(self._handles)# ---- bus -------------------------------------------------------------@@ -936,9 +1109,23 @@ def _encode(image: Any) -> tuple[bytes, tuple[int, int]]:buffer = io.BytesIO()image.save(buffer, format="JPEG", quality=quality, optimize=True)data = buffer.getvalue()- if len(data) <= _MAX_IMAGE_BYTES or quality <= _MIN_JPEG_QUALITY:+ if len(data) <= _MAX_IMAGE_BYTES:+ return data, image.size+ if quality > _MIN_JPEG_QUALITY:+ quality = max(_MIN_JPEG_QUALITY, quality - 10)+ continue++ # High-entropy frames remain large even at the minimum useful JPEG+ # quality. Continue shrinking until the advertised byte ceiling is a+ # fact, not a best effort.+ shrink = min(0.9, math.sqrt(_MAX_IMAGE_BYTES / len(data)) * 0.95)+ new_size = (+ max(1, int(image.size[0] * shrink)),+ max(1, int(image.size[1] * shrink)),+ )+ if new_size == image.size:return data, image.size- quality -= 10+ image = image.resize(new_size, resample=Image.Resampling.LANCZOS)def _rects_intersect_or_unknown(diff --git a/jarvis/screen_context/targeting.py b/jarvis/screen_context/targeting.pyindex 5d06b89923..9876ec3da2 100644--- a/jarvis/screen_context/targeting.py+++ b/jarvis/screen_context/targeting.py@@ -122,11 +122,29 @@ def _monitor_name(monitor: dict, monitors: list[dict]) -> str:return "?"-def _window_rect_is_usable(rect: Rect | None) -> bool:+def _window_rect_is_usable(rect: Rect | None, monitors: list[dict]) -> bool:if rect is None:return False- _left, _top, width, height = rect- return width >= _MIN_WINDOW_EXTENT_PX and height >= _MIN_WINDOW_EXTENT_PX+ left, top, width, height = rect+ if width < _MIN_WINDOW_EXTENT_PX or height < _MIN_WINDOW_EXTENT_PX:+ return False+ physical = monitors[1:] if len(monitors) > 1 else monitors+ for monitor in physical:+ monitor_left, monitor_top, monitor_width, monitor_height = _rect_of(monitor)+ visible_width = min(left + width, monitor_left + monitor_width) - max(+ left,+ monitor_left,+ )+ visible_height = min(top + height, monitor_top + monitor_height) - max(+ top,+ monitor_top,+ )+ if (+ visible_width >= _MIN_WINDOW_EXTENT_PX+ and visible_height >= _MIN_WINDOW_EXTENT_PX+ ):+ return True+ return Falsedef resolve_target(@@ -165,7 +183,7 @@ def resolve_target(# ---- Window scope: only when the user actually scoped it there --------if intent is VisualIntent.WINDOW:- if _window_rect_is_usable(facts.frame_rect):+ if _window_rect_is_usable(facts.frame_rect, monitors):assert facts.frame_rect is not None # narrowed by the check abovereturn (CaptureTarget(diff --git a/jarvis/screen_context/turn.py b/jarvis/screen_context/turn.pyindex a4af12cccc..50306a07bd 100644--- a/jarvis/screen_context/turn.py+++ b/jarvis/screen_context/turn.py@@ -86,7 +86,7 @@ def reset_service() -> None:"""global _serviceif _service is not None:- _service.discard_all()+ _service.close()_service = Nonediff --git a/jarvis/screen_context/uitext.py b/jarvis/screen_context/uitext.pyindex a7e0b7ad73..f52cc598a8 100644--- a/jarvis/screen_context/uitext.py+++ b/jarvis/screen_context/uitext.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport loggingfrom collections.abc import Iterable+from dataclasses import dataclassfrom typing import Anyfrom jarvis.screen_context.models import Degradation, DegradationCode@@ -209,9 +210,106 @@ async def read_ui_text(# ---------------------------------------------------------------------------def text_is_sparse(text: str) -> bool:- """Whether the accessibility result is thin enough to warrant OCR."""- return len(text.strip()) < _SPARSE_TEXT_THRESHOLD+def text_is_sparse(+ text: str,+ *,+ image_size: tuple[int, int] | None = None,+) -> bool:+ """Whether accessibility text is too thin for the captured surface."""+ threshold = _SPARSE_TEXT_THRESHOLD+ if image_size is not None:+ width, height = image_size+ threshold = min(256, max(threshold, int(width * height / 25_000)))+ return len(text.strip()) < threshold+++@dataclass(frozen=True, slots=True)+class OcrTextRegion:+ """One OCR line and its image-local bounding rectangle."""++ text: str+ bounds: tuple[int, int, int, int]+++@dataclass(frozen=True, slots=True)+class OcrSupplement:+ """OCR text plus the geometry needed to burn secrets out of pixels."""++ text: str = ""+ regions: tuple[OcrTextRegion, ...] = ()+ degradation: Degradation | None = None+++def _ocr_unavailable(message: str) -> OcrSupplement:+ return OcrSupplement(+ degradation=Degradation(+ code=DegradationCode.OCR_UNAVAILABLE,+ message=message,+ )+ )+++def ocr_supplement_with_regions(image: Any) -> OcrSupplement:+ """Run OCR once and retain line boxes for deterministic pixel redaction."""+ try:+ import pytesseract # noqa: PLC0415+ except ImportError:+ log.info(+ "screen_context: OCR is enabled but no OCR engine is installed; "+ "OCR-based pixel redaction was unavailable."+ )+ return _ocr_unavailable(+ "Text recognition is switched on but no OCR engine is installed, "+ "so OCR-based pixel redaction was unavailable."+ )++ try:+ output = getattr(getattr(pytesseract, "Output", None), "DICT", "dict")+ data = pytesseract.image_to_data(image, output_type=output)+ texts = list(data.get("text", ()))+ grouped: dict[tuple[int, int, int], list[tuple[str, int, int, int, int]]] = {}+ for index, raw_text in enumerate(texts):+ word = " ".join(str(raw_text or "").split())+ if not word:+ continue+ try:+ left = int(data["left"][index])+ top = int(data["top"][index])+ width = int(data["width"][index])+ height = int(data["height"][index])+ key = (+ int(data.get("block_num", list(range(len(texts))))[index]),+ int(data.get("par_num", [0] * len(texts))[index]),+ int(data.get("line_num", list(range(len(texts))))[index]),+ )+ except (IndexError, KeyError, TypeError, ValueError):+ continue+ if width <= 0 or height <= 0:+ continue+ grouped.setdefault(key, []).append((word, left, top, width, height))++ regions: list[OcrTextRegion] = []+ for words in grouped.values():+ left = min(word[1] for word in words)+ top = min(word[2] for word in words)+ right = max(word[1] + word[3] for word in words)+ bottom = max(word[2] + word[4] for word in words)+ regions.append(+ OcrTextRegion(+ text=" ".join(word[0] for word in words),+ bounds=(left, top, right - left, bottom - top),+ )+ )+ return OcrSupplement(+ text="\n".join(region.text for region in regions),+ regions=tuple(regions),+ )+ except Exception as exc: # noqa: BLE001 - optional binary/backend failures+ log.debug("OCR failed", exc_info=True)+ return _ocr_unavailable(+ f"Text recognition could not run ({exc}), so OCR-based pixel "+ "redaction was unavailable."+ )def ocr_supplement(image: Any) -> tuple[str, Degradation | None]:@@ -259,9 +357,12 @@ def ocr_supplement(image: Any) -> tuple[str, Degradation | None]:__all__ = [+ "OcrSupplement",+ "OcrTextRegion","aggregate_text","nodes_in_rect","ocr_supplement",+ "ocr_supplement_with_regions","read_ui_text","text_is_sparse",]diff --git a/jarvis/vision/screenshot.py b/jarvis/vision/screenshot.pyindex 41b0da9ec5..38e3cbfdf8 100644--- a/jarvis/vision/screenshot.py+++ b/jarvis/vision/screenshot.py@@ -25,11 +25,18 @@ import hashlibimport ioimport loggingimport time+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Literalfrom uuid import uuid4from jarvis.core.protocols import CancelToken, Observation+from jarvis.core.win32_dpi import (+ ensure_dpi_awareness as _ensure_dpi_awareness,+)+from jarvis.core.win32_dpi import (+ per_monitor_dpi_context,+)logger = logging.getLogger(__name__)@@ -84,8 +91,6 @@ def warn_if_screen_recording_denied() -> bool:# without changes.# ----------------------------------------------------------------------------from jarvis.core.win32_dpi import ensure_dpi_awareness as _ensure_dpi_awareness # noqa: E402-# ---------------------------------------------------------------------------# ScreenshotSource# ---------------------------------------------------------------------------@@ -93,6 +98,12 @@ from jarvis.core.win32_dpi import ensure_dpi_awareness as _ensure_dpi_awarenessMonitorStrategy = Literal["foreground", "primary", "all"]+@dataclass(frozen=True, slots=True)+class _CapturedImage:+ image_bytes: bytes+ monitor_geom: tuple[int, int, int, int]++def cu_capture_strategy(monitor_policy: str) -> MonitorStrategy:"""Map the ``[computer_use].monitor`` policy to the screenshot CAPTUREstrategy (Problem 1, 2026-06-28).@@ -261,7 +272,7 @@ def _mss_grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:"""Default grabber: capture an arbitrary screen rectangle via mss."""import mss # type: ignore[import-not-found] # noqa: PLC0415- with mss.mss() as sct:+ with per_monitor_dpi_context(), mss.mss() as sct:raw = sct.grab(bbox)return (tuple(raw.size), raw.rgb)@@ -371,13 +382,14 @@ class ScreenshotSource:raise RuntimeError(f"cancelled: {cancel_token.reason}")# Screenshot is synchronous — thread pool because of blocking GDI calls.- image_bytes = await asyncio.to_thread(self._capture_image)+ captured = await asyncio.to_thread(self._capture_image)# _capture_image returns None on a transient BitBlt / GDI error.# Propagate None upward so the engine/context_provider can skip the# frame gracefully without a traceback.- if image_bytes is None:+ if captured is None:return None+ image_bytes = captured.image_bytesif cancel_token is not None and cancel_token.is_cancelled():raise RuntimeError(f"cancelled: {cancel_token.reason}")@@ -412,7 +424,7 @@ class ScreenshotSource:pruning_stats={"nodes_before": 0, "nodes_after": 0, "depth_used": 0},# Thread the EXACT captured monitor so clicks map back to THIS screen# (mixed-DPI / multi-monitor consistency, live bug 2026-06-28).- monitor_geom=getattr(self, "_last_capture_monitor", (0, 0, 0, 0)),+ monitor_geom=captured.monitor_geom,)async def close(self) -> None:@@ -420,8 +432,8 @@ class ScreenshotSource:# ---- Internals ---------------------------------------------------------- def _capture_image(self) -> bytes | None:- """Blocking: takes a primary-monitor capture and returns image bytes.+ def _capture_image(self) -> _CapturedImage | None:+ """Blocking: capture image bytes and their immutable monitor geometry.Format is `self._image_format` — JPEG q85 default (8x smaller than PNGat identical token cost, since Claude/GPT/Gemini bill by pixel area,@@ -462,18 +474,14 @@ class ScreenshotSource:monitor_id: str = "unknown"try:- with mss.mss() as sct:+ with per_monitor_dpi_context(), mss.mss() as sct:target = self._select_capture_monitor(sct.monitors)# Keep a human-readable monitor identity for the warning message.monitor_id = (f"left={target.get('left', '?')},top={target.get('top', '?')},"f"{target.get('width', '?')}x{target.get('height', '?')}")- # Record the EXACT monitor this frame was captured from so the- # click-coordinate resolver maps the model's 0-1000 coords back to- # THIS screen — not a separately-derived monitor that can diverge- # on a mixed-DPI / multi-monitor desktop (live bug 2026-06-28).- self._last_capture_monitor = (+ monitor_geom = (int(target.get("left", 0)), int(target.get("top", 0)),int(target.get("width", 0)), int(target.get("height", 0)),)@@ -506,7 +514,7 @@ class ScreenshotSource:img.save(buf, format="JPEG", quality=self._jpeg_quality, optimize=False)else:img.save(buf, format="PNG", optimize=False, compress_level=1)- return buf.getvalue()+ return _CapturedImage(buf.getvalue(), monitor_geom)def _select_capture_monitor(self, monitors: list[dict]) -> dict:"""Delegates to the module function, so other pathsdiff --git a/jarvis/vision/uia_tree.py b/jarvis/vision/uia_tree.pyindex 8983d53d1e..32242d06c2 100644--- a/jarvis/vision/uia_tree.py+++ b/jarvis/vision/uia_tree.py@@ -22,12 +22,14 @@ from __future__ import annotationsimport asyncioimport hashlibimport logging+import threadingimport timefrom collections.abc import Callable, Sequencefrom typing import Any, Literalfrom uuid import uuid4from jarvis.core.protocols import CancelToken, Observation, UIANode+from jarvis.core.win32_dpi import per_monitor_dpi_contextfrom .pruning import (DEFAULT_INTERESTING_ROLES,@@ -62,7 +64,8 @@ def _run_traverser_with_com(import os # noqa: PLC0415if os.name != "nt":- return traverser(max_depth, window_title_filter)+ with per_monitor_dpi_context():+ return traverser(max_depth, window_title_filter)try:import pythoncom # type: ignore[import-not-found] # noqa: PLC0415except ImportError:@@ -81,7 +84,8 @@ def _run_traverser_with_com(# initialized as STA. UIA can traverse in that existing apartment;# it is not ours, so the finally block must not uninitialize it.logger.debug("UIA worker reusing its existing COM apartment")- return traverser(max_depth, window_title_filter)+ with per_monitor_dpi_context():+ return traverser(max_depth, window_title_filter)except Exception: # noqa: BLE001 — traversal failure degrades to image-onlylogger.warning("UIA worker traversal failed", exc_info=True)return ("", 0, [])@@ -90,6 +94,32 @@ def _run_traverser_with_com(pythoncom.CoUninitialize()+def _run_traverser_and_release(+ gate: threading.Lock,+ traverser: Callable[..., tuple[str, int, list[RawNode]]],+ max_depth: int,+ window_title_filter: str | None,+) -> tuple[str, int, list[RawNode]]:+ try:+ return _run_traverser_with_com(traverser, max_depth, window_title_filter)+ finally:+ gate.release()+++def _consume_traversal_exception(future: asyncio.Future) -> None:+ if future.cancelled():+ return+ try:+ error = future.exception()+ if error is not None:+ logger.debug(+ "Deferred UIA traversal failed",+ exc_info=(type(error), error, error.__traceback__),+ )+ except Exception: # noqa: BLE001 - callback must never reach the event loop+ logger.debug("Deferred UIA traversal failed", exc_info=True)++class UIATreeSource:"""Reads the UIAutomation tree of the active window and prunes it."""@@ -112,6 +142,7 @@ class UIATreeSource:self._min_overlap = min_on_screen_overlapself._monitor_bounds = monitor_bounds # None = detect at runtimeself._traverser = traverser+ self._traversal_gate = threading.Lock()self._closed = False# ---- Public API --------------------------------------------------------@@ -153,12 +184,23 @@ class UIATreeSource:if cancel_token is not None and cancel_token.is_cancelled():raise RuntimeError(f"cancelled: {cancel_token.reason}")traverse_fn = self._traverser or self._traverse_via_pywinauto- window_title, active_pid, raw_nodes = await asyncio.to_thread(- _run_traverser_with_com,- traverse_fn,- depth,- window_title_filter,- )+ if not self._traversal_gate.acquire(blocking=False):+ return self._fallback_observation(depth)+ loop = asyncio.get_running_loop()+ try:+ traversal = loop.run_in_executor(+ None,+ _run_traverser_and_release,+ self._traversal_gate,+ traverse_fn,+ depth,+ window_title_filter,+ )+ traversal.add_done_callback(_consume_traversal_exception)+ except Exception:+ self._traversal_gate.release()+ raise+ window_title, active_pid, raw_nodes = await asyncio.shield(traversal)nodes_before = len(raw_nodes)pruned = prune_tree(raw_nodes,@@ -206,6 +248,24 @@ class UIATreeSource:},)+ @staticmethod+ def _fallback_observation(depth: int) -> Observation:+ return Observation(+ trace_id=uuid4(),+ timestamp_ns=time.time_ns(),+ screenshot_path=None,+ screenshot_hash=UIATreeSource._hash_tree("", 0, ()),+ nodes=(),+ window_title="",+ active_pid=0,+ source="screenshot_only",+ pruning_stats={+ "nodes_before": 0,+ "nodes_after": 0,+ "depth_used": depth,+ },+ )+async def close(self) -> None:self._closed = True@@ -225,8 +285,12 @@ class UIATreeSource:import ctypes # noqa: PLC0415user32 = ctypes.windll.user32- w = user32.GetSystemMetrics(0)- h = user32.GetSystemMetrics(1)+ get_metric = user32.GetSystemMetrics+ get_metric.argtypes = [ctypes.c_int]+ get_metric.restype = ctypes.c_int+ with per_monitor_dpi_context():+ w = get_metric(0)+ h = get_metric(1)return (0, 0, int(w), int(h))except Exception: # noqa: BLE001# Fallback: FullHD. The only effect is that the OnScreen filter@@ -245,6 +309,10 @@ class UIATreeSource:UIA unavailable) an empty result is returned —never an exception, so the pipeline stays robust."""+ import os # noqa: PLC0415++ if os.name != "nt":+ return ("", 0, [])try:from pywinauto.uia_element_info import UIAElementInfo # noqa: PLC0415except ImportError:@@ -255,8 +323,13 @@ class UIATreeSource:# Find the foreground window. UIAElementInfo() with no arguments is# the desktop root — we need the foreground window.import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415- hwnd = ctypes.windll.user32.GetForegroundWindow()+ get_foreground = ctypes.windll.user32.GetForegroundWindow+ get_foreground.argtypes = []+ get_foreground.restype = wintypes.HWND+ with per_monitor_dpi_context():+ hwnd = get_foreground()if not hwnd:return ("", 0, [])root = UIAElementInfo(hwnd)diff --git a/tests/unit/core/test_win32_dpi_declaration.py b/tests/unit/core/test_win32_dpi_declaration.pyindex 2460291b19..40dababf33 100644--- a/tests/unit/core/test_win32_dpi_declaration.py+++ b/tests/unit/core/test_win32_dpi_declaration.py@@ -14,6 +14,9 @@ The ladder is tested with an injected fake ``windll`` so it runs on any OS.from __future__ import annotationsimport ctypes+from types import SimpleNamespace++import pytestfrom jarvis.core import win32_dpi@@ -68,11 +71,33 @@ def test_falls_back_to_shcore_per_monitor_v1():assert len(shcore.calls) == 1-def test_shcore_access_denied_counts_as_already_per_monitor():+def test_shcore_access_denied_reports_the_effective_awareness():fake = _windll(v2=_Fn(result=0), shcore=_Fn(result=-2147024891))+ fake.user32.GetThreadDpiAwarenessContext = _Fn(result=123)+ fake.user32.AreDpiAwarenessContextsEqual = _Fn(result=0)+ fake.user32.GetAwarenessFromDpiAwarenessContext = _Fn(result=2)assert win32_dpi._apply_process_awareness(fake) == "per_monitor"+def test_shcore_access_denied_does_not_invent_per_monitor_awareness():+ fake = _windll(v2=_Fn(result=0), shcore=_Fn(result=-2147024891))+ fake.user32.GetThreadDpiAwarenessContext = _Fn(result=123)+ fake.user32.AreDpiAwarenessContextsEqual = _Fn(result=0)+ fake.user32.GetAwarenessFromDpiAwarenessContext = _Fn(result=1)+ assert win32_dpi._apply_process_awareness(fake) == "system"+++def test_shcore_access_denied_prefers_actual_process_awareness():+ fake = _windll(v2=_Fn(result=0), shcore=_Fn(result=-2147024891))++ def get_process_awareness(_process, awareness):+ awareness._obj.value = 1+ return 0++ fake.shcore.GetProcessDpiAwareness = get_process_awareness+ assert win32_dpi._apply_process_awareness(fake) == "system"++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"@@ -104,3 +129,30 @@ 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()+++def test_per_monitor_context_restores_the_previous_thread_context(monkeypatch):+ calls: list[int | None] = []++ def set_context(context):+ calls.append(context.value)+ return 123++ monkeypatch.setattr(win32_dpi, "os", SimpleNamespace(name="nt"))+ monkeypatch.setattr(win32_dpi, "_DPI_AWARENESS_SET", True)+ monkeypatch.setattr(+ ctypes,+ "windll",+ SimpleNamespace(user32=SimpleNamespace(SetThreadDpiAwarenessContext=set_context)),+ raising=False,+ )++ with win32_dpi.per_monitor_dpi_context():+ assert calls == [ctypes.c_void_p(-4).value]++ assert calls == [ctypes.c_void_p(-4).value, 123]++ calls.clear()+ with pytest.raises(RuntimeError), win32_dpi.per_monitor_dpi_context():+ raise RuntimeError("probe")+ assert calls == [ctypes.c_void_p(-4).value, 123]diff --git a/tests/unit/platform/test_win32_ctypes_bindings.py b/tests/unit/platform/test_win32_ctypes_bindings.pynew file mode 100644index 0000000000..d0b75a2165--- /dev/null+++ b/tests/unit/platform/test_win32_ctypes_bindings.py@@ -0,0 +1,65 @@+from __future__ import annotations++import ctypes+from ctypes import wintypes+from types import SimpleNamespace++from jarvis.cu.indicator.win32 import _configure_user32 as configure_indicator_api+from jarvis.platform.window_state import _configure_window_query_api+++class _Fn:+ def __call__(self, *args):+ return 0+++def _api(*names: str) -> SimpleNamespace:+ return SimpleNamespace(**{name: _Fn() for name in names})+++def test_window_query_bindings_preserve_pointer_sized_hwnds() -> None:+ user32 = _api(+ "GetForegroundWindow",+ "GetWindowTextLengthW",+ "GetWindowTextW",+ "GetWindowThreadProcessId",+ "GetWindowRect",+ "GetClientRect",+ "ClientToScreen",+ "IsWindowVisible",+ "IsIconic",+ "GetSystemMetrics",+ "GetClassNameW",+ "GetWindowLongW",+ "ShowWindow",+ "SetForegroundWindow",+ "SetActiveWindow",+ "BringWindowToTop",+ "AttachThreadInput",+ "GetWindowPlacement",+ "SetWindowPos",+ )++ _configure_window_query_api(user32, ctypes, wintypes)++ assert user32.GetForegroundWindow.restype is wintypes.HWND+ assert user32.GetWindowRect.argtypes[0] is wintypes.HWND+ assert ctypes.sizeof(user32.GetWindowRect.argtypes[0]) == ctypes.sizeof(+ ctypes.c_void_p+ )+++def test_indicator_bindings_preserve_pointer_sized_hwnds() -> None:+ user32 = _api(+ "GetWindowLongW",+ "SetWindowLongW",+ "SetWindowDisplayAffinity",+ )++ configure_indicator_api(user32, ctypes, wintypes)++ assert user32.GetWindowLongW.argtypes[0] is wintypes.HWND+ assert user32.SetWindowDisplayAffinity.argtypes[0] is wintypes.HWND+ assert ctypes.sizeof(user32.GetWindowLongW.argtypes[0]) == ctypes.sizeof(+ ctypes.c_void_p+ )diff --git a/tests/unit/platform/test_window_state_rects.py b/tests/unit/platform/test_window_state_rects.pyindex 0013e6ac02..e35b0954f1 100644--- a/tests/unit/platform/test_window_state_rects.py+++ b/tests/unit/platform/test_window_state_rects.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport subprocessimport sysimport types+from contextlib import nullcontextfrom jarvis.platform import window_state as wsfrom jarvis.platform.window_state import WindowInfo@@ -159,14 +160,80 @@ def test_windows_frame_rect_without_handle_is_none(monkeypatch):# 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.+def test_grab_window_dispatches_to_native_windows_capture(monkeypatch):from jarvis.platform import window_capture as wcmonkeypatch.setattr(wc, "detect_platform", lambda: "win32")+ monkeypatch.setattr(+ wc,+ "_grab_window_windows",+ lambda handle, bbox: ((bbox["width"], bbox["height"]), b"rgb"),+ )assert wc.grab_window(1234, {"left": 0, "top": 0,- "width": 100, "height": 100}) is None+ "width": 100, "height": 100}) == (+ (100, 100), b"rgb"+ )+++def test_offscreen_rects_do_not_intersect_virtual_desktop():+ assert ws._rects_intersect((10, 10, 100, 100), (0, 0, 1920, 1080))+ assert not ws._rects_intersect((-32000, -32000, 160, 30), (0, 0, 1920, 1080))+++def test_windows_capture_uses_hwnd_and_rejects_ambiguous_framing(monkeypatch):+ from jarvis.core import win32_dpi+ from jarvis.platform import window_capture as wc++ calls: list[int] = []++ class _Image:+ size = (101, 100)++ def close(self):+ pass++ monkeypatch.setattr(wc, "os", types.SimpleNamespace(name="nt"))+ monkeypatch.setattr(win32_dpi, "per_monitor_dpi_context", nullcontext)+ monkeypatch.setattr(+ "PIL.ImageGrab.grab",+ lambda *, window: calls.append(window) or _Image(),+ )++ assert wc._grab_window_windows(+ 0x1_0000_1234,+ {"left": 0, "top": 0, "width": 100, "height": 100},+ ) is None+ assert calls == [0x1_0000_1234]+++def test_windows_client_capture_is_padded_into_frame_coordinates(monkeypatch):+ from PIL import Image++ from jarvis.core import win32_dpi+ from jarvis.platform import window_capture as wc++ client_image = Image.new("RGB", (100, 80), color=(200, 10, 20))+ monkeypatch.setattr(wc, "os", types.SimpleNamespace(name="nt"))+ monkeypatch.setattr(win32_dpi, "per_monitor_dpi_context", nullcontext)+ monkeypatch.setattr("PIL.ImageGrab.grab", lambda *, window: client_image.copy())+ monkeypatch.setattr(ws, "_window_rect_windows", lambda _hwnd: None)+ monkeypatch.setattr(+ ws,+ "_window_client_rect_windows",+ lambda _hwnd: (0, 20, 100, 80),+ )++ result = wc._grab_window_windows(+ 0x1_0000_1234,+ {"left": 0, "top": 0, "width": 100, "height": 100},+ )++ assert result is not None+ size, rgb = result+ framed = Image.frombytes("RGB", size, rgb)+ assert size == (100, 100)+ assert framed.getpixel((50, 10)) == (0, 0, 0)+ assert framed.getpixel((50, 20)) == (200, 10, 20)def test_grab_window_macos_degrades_without_frameworks(monkeypatch):diff --git a/tests/unit/screen_context/test_ports.py b/tests/unit/screen_context/test_ports.pyindex 524ef4f2cd..644c87da28 100644--- a/tests/unit/screen_context/test_ports.py+++ b/tests/unit/screen_context/test_ports.py@@ -1,6 +1,9 @@"""Cross-platform capability guards for Screen Context ports."""from __future__ import annotations+from contextlib import nullcontext+from types import SimpleNamespace+import pytestfrom jarvis.platform.window_state import WindowInfo@@ -36,6 +39,24 @@ def test_wayland_permission_probe_is_actionable(assert "portal" in issue.message.lower()+def test_windows_window_capture_never_falls_back_to_desktop_rect(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(ports, "os", SimpleNamespace(name="nt"))+ monkeypatch.setattr(ports, "_input_space", nullcontext)+ monkeypatch.setattr(+ "jarvis.cu.indicator.capture_guard.indicator_suppressed",+ nullcontext,+ )+ monkeypatch.setattr("jarvis.platform.window_capture.grab_window", lambda *_a, **_k: None)++ with pytest.raises(ports.CaptureUnavailable, match="refused"):+ ports.NativeSurfaceCapturer().grab(+ (0, 0, 100, 100),+ window_handle=0x1_0000_1234,+ )++def test_visible_windows_retains_untitled_password_manager_candidate(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/unit/screen_context/test_redaction.py b/tests/unit/screen_context/test_redaction.pyindex 4e981b3939..d40367515e 100644--- a/tests/unit/screen_context/test_redaction.py+++ b/tests/unit/screen_context/test_redaction.py@@ -16,6 +16,7 @@ from jarvis.screen_context.redaction import (merge_reports,regions_to_redact,scrub_text,+ validate_pattern_source,)@@ -187,6 +188,17 @@ def test_invalid_custom_pattern_is_skipped_not_fatal() -> None:assert "[redacted:card]" in scrubbed, "defaults must still apply"+def test_custom_pattern_rejects_nested_repetition() -> None:+ source = r"(a+)+$"++ assert validate_pattern_source(source) is not None+ assert build_patterns([f"unsafe:{source}"], include_defaults=False) == ()+++def test_bounded_custom_pattern_remains_available() -> None:+ assert validate_pattern_source(r"CUST-[0-9]+") is None++def test_defaults_can_be_replaced_entirely() -> None:patterns = build_patterns(["only:SECRET"], include_defaults=False)scrubbed, _ = scrub_text("4111 1111 1111 1111 SECRET", patterns)diff --git a/tests/unit/screen_context/test_service.py b/tests/unit/screen_context/test_service.pyindex 7cc52b2c08..94e6d44bd6 100644--- a/tests/unit/screen_context/test_service.py+++ b/tests/unit/screen_context/test_service.py@@ -13,6 +13,9 @@ assertion about behaviour rather than about call plumbing."""from __future__ import annotations+import asyncio+import io+import secretsimport threadingfrom jarvis.screen_context.models import (@@ -30,6 +33,7 @@ from jarvis.screen_context.ports import (from jarvis.screen_context.service import (ScreenContextService,ScreenContextSettings,+ _encode,settings_from_config,)@@ -529,6 +533,33 @@ async def test_sensitive_text_is_scrubbed_from_the_context() -> None:assert "4111" not in outcome.context.ui_text+async def test_ocr_sensitive_line_is_burned_out_of_delivered_pixels(monkeypatch) -> None:+ from PIL import Image++ from jarvis.screen_context import uitext++ monkeypatch.setattr(+ uitext,+ "ocr_supplement_with_regions",+ lambda _image: uitext.OcrSupplement(+ text="Card 4111 1111 1111 1111",+ regions=(+ uitext.OcrTextRegion(+ text="Card 4111 1111 1111 1111",+ bounds=(10, 10, 180, 30),+ ),+ ),+ ),+ )+ service = make_service(settings=ScreenContextSettings(ocr_enabled=True))++ outcome = await service.capture_for_turn("look at this", locale="en")++ assert outcome.context.redactions.region_count == 1+ delivered = Image.open(io.BytesIO(outcome.context.image)).convert("RGB")+ assert sum(delivered.getpixel((40, 20))) < 30++async def test_text_from_another_monitor_is_not_included() -> None:"""The tree spans the desktop; the picture does not."""reader = FakeTextReader(@@ -574,6 +605,27 @@ async def test_absent_accessibility_layer_is_reported_not_faked() -> None:assert DegradationCode.NO_UI_TEXT in {d.code for d in outcome.context.degradations}+async def test_accessibility_timeout_degrades_to_image_only(monkeypatch) -> None:+ from jarvis.screen_context import service as service_module++ class HangingTextReader:+ name = "hanging-text"++ async def read(self, *, window_title_filter=None):+ await asyncio.Event().wait()++ monkeypatch.setattr(service_module, "_UI_TEXT_TIMEOUT_S", 0.01)+ service = make_service(ui_text_reader=HangingTextReader())++ outcome = await service.capture_for_turn("look at this", locale="en")++ assert outcome.status == "captured"+ assert outcome.context.ui_text_source == "none"+ assert DegradationCode.NO_UI_TEXT in {+ item.code for item in outcome.context.degradations+ }++async def test_accessibility_text_from_a_different_process_is_discarded() -> None:reader = FakeTextReader(FakeObservation(@@ -729,6 +781,30 @@ async def test_an_unconsumed_capture_expires() -> None:assert service.held_count == 0+async def test_unconsumed_capture_expires_without_another_service_call() -> None:+ service = make_service(settings=ScreenContextSettings(ttl_s=0.01))+ outcome = await service.capture_for_turn("look at this", locale="en")+ assert outcome.handle_id in service._handles++ await asyncio.sleep(0.03)++ assert outcome.handle_id not in service._handles+++async def test_closing_service_rejects_new_pixels_and_cancels_timers() -> None:+ service = make_service(settings=ScreenContextSettings(ttl_s=60.0))+ outcome = await service.capture_for_turn("look at this", locale="en")+ assert outcome.handle_id in service._expiry_timers++ assert service.close() == 1+ assert service._handles == {}+ assert service._expiry_timers == {}++ refused = await service.capture_for_turn("look at this", locale="en")+ assert refused.status == "refused"+ assert refused.reason_kind == "technical"++async def test_discard_all_drops_everything_immediately() -> None:service = make_service()await service.capture_for_turn("look at this", locale="en")@@ -738,6 +814,16 @@ async def test_discard_all_drops_everything_immediately() -> None:assert service.held_count == 0+async def test_discard_one_does_not_return_pixels_or_drop_other_handles() -> None:+ service = make_service()+ first = await service.capture_for_turn("look at this", locale="en")+ second = await service.capture_for_turn("look at this", locale="en")++ assert service.discard(first.handle_id) is True+ assert service.discard(first.handle_id) is False+ assert service.peek(second.handle_id) is not None++async def test_nothing_is_written_to_disk(tmp_path, monkeypatch) -> None:"""The context carries bytes, never a path — a path implies a file."""monkeypatch.chdir(tmp_path)@@ -750,6 +836,19 @@ async def test_nothing_is_written_to_disk(tmp_path, monkeypatch) -> None:assert not hasattr(outcome.context, "screenshot_path")+def test_high_entropy_image_is_always_encoded_below_the_byte_ceiling() -> None:+ from PIL import Image++ random_bytes = secrets.token_bytes(2048 * 2048 * 3)+ image = Image.frombytes("RGB", (2048, 2048), random_bytes)++ encoded, size = _encode(image)++ assert len(encoded) <= 500_000+ assert size[0] < 2048+ assert size[1] < 2048++# --------------------------------------------------------------------------# Bus / indicator# --------------------------------------------------------------------------diff --git a/tests/unit/screen_context/test_targeting.py b/tests/unit/screen_context/test_targeting.pyindex e33997967a..a53be79898 100644--- a/tests/unit/screen_context/test_targeting.py+++ b/tests/unit/screen_context/test_targeting.py@@ -119,6 +119,30 @@ def test_unusable_window_rect_falls_back_to_the_monitor() -> None:assert DegradationCode.WINDOW_RECT_UNUSABLE in {d.code for d in degradations}+def test_stale_offscreen_window_rect_falls_back_to_a_physical_monitor() -> None:+ target, degradations = resolve_target(+ VisualIntent.WINDOW,+ monitors=MONITORS,+ cursor_point=(1000, 500),+ bar_point=None,+ window=WindowFacts(+ title="Disconnected display",+ frame_rect=(20_000, 20_000, 1200, 900),+ ),+ window_handle=4242,+ )++ assert target.kind is TargetKind.MONITOR+ assert target.bbox == (+ PRIMARY["left"],+ PRIMARY["top"],+ PRIMARY["width"],+ PRIMARY["height"],+ )+ assert target.window_handle is None+ assert DegradationCode.WINDOW_RECT_UNUSABLE in {item.code for item in degradations}++def test_screen_intent_never_narrows_to_the_window() -> None:""""Look at this" means the screen; only a window-scoped turn narrows."""target, _ = resolve_target(diff --git a/tests/unit/screen_context/test_uitext.py b/tests/unit/screen_context/test_uitext.pynew file mode 100644index 0000000000..79c53a215f--- /dev/null+++ b/tests/unit/screen_context/test_uitext.py@@ -0,0 +1,41 @@+"""OCR geometry and accessibility-density guards for Screen Context."""+from __future__ import annotations++import sys+from types import SimpleNamespace++from jarvis.screen_context.uitext import (+ ocr_supplement_with_regions,+ text_is_sparse,+)+++def test_ocr_words_are_grouped_into_redactable_lines(monkeypatch) -> None:+ data = {+ "text": ["Card", "4111", "1111"],+ "left": [10, 55, 100],+ "top": [20, 20, 20],+ "width": [35, 35, 35],+ "height": [12, 12, 12],+ "block_num": [1, 1, 1],+ "par_num": [1, 1, 1],+ "line_num": [1, 1, 1],+ }+ fake = SimpleNamespace(+ Output=SimpleNamespace(DICT="dict"),+ image_to_data=lambda _image, *, output_type: data,+ )+ monkeypatch.setitem(sys.modules, "pytesseract", fake)++ result = ocr_supplement_with_regions(object())++ assert result.text == "Card 4111 1111"+ assert result.regions[0].bounds == (10, 20, 125, 12)+ assert result.degradation is None+++def test_sparse_text_threshold_scales_with_full_monitor_area() -> None:+ text = "A few toolbar labels that exceed the legacy fixed threshold"++ assert not text_is_sparse(text, image_size=(400, 200))+ assert text_is_sparse(text, image_size=(2048, 1152))diff --git a/tests/unit/vision/test_screenshot_capture_geometry.py b/tests/unit/vision/test_screenshot_capture_geometry.pynew file mode 100644index 0000000000..9d74fecf73--- /dev/null+++ b/tests/unit/vision/test_screenshot_capture_geometry.py@@ -0,0 +1,38 @@+from __future__ import annotations++import asyncio+import hashlib+import threading++from jarvis.vision.screenshot import ScreenshotSource, _CapturedImage+++async def test_concurrent_observations_keep_their_own_capture_geometry(+ monkeypatch,+) -> None:+ source = ScreenshotSource(save_blob=False)+ barrier = threading.Barrier(2)+ capture_count = 0+ count_lock = threading.Lock()+ captures = (+ _CapturedImage(b"first", (-1920, 0, 1920, 1080)),+ _CapturedImage(b"second", (0, 0, 2560, 1440)),+ )++ def capture() -> _CapturedImage:+ nonlocal capture_count+ with count_lock:+ index = capture_count+ capture_count += 1+ barrier.wait(timeout=2.0)+ return captures[index]++ monkeypatch.setattr(source, "_capture_image", capture)+ observations = await asyncio.gather(source.observe(), source.observe())++ actual = {(item.screenshot_hash, item.monitor_geom) for item in observations}+ expected = {+ (hashlib.sha256(item.image_bytes).hexdigest(), item.monitor_geom)+ for item in captures+ }+ assert actual == expecteddiff --git a/tests/unit/vision/test_uia_traversal_gate.py b/tests/unit/vision/test_uia_traversal_gate.pynew file mode 100644index 0000000000..8dab4d2884--- /dev/null+++ b/tests/unit/vision/test_uia_traversal_gate.py@@ -0,0 +1,105 @@+from __future__ import annotations++import asyncio+import threading+from collections.abc import Callable++import pytest++from jarvis.vision.uia_tree import UIATreeSource+++async def test_busy_traversal_gate_falls_back_without_submitting_another_worker() -> None:+ started = threading.Event()+ release = threading.Event()+ calls = 0++ def traverser(depth, title_filter):+ nonlocal calls+ calls += 1+ started.set()+ release.wait(timeout=2.0)+ return ("Window", 1, [])++ source = UIATreeSource(+ traverser=traverser,+ monitor_bounds=(0, 0, 1920, 1080),+ )+ first = asyncio.create_task(source.observe())+ assert await asyncio.to_thread(started.wait, 1.0)++ second = await asyncio.wait_for(source.observe(), timeout=0.2)+ assert second.source == "screenshot_only"+ assert calls == 1++ release.set()+ assert (await first).source == "ui_tree_only"+++async def test_cancelled_observe_keeps_gate_closed_until_worker_finishes() -> None:+ started = threading.Event()+ release = threading.Event()+ calls = 0++ def traverser(depth, title_filter):+ nonlocal calls+ calls += 1+ started.set()+ release.wait(timeout=2.0)+ return ("Window", 1, [])++ source = UIATreeSource(+ traverser=traverser,+ monitor_bounds=(0, 0, 1920, 1080),+ )+ first = asyncio.create_task(source.observe())+ assert await asyncio.to_thread(started.wait, 1.0)+ first.cancel()+ with pytest.raises(asyncio.CancelledError):+ await first++ second = await asyncio.wait_for(source.observe(), timeout=0.2)+ assert second.source == "screenshot_only"+ assert calls == 1+ release.set()+++async def test_queued_traversal_releases_gate_after_caller_is_cancelled(+ monkeypatch,+) -> None:+ source = UIATreeSource(+ traverser=lambda depth, title_filter: ("Window", 1, []),+ monitor_bounds=(0, 0, 1920, 1080),+ )+ loop = asyncio.get_running_loop()+ scheduled: list[+ tuple[asyncio.Future, Callable[..., object], tuple[object, ...]]+ ] = []++ def queue_only(_executor, function, *args):+ future = loop.create_future()+ scheduled.append((future, function, args))+ return future++ monkeypatch.setattr(loop, "run_in_executor", queue_only)+ first = asyncio.create_task(source.observe())+ await asyncio.sleep(0)+ assert len(scheduled) == 1+ first.cancel()+ with pytest.raises(asyncio.CancelledError):+ await first++ busy = await source.observe()+ assert busy.source == "screenshot_only"+ assert len(scheduled) == 1++ queued, function, args = scheduled[0]+ queued.set_result(function(*args))+ await asyncio.sleep(0)++ third = asyncio.create_task(source.observe())+ await asyncio.sleep(0)+ assert len(scheduled) == 2+ queued, function, args = scheduled[1]+ queued.set_result(function(*args))+ assert (await third).source == "ui_tree_only"