Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(screen-context): capture the front window as its screen rectangle first

rubenluetke10-beepc296efddcc52
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
index 4f1b1a3af3..84cf2585aa 100644
--- a/jarvis/screen_context/service.py
+++ b/jarvis/screen_context/service.py
@@ -633,39 +633,31 @@ class ScreenContextService:
await self._dismiss_indicator(trace_id=event_trace_id)
async def _grab(self, target: CaptureTarget) -> tuple[tuple[int, int], bytes]:
- """Grab the target; rescue a window capture that came back empty.
-
- Native window-only capture returns a single flat colour for some
- GPU-composited windows (WebView2 apps — Jarvis's own window among
- them — measured 2026-09-29: every pixel luma 10; BUG-220). Handing that to a
- model produces a confident description of a blank screen. When the
- window is in front, the same rectangle of the desktop IS the window,
- so the rect grab is used instead — but only under the rule monitor
- captures already follow: no configured denylist, or no visible window
- in that rectangle matching it.
+ """Grab the target the way the user sees it.
+
+ A window target is always the window in FRONT, so its rectangle of the
+ desktop is exactly the window as the user sees it. That rect grab is
+ the first choice. Native window-only capture returned near-black
+ frames for GPU-composited windows (WebView2 apps, Jarvis's own window
+ among them — BUG-220: luma 0-13 across the whole frame, so a
+ flat-colour check missed it) and remains only the privacy path: when a
+ denylisted window intersects the rectangle, the window alone is
+ captured, and a blank result there is refused rather than described.
"""
handle = target.window_handle
- native_error: CaptureUnavailable | None = None
- try:
- size, rgb = await asyncio.to_thread(
- self.capturer.grab, target.bbox, window_handle=handle
- )
- except CaptureUnavailable as exc:
- if handle is None:
- raise
- native_error, size, rgb = exc, (0, 0), b""
if handle is None:
- return size, rgb
- if native_error is None and not await asyncio.to_thread(_is_flat_frame, size, rgb):
- return size, rgb
+ return await asyncio.to_thread(self.capturer.grab, target.bbox, window_handle=None)
blocked = await asyncio.to_thread(self._rect_privacy_error, target.bbox)
- if blocked:
- raise CaptureUnavailable(blocked) from native_error
- log.info(
- "screen_context: window-only capture %s — using the window's screen rectangle",
- "failed" if native_error is not None else "came back blank",
+ if not blocked:
+ return await asyncio.to_thread(self.capturer.grab, target.bbox, window_handle=None)
+ size, rgb = await asyncio.to_thread(
+ self.capturer.grab, target.bbox, window_handle=handle
)
- return await asyncio.to_thread(self.capturer.grab, target.bbox, window_handle=None)
+ if await asyncio.to_thread(_is_flat_frame, size, rgb):
+ raise CaptureUnavailable(
+ f"{blocked} The window alone could not be captured either."
+ )
+ return size, rgb
def _rect_privacy_error(self, bbox: tuple[int, int, int, int]) -> str | None:
"""Refuse a desktop-rectangle grab a denylisted window could appear in."""
@@ -1156,20 +1148,37 @@ class ScreenContextService:
def _is_flat_frame(size: tuple[int, int], rgb: bytes) -> bool:
- """True when a frame is one flat colour — a capture that produced nothing.
+ """True when a frame carries no picture — a capture that produced nothing.
- A real window always carries some contrast (text, borders, an icon); a
- downscaled frame whose every channel spans at most two levels does not.
+ A real window has contrast somewhere (text, borders, an icon). A frame
+ whose middle 98 % of pixels spans at most a few luma levels does not, even
+ when anti-aliased corners or a one-pixel edge stray from the flat body.
"""
width, height = size
if width <= 0 or height <= 0 or len(rgb) < width * height * 3:
return True
from PIL import Image # noqa: PLC0415
- image = Image.frombytes("RGB", size, rgb)
- factor = max(1, min(width, height) // 64)
- sample = image.reduce(factor) if factor > 1 else image
- return all(high - low <= 2 for low, high in sample.getextrema())
+ image = Image.frombytes("RGB", size, rgb).convert("L")
+ factor = max(1, min(width, height) // 128)
+ if factor > 1:
+ image = image.reduce(factor)
+ histogram = image.histogram()
+ total = sum(histogram)
+ cut = total * 0.01
+ seen, low = 0, 0
+ for level, count in enumerate(histogram):
+ seen += count
+ if seen > cut:
+ low = level
+ break
+ seen, high = 0, 255
+ for level in range(255, -1, -1):
+ seen += histogram[level]
+ if seen > cut:
+ high = level
+ break
+ return high - low <= 6
def _safe_target_label(target: CaptureTarget) -> str:
diff --git a/tests/unit/screen_context/test_blank_window_capture.py b/tests/unit/screen_context/test_blank_window_capture.py
index b7f341cc6f..1d0d87764c 100644
--- a/tests/unit/screen_context/test_blank_window_capture.py
+++ b/tests/unit/screen_context/test_blank_window_capture.py
@@ -1,9 +1,11 @@
-"""A window-only capture that comes back as one flat colour is not a picture.
-
-Native window capture returns a uniform frame for some GPU-composited windows
-(WebView2 apps, measured 2026-09-29). Handing that to a model yields a
-confident description of a blank screen, so the service uses the window's
-screen rectangle instead — under the same denylist rule monitor captures obey.
+"""The front window is captured as the user sees it (BUG-220).
+
+Native window-only capture returned near-black frames for GPU-composited
+windows (WebView2 apps; live 2026-09-29: luma 0-13 over the whole frame), and
+the model then described a blank screen. A window target is always the window
+in front, so its rectangle of the desktop is the first choice. The window-only
+path survives only as the privacy route when a denylisted window intersects
+that rectangle — and a blank result there is refused, never described.
"""
from __future__ import annotations
@@ -11,7 +13,7 @@ from __future__ import annotations
from jarvis.screen_context.models import IntentVerdict, VisualIntent, WindowFacts
from jarvis.screen_context.service import ScreenContextSettings, _is_flat_frame
-from .test_service import FakeCapturer, FakeWindowProbe, make_service
+from .test_service import FakeCapturer, FakeWindowProbe, RecordingBus, make_service
class VisibleWindows(FakeWindowProbe):
@@ -23,73 +25,86 @@ class VisibleWindows(FakeWindowProbe):
return list(self._visible)
+def striped(width: int, height: int) -> bytes:
+ row = bytes(((x // 8) % 2) * 255 for x in range(width))
+ return bytes(v for v in row * height for _ in range(3))
+
+
class BlankWindowCapturer(FakeCapturer):
- """Flat frame for the window-only path, real content for the rectangle."""
+ """Near-black frame for the window-only path, real content for the rectangle."""
def grab(self, bbox, *, window_handle=None):
(width, height), _ = super().grab(bbox, window_handle=window_handle)
if window_handle is not None:
- return (width, height), b"\x0a" * (width * height * 3)
- stripes = bytes(((x // 8) % 2) * 255 for x in range(width)) * height
- return (width, height), bytes(v for v in stripes for _ in range(3))
+ frame = bytearray(b"\x0a" * (width * height * 3))
+ frame[:3] = b"\x00\x00\x00" # a darker anti-aliased corner
+ return (width, height), bytes(frame)
+ return (width, height), striped(width, height)
+
+
+class ContentWindowCapturer(FakeCapturer):
+ def grab(self, bbox, *, window_handle=None):
+ (width, height), _ = super().grab(bbox, window_handle=window_handle)
+ return (width, height), striped(width, height)
WINDOW = IntentVerdict(intent=VisualIntent.WINDOW)
+VAULT_ON_TOP = VisibleWindows(
+ [WindowFacts(app_name="Vault", title="secrets", frame_rect=(10, 10, 800, 600))]
+)
-def test_flat_frame_detection() -> None:
- assert _is_flat_frame((4, 4), b"\x0a" * 48)
- assert not _is_flat_frame((4, 1), b"\x00\x00\x00\xff\xff\xff" * 2)
+def test_flat_frame_detection_tolerates_stray_corner_pixels() -> None:
+ body = bytearray(b"\x0a" * (64 * 64 * 3))
+ body[:3] = b"\x00\x00\x00"
+ body[-3:] = b"\x0d\x0d\x0d"
+ assert _is_flat_frame((64, 64), bytes(body))
+ assert not _is_flat_frame((64, 64), striped(64, 64))
assert _is_flat_frame((0, 0), b"")
-async def test_a_blank_window_capture_falls_back_to_its_rectangle() -> None:
+async def test_the_front_window_is_grabbed_as_its_screen_rectangle() -> None:
capturer = BlankWindowCapturer()
service = make_service(capturer=capturer)
outcome = await service.capture(verdict=WINDOW)
assert outcome.status == "captured"
- assert [handle for _bbox, handle in capturer.grabs] == [7, None]
- assert capturer.grabs[0][0] == capturer.grabs[1][0], "same rectangle both times"
+ assert [handle for _bbox, handle in capturer.grabs] == [None]
-async def test_the_fallback_obeys_the_denylist() -> None:
- capturer = BlankWindowCapturer()
+async def test_a_denylisted_overlap_uses_the_window_alone() -> None:
+ capturer = ContentWindowCapturer()
service = make_service(
capturer=capturer,
settings=ScreenContextSettings(denylist=("vault",)),
- window_probe=VisibleWindows(
- [WindowFacts(app_name="Vault", title="secrets", frame_rect=(10, 10, 800, 600))]
- ),
+ window_probe=VAULT_ON_TOP,
)
outcome = await service.capture(verdict=WINDOW)
- assert outcome.status == "refused"
- assert [handle for _bbox, handle in capturer.grabs] == [7], "no desktop rectangle grab"
-
+ assert outcome.status == "captured"
+ assert [handle for _bbox, handle in capturer.grabs] == [7], "no desktop rectangle"
-async def test_a_window_with_content_is_used_as_captured() -> None:
- class ContentCapturer(BlankWindowCapturer):
- def grab(self, bbox, *, window_handle=None):
- return super().grab(bbox, window_handle=None)
- capturer = ContentCapturer()
- service = make_service(capturer=capturer)
+async def test_a_blank_window_alone_is_refused_not_described() -> None:
+ capturer = BlankWindowCapturer()
+ service = make_service(
+ capturer=capturer,
+ settings=ScreenContextSettings(denylist=("vault",)),
+ window_probe=VAULT_ON_TOP,
+ )
outcome = await service.capture(verdict=WINDOW)
- assert outcome.status == "captured"
- assert len(capturer.grabs) == 1
+ assert outcome.status == "refused"
+ assert [handle for _bbox, handle in capturer.grabs] == [7]
async def test_an_appshot_service_shows_no_border_and_claims_no_missing_signal() -> None:
- from .test_service import RecordingBus
-
bus = RecordingBus()
shutters: list = []
- service = make_service(capturer=BlankWindowCapturer(), bus=bus)
+ service = make_service(capturer=ContentWindowCapturer(), bus=bus)
service.set_shutter_hook(lambda *args: shutters.append(args))
outcome = await service.capture(verdict=WINDOW)
diff --git a/tests/unit/screen_context/test_service.py b/tests/unit/screen_context/test_service.py
index 66872e591a..b8177766b1 100644
--- a/tests/unit/screen_context/test_service.py
+++ b/tests/unit/screen_context/test_service.py
@@ -328,7 +328,9 @@ async def test_window_scoped_request_captures_the_window() -> None:
outcome = await service.capture_for_turn("look at this window", locale="en")
assert outcome.context.target.kind is TargetKind.WINDOW
- assert capturer.grabs[0] == ((10, 10, 800, 600), 7)
+ # The front window's own rectangle, grabbed as the user sees it (BUG-220).
+ assert capturer.grabs == [((10, 10, 800, 600), None)]
+ assert outcome.context.target.window_handle == 7
async def test_window_facts_and_handle_come_from_one_atomic_snapshot() -> None:
@@ -355,7 +357,8 @@ async def test_window_facts_and_handle_come_from_one_atomic_snapshot() -> None:
outcome = await service.capture_for_turn("look at this window", locale="en")
assert outcome.status == "captured"
- assert capturer.grabs[0] == ((20, 30, 640, 480), 99)
+ assert capturer.grabs[0] == ((20, 30, 640, 480), None)
+ assert outcome.context.target.window_handle == 99
# --------------------------------------------------------------------------