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(vision): keep the overlay out of screenshots and let Grok inspect them

rubenluetke10-beep4ee69e18f518
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 27816ef9e2..dea2e5911a 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -2524,6 +2524,28 @@ _PROVIDER_DOWN_CAUSE_PHRASES: dict[str, dict[str, str]] = {
"de nuevo en un momento."
),
},
+ # A screenshot was attached but every reachable brain reported blind.
+ # This is NOT a missing/invalid API key — the key is often present and
+ # the API-Keys card is green; the model simply cannot inspect images.
+ # Spoken separately so a vision skip is not heard as "your key is broken".
+ "vision_unsupported": {
+ "de": (
+ "Entschuldige — ich habe den Bildschirm aufgenommen, aber keiner " # i18n-allow
+ "der verbundenen Assistenten kann gerade Bilder auswerten. Der " # i18n-allow
+ "Schlüssel ist da, nur das Sehen fehlt. Nimm unter API-Keys " # i18n-allow
+ "einen Anbieter mit Bildverarbeitung." # i18n-allow
+ ),
+ "en": (
+ "Sorry — I captured the screen, but none of the connected "
+ "assistants can inspect images right now. The key is there; "
+ "vision is not. Pick a vision-capable provider under API keys."
+ ),
+ "es": (
+ "Lo siento: capturé la pantalla, pero ninguno de los asistentes "
+ "conectados puede analizar imágenes ahora. La clave está; falta "
+ "la visión. Elige un proveedor con visión en Claves API."
+ ),
+ },
}
# Priority when several providers failed for different reasons — the FIRST
@@ -2535,6 +2557,7 @@ _PROVIDER_DOWN_CAUSE_PRIORITY: tuple[str, ...] = (
"missing_key",
"bad_key",
"account_blocked",
+ "vision_unsupported",
"invalid_model",
"context_overflow",
"rate_limit",
@@ -2555,6 +2578,7 @@ def _primary_provider_down_cause(
"missing_key",
"bad_key",
"account_blocked",
+ "vision_unsupported",
"invalid_model",
"context_overflow",
"rate_limit",
@@ -13572,6 +13596,7 @@ def _format_provider_chain_error(
missing_keys: list[str] = []
invalid_keys: list[str] = []
account_blocked: list[str] = []
+ vision_unsupported: list[str] = []
invalid_models: list[str] = []
context_overflow: list[str] = []
rate_limited: list[str] = []
@@ -13584,6 +13609,8 @@ def _format_provider_chain_error(
invalid_keys.append(prov_name)
elif kind == "account_blocked":
account_blocked.append(prov_name)
+ elif kind == "vision_unsupported":
+ vision_unsupported.append(prov_name)
elif kind == "invalid_model":
invalid_models.append(prov_name)
elif kind == "context_overflow":
@@ -13608,6 +13635,7 @@ def _format_provider_chain_error(
missing_keys = _uniq(missing_keys)
invalid_keys = _uniq(invalid_keys)
account_blocked = _uniq(account_blocked)
+ vision_unsupported = _uniq(vision_unsupported)
invalid_models = _uniq(invalid_models)
context_overflow = _uniq(context_overflow)
rate_limited = _uniq(rate_limited)
@@ -13641,6 +13669,12 @@ def _format_provider_chain_error(
"Bei Anthropic: console.anthropic.com/settings/billing. "
"Bei xAI: console.x.ai/team/billing."
)
+ if vision_unsupported:
+ parts.append(
+ f"Kein Bildverstehen bei {', '.join(vision_unsupported)} — " # i18n-allow
+ "der Key ist da, aber das Modell sieht keine Bilder. " # i18n-allow
+ "Unter API-Keys einen Anbieter mit Bildverarbeitung aktivieren." # i18n-allow
+ )
if invalid_models:
parts.append(
f"Ungueltige Model-ID bei {', '.join(invalid_models)}. "
diff --git a/jarvis/cu/indicator/win32.py b/jarvis/cu/indicator/win32.py
index 5608fbc7fd..3a44a3317d 100644
--- a/jarvis/cu/indicator/win32.py
+++ b/jarvis/cu/indicator/win32.py
@@ -25,7 +25,6 @@ _WS_EX_LAYERED = 0x00080000
_WS_EX_TRANSPARENT = 0x00000020
_WS_EX_NOACTIVATE = 0x08000000
_WS_EX_TOOLWINDOW = 0x00000080
-_WDA_EXCLUDEFROMCAPTURE = 0x00000011
CAPTURABLE_ENV = "JARVIS_CU_INDICATOR_CAPTURABLE"
@@ -57,13 +56,7 @@ def harden_window(hwnd: int) -> bool:
return False
try:
style = user32.GetWindowLongW(hwnd, _GWL_EXSTYLE)
- wanted = (
- style
- | _WS_EX_LAYERED
- | _WS_EX_TRANSPARENT
- | _WS_EX_NOACTIVATE
- | _WS_EX_TOOLWINDOW
- )
+ wanted = style | _WS_EX_LAYERED | _WS_EX_TRANSPARENT | _WS_EX_NOACTIVATE | _WS_EX_TOOLWINDOW
if wanted != style:
user32.SetWindowLongW(hwnd, _GWL_EXSTYLE, wanted)
return True
@@ -76,14 +69,11 @@ def exclude_from_capture(hwnd: int) -> bool:
"""Hide ``hwnd`` from all screen capture (BitBlt/mss/OBS/CU frames)."""
if os.environ.get(CAPTURABLE_ENV, "").strip() in {"1", "true", "yes"}:
return False
- user32 = _user32()
- if user32 is None or not hwnd:
- return False
- try:
- return bool(user32.SetWindowDisplayAffinity(hwnd, _WDA_EXCLUDEFROMCAPTURE))
- except Exception: # noqa: BLE001
- log.debug("exclude_from_capture failed for hwnd=%s", hwnd, exc_info=True)
- return False
+ from jarvis.platform.capture_exclusion import ( # noqa: PLC0415
+ exclude_hwnd_from_capture,
+ )
+
+ return exclude_hwnd_from_capture(hwnd)
def capture_exclusion_available() -> bool:
diff --git a/jarvis/platform/capture_exclusion.py b/jarvis/platform/capture_exclusion.py
new file mode 100644
index 0000000000..f7ab98dcc9
--- /dev/null
+++ b/jarvis/platform/capture_exclusion.py
@@ -0,0 +1,119 @@
+"""Keep overlay windows out of screenshots on every OS that can.
+
+The on-screen bar, mascot, and transcription bubble are for the person at
+the keyboard. They must not appear in a Screen Context / Computer-Use /
+screenshot-tool capture, or the model reads the last spoken line off the
+glass instead of the screen the user asked it to look at.
+
+Windows: ``SetWindowDisplayAffinity(WDA_EXCLUDEFROMCAPTURE)`` — the window
+stays visible to the user and is omitted from BitBlt/mss/OBS.
+macOS: ``NSWindowSharingNone`` on overlay process windows.
+Linux / headless: a quiet no-op (no equivalent API); callers may still
+blank the overlay around a grab via ``capture_guard``.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+_WDA_EXCLUDEFROMCAPTURE = 0x00000011
+# AppKit.NSWindowSharingNone — keep the numeric literal so a host without
+# pyobjc still documents the contract.
+_NS_WINDOW_SHARING_NONE = 0
+
+
+def _configure_user32(user32: Any, ctypes: Any, wintypes: Any) -> None:
+ user32.GetParent.argtypes = [wintypes.HWND]
+ user32.GetParent.restype = wintypes.HWND
+ user32.SetWindowDisplayAffinity.argtypes = [wintypes.HWND, wintypes.DWORD]
+ user32.SetWindowDisplayAffinity.restype = wintypes.BOOL
+
+
+def _user32() -> Any:
+ if sys.platform != "win32":
+ return None
+ import ctypes # noqa: PLC0415
+ from ctypes import wintypes # noqa: PLC0415
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ _configure_user32(user32, ctypes, wintypes)
+ return user32
+
+
+def exclude_hwnd_from_capture(hwnd: int) -> bool:
+ """Hide one native window from screen capture. No-op off Windows."""
+ if sys.platform != "win32" or not hwnd:
+ return False
+ user32 = _user32()
+ if user32 is None:
+ return False
+ try:
+ return bool(user32.SetWindowDisplayAffinity(int(hwnd), _WDA_EXCLUDEFROMCAPTURE))
+ except Exception: # noqa: BLE001 — overlay must degrade, never crash
+ log.debug("exclude_hwnd_from_capture failed for hwnd=%s", hwnd, exc_info=True)
+ return False
+
+
+def exclude_tk_window_from_capture(root: Any) -> bool:
+ """Exclude a Tk toplevel. Targets the outer ``TkTopLevel`` HWND on Windows.
+
+ Tk's ``winfo_id()`` is the inner ``TkChild``; capture affinity has to
+ land on the parent or the overlay still photographs. Best-effort: a
+ missing handle or a test double without ``winfo_id`` returns False.
+ """
+ if root is None:
+ return False
+ if sys.platform == "darwin":
+ return exclude_macos_app_windows()
+ if sys.platform != "win32":
+ return False
+ try:
+ inner = int(root.winfo_id())
+ except Exception: # noqa: BLE001 — FakeRoot / torn-down interpreter
+ return False
+ user32 = _user32()
+ if user32 is None or not inner:
+ return False
+ try:
+ outer = int(user32.GetParent(inner) or inner)
+ except Exception: # noqa: BLE001
+ outer = inner
+ return exclude_hwnd_from_capture(outer)
+
+
+def exclude_macos_app_windows() -> bool:
+ """Mark every NSWindow of this process as not shareable (overlay hosts).
+
+ Safe only in the overlay companion / bar process, whose windows are all
+ chrome. Best-effort: missing AppKit is a quiet no-op.
+ """
+ if sys.platform != "darwin":
+ return False
+ try:
+ from AppKit import NSApp # type: ignore[import-not-found] # noqa: PLC0415
+ except Exception: # noqa: BLE001
+ return False
+ try:
+ wins = list(NSApp.windows())
+ ok = False
+ for win in wins:
+ try:
+ win.setSharingType_(_NS_WINDOW_SHARING_NONE)
+ ok = True
+ except Exception: # noqa: BLE001, S112 — one window must not abort the rest
+ continue
+ return ok
+ except Exception: # noqa: BLE001
+ log.debug("exclude_macos_app_windows failed", exc_info=True)
+ return False
+
+
+__all__ = [
+ "exclude_hwnd_from_capture",
+ "exclude_macos_app_windows",
+ "exclude_tk_window_from_capture",
+]
diff --git a/jarvis/plugins/brain/grok.py b/jarvis/plugins/brain/grok.py
index 02a18a2a20..7088d8ed09 100644
--- a/jarvis/plugins/brain/grok.py
+++ b/jarvis/plugins/brain/grok.py
@@ -1,4 +1,5 @@
"""xAI Grok brain over its OpenAI-compatible API."""
+
from __future__ import annotations
import asyncio
@@ -20,8 +21,12 @@ class GrokBrain:
name: str = "grok"
context_window: int = 1_000_000
supports_tools: bool = True
- # The OpenAI-compatible image path has not been verified end to end yet.
- supports_vision: bool = False
+ # xAI's OpenAI-compatible chat API accepts ``image_url`` data URIs on
+ # grok-4.x. A False here made Screen Context / Computer-Use skip a live
+ # key and tell the user to "connect a vision-capable provider" even
+ # though the card in API Keys was green (architecture-overview: the
+ # 2026-06-21 CU "no vision" incident).
+ supports_vision: bool = True
def __init__(self, model: str | None = None) -> None:
self._model = model or DEFAULT_MODEL
@@ -32,9 +37,7 @@ class GrokBrain:
def _ensure_client(self) -> Any:
if self._client is None:
- ep = cfg.resolve_provider_endpoint(
- "grok", vendor_default_base_url=BASE_URL
- )
+ ep = cfg.resolve_provider_endpoint("grok", vendor_default_base_url=BASE_URL)
if not ep.credential:
raise RuntimeError(
"No xAI API key found "
diff --git a/jarvis/plugins/tool/screen_snapshot.py b/jarvis/plugins/tool/screen_snapshot.py
index dcc96315ee..b171180668 100644
--- a/jarvis/plugins/tool/screen_snapshot.py
+++ b/jarvis/plugins/tool/screen_snapshot.py
@@ -27,6 +27,7 @@ Flow in `execute`:
<base64>}]` so the vision-capable brain can consume the screenshot
directly.
"""
+
from __future__ import annotations
import base64
@@ -139,7 +140,16 @@ class ScreenSnapshotTool:
)
try:
- with mss.mss() as sct:
+ from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415
+ indicator_suppressed,
+ )
+ except Exception: # noqa: BLE001 — grab must still work without CU
+ from contextlib import nullcontext # noqa: PLC0415
+
+ indicator_suppressed = nullcontext
+
+ try:
+ with indicator_suppressed(), mss.mss() as sct:
monitors = sct.monitors
if len(monitors) < 2:
return ToolResult(
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index ad92a49191..c3d88b97fe 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -278,6 +278,11 @@ def _apply_macos_clear_backing() -> None:
win.setOpaque_(False)
win.setBackgroundColor_(NSColor.clearColor())
win.setHasShadow_(False)
+ from jarvis.platform.capture_exclusion import ( # noqa: PLC0415
+ exclude_macos_app_windows,
+ )
+
+ exclude_macos_app_windows()
log.debug("macOS clear-backing applied to %d window(s)", len(wins))
except Exception: # noqa: BLE001 — cosmetic; the grey box is the degrade
log.warning("macOS clear-backing pass failed", exc_info=True)
@@ -297,6 +302,19 @@ def _create_hidden_tk_root(tk: Any) -> Any:
return root
+def _exclude_tk_window_from_capture(root: Any) -> bool:
+ """Keep the bar out of screenshots. Best-effort, never raises."""
+ try:
+ from jarvis.platform.capture_exclusion import ( # noqa: PLC0415
+ exclude_tk_window_from_capture,
+ )
+
+ return bool(exclude_tk_window_from_capture(root))
+ except Exception: # noqa: BLE001 — overlay must degrade, never crash
+ log.debug("jarvisbar capture exclusion skipped", exc_info=True)
+ return False
+
+
def _win32_force_topmost(root: Any, *, user32: Any | None = None) -> bool:
"""Put a Tk toplevel in Win32's real topmost Z-order band.
@@ -918,6 +936,9 @@ class JarvisBarOverlay:
self._start_loop_waker() # outside Tk: wakes the thread itself (BUG-202)
self._schedule_z_order_guard()
self._schedule_cursor_monitor_guard() # follow the mouse across monitors
+ # Affinity can be set on a still-withdrawn HWND. Do it before the
+ # first map so the first screenshot never photographs the bar.
+ _exclude_tk_window_from_capture(root)
if not self._should_start_withdrawn():
self._do_show()
self._started.set()
@@ -1225,6 +1246,10 @@ class JarvisBarOverlay:
# only raised within the wrong band. Other desktop window managers use
# Tk's portable -topmost request + lift fallback.
self._do_pin_topmost()
+ # Style mutations (BUG-030 class) can silently drop display affinity
+ # the same way they drop the layered color-key. Re-pin after every
+ # topmost repair so the bar never re-enters screenshots.
+ _exclude_tk_window_from_capture(self._root)
# BUG-030 guard: re-asserting ``-topmost`` is itself a Win32 style
# mutation on this layered (color-key + alpha) window, and Windows can
# silently drop the layered attributes on such a mutation — the bar
@@ -1911,9 +1936,7 @@ class JarvisBarOverlay:
# The dictation modes render on the active pill too (dictate →
# "speak", dictate_transcribing → "think"), so their close-X sits
# where the active pill puts it.
- active = self._mode in ("listen", "think", "speak") or (
- self._mode in DICTATION_MODES
- )
+ active = self._mode in ("listen", "think", "speak") or (self._mode in DICTATION_MODES)
# The idle pill is OPEN while its controls are up, and the
# sparkle's hit-box has to track that pill, not the window.
pill_w = renderer.ACTIVE_W if active else renderer.OPEN_W
@@ -1968,9 +1991,7 @@ class JarvisBarOverlay:
cb = self._on_prompt_mode_toggle
if cb is not None:
cb()
- self._prompt_mode_paused = not getattr(
- self, "_prompt_mode_paused", False
- )
+ self._prompt_mode_paused = not getattr(self, "_prompt_mode_paused", False)
elif action == "hangup":
callback = self._on_hangup
if callback is not None:
diff --git a/jarvis/ui/jarvisbar/qt_overlay.py b/jarvis/ui/jarvisbar/qt_overlay.py
index 1a58fe6a81..b4e8837c71 100644
--- a/jarvis/ui/jarvisbar/qt_overlay.py
+++ b/jarvis/ui/jarvisbar/qt_overlay.py
@@ -200,8 +200,7 @@ def _macos_dock_is_visible_on_screen(screen: GeometryBounds) -> bool | None:
import Quartz # type: ignore[import-not-found] # noqa: PLC0415
options = (
- Quartz.kCGWindowListOptionOnScreenOnly
- | Quartz.kCGWindowListExcludeDesktopElements
+ Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements
)
windows = Quartz.CGWindowListCopyWindowInfo(
options,
@@ -660,15 +659,14 @@ class QtJarvisBarOverlay:
# in points, not physical pixels — mixing a physical-DPI anchor here
# would regress the signed-off Mac look. Physical sizing on macOS is a
# documented follow-up (renderer.resolve_screen_scale accepts a dpi).
- self._screen_scale = renderer.resolve_screen_scale(
- geometry.width(), geometry.height()
- )
+ self._screen_scale = renderer.resolve_screen_scale(geometry.width(), geometry.height())
renderer.apply_display_scale(self._screen_scale, user_size=self._user_size_scale)
self._renderer = renderer.JarvisBarRenderer(accent=self._accent)
window_type = _window_class()
self._window = window_type(self)
self._configure_macos_nonactivating_window_ui()
+ self._exclude_from_capture_ui()
self._resolve_position_ui()
self._window.move(self._x, self._y)
@@ -843,11 +841,30 @@ class QtJarvisBarOverlay:
self._invalidate_static_frame()
self._render_frame_ui()
self._window.show()
+ self._exclude_from_capture_ui()
self._raise_ui()
q = _qt()
mode = self._mode
q.QtCore.QTimer.singleShot(50, lambda: self._publish_visibility_ui(mode))
+ def _exclude_from_capture_ui(self) -> None:
+ """Keep the Qt bar out of screenshots. Best-effort, never raises."""
+ window = self._window
+ if window is None:
+ return
+ try:
+ from jarvis.platform.capture_exclusion import ( # noqa: PLC0415
+ exclude_hwnd_from_capture,
+ exclude_macos_app_windows,
+ )
+
+ if sys.platform == "darwin":
+ exclude_macos_app_windows()
+ return
+ exclude_hwnd_from_capture(int(window.winId()))
+ except Exception: # noqa: BLE001 — overlay must degrade, never crash
+ log.debug("qt bar capture exclusion skipped", exc_info=True)
+
def _raise_ui(self) -> None:
window = self._window
if window is None or not window.isVisible() or self._startup_gated:
@@ -995,12 +1012,8 @@ class QtJarvisBarOverlay:
x = float(point.x())
y = float(point.y())
return (
- center_x - pill_w / 2.0 - slop
- <= x
- < center_x + pill_w / 2.0 + slop
- and center_y - pill_h / 2.0 - slop
- <= y
- < center_y + pill_h / 2.0 + slop
+ center_x - pill_w / 2.0 - slop <= x < center_x + pill_w / 2.0 + slop
+ and center_y - pill_h / 2.0 - slop <= y < center_y + pill_h / 2.0 + slop
)
def _poll_hover_ui(self) -> None:
@@ -1033,9 +1046,7 @@ class QtJarvisBarOverlay:
full_bounds = _geometry_bounds(full)
available_bounds = _geometry_bounds(available)
dock_visible = (
- _macos_dock_is_visible_on_screen(full_bounds)
- if respect_visible_dock
- else False
+ _macos_dock_is_visible_on_screen(full_bounds) if respect_visible_dock else False
)
if dock_visible is not False:
return available
@@ -1425,9 +1436,7 @@ class QtJarvisBarOverlay:
protocol, so this is reached from the stdin reader thread and marshals
onto the Qt UI thread like every other cross-thread mutation.
"""
- state = (
- renderer.DROP_STATE_OK if accepted else renderer.DROP_STATE_REJECTED
- )
+ state = renderer.DROP_STATE_OK if accepted else renderer.DROP_STATE_REJECTED
self._enqueue_if_started(lambda s=state: self._set_drop_visual_ui(s))
def _deliver_drop_ui(self, mime: Any) -> None:
@@ -1466,9 +1475,7 @@ class QtJarvisBarOverlay:
# The dictation modes render on the active pill (dictate → "speak",
# dictate_transcribing → "think"), so their close-X sits where the
# active pill puts it.
- active = self._mode in ("listen", "think", "speak") or (
- self._mode in DICTATION_MODES
- )
+ active = self._mode in ("listen", "think", "speak") or (self._mode in DICTATION_MODES)
action = interaction.resolve_click(
click_x,
renderer.WIN_W,
diff --git a/tests/unit/brain/test_grok_provider_wiring.py b/tests/unit/brain/test_grok_provider_wiring.py
index 81ab5d7518..f7e6c03a62 100644
--- a/tests/unit/brain/test_grok_provider_wiring.py
+++ b/tests/unit/brain/test_grok_provider_wiring.py
@@ -1,4 +1,5 @@
"""xAI Grok is a first-class Brain and Jarvis-Agent provider."""
+
from __future__ import annotations
from types import SimpleNamespace
@@ -15,7 +16,7 @@ from jarvis.brain.manager import (
from jarvis.brain.model_catalog import _ENDPOINTS, CATALOG_PROVIDERS, catalog_spec
from jarvis.brain.provider_registry import BrainProviderRegistry
from jarvis.core import config as cfg
-from jarvis.core.protocols import BrainMessage, BrainRequest
+from jarvis.core.protocols import BrainMessage, BrainRequest, ImageBlock
from jarvis.missions.critic.runner import _API_CRITIC_PROVIDERS
from jarvis.missions.init import _API_AGENT_SLUGS, _select_subagent_worker_kind
from jarvis.missions.worker_runtime.provider_map import env_vars_for, to_worker_slug
@@ -104,7 +105,7 @@ def test_grok_defaults_are_universal_and_tool_capable() -> None:
brain = GrokBrain()
assert brain.context_window == 1_000_000
assert brain.can_call_tools() is True
- assert brain.supports_vision is False
+ assert brain.supports_vision is True
def test_grok_has_authenticated_live_model_catalog() -> None:
@@ -176,6 +177,55 @@ async def test_grok_streams_a_local_tool_call_round_trip() -> None:
assert completions.kwargs["model"] == DEFAULT_MODEL
+class _VisionStream:
+ def __init__(self) -> None:
+ self.kwargs: dict[str, Any] = {}
+
+ async def create(self, **kwargs: Any): # noqa: ANN201
+ self.kwargs = kwargs
+
+ async def _chunks(): # noqa: ANN202
+ yield SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ delta=SimpleNamespace(content="a window", tool_calls=None),
+ finish_reason="stop",
+ )
+ ],
+ usage=None,
+ )
+
+ return _chunks()
+
+
+async def test_grok_forwards_attached_images_on_the_openai_path() -> None:
+ """A screenshot attached to a Grok turn must reach xAI as image_url.
+
+ Live 2026-08-31: GrokBrain.supports_vision was False, so Screen Context
+ skipped a working xAI key and told the user to connect a vision provider
+ even though the API-Keys card was green.
+ """
+ completions = _VisionStream()
+ brain = GrokBrain()
+ brain._client = SimpleNamespace(chat=SimpleNamespace(completions=completions))
+ request = BrainRequest(
+ messages=(
+ BrainMessage(
+ role="user",
+ content="what is on the screen?",
+ images=(ImageBlock(mime="image/jpeg", data_b64="AAAA"),),
+ ),
+ ),
+ )
+ deltas = [delta async for delta in brain.complete(request)]
+ assert deltas, "Grok must complete a vision turn instead of dropping the image"
+ user = next(m for m in completions.kwargs["messages"] if m["role"] == "user")
+ assert isinstance(user["content"], list)
+ img = next(b for b in user["content"] if b.get("type") == "image_url")
+ assert img["image_url"]["url"].startswith("data:image/jpeg;base64,")
+
+
def test_grok_runs_in_process_for_worker_and_critic() -> None:
assert "grok" in _API_AGENT_SLUGS
assert _select_subagent_worker_kind("grok", "foreign-model") == "api_agent"
diff --git a/tests/unit/brain/test_provider_down_phrase.py b/tests/unit/brain/test_provider_down_phrase.py
index 7ba0785307..d94fd46f36 100644
--- a/tests/unit/brain/test_provider_down_phrase.py
+++ b/tests/unit/brain/test_provider_down_phrase.py
@@ -8,6 +8,7 @@ never read provider names or billing URLs; it speaks a short, provider-
agnostic apology in the user's SELECTED reply language (de/en/es; "auto" → de)
with three variants so repeated failures don't sound robotic.
"""
+
from __future__ import annotations
import pytest
@@ -21,8 +22,16 @@ from jarvis.brain.manager import (
# The exact leak tokens emitted by _format_provider_chain_error — none may
# survive into the spoken phrase.
_JARGON = (
- "grok", "anthropic", "openai", "openrouter", "gemini", "xai",
- "console.", "http", "billing", "credit",
+ "grok",
+ "anthropic",
+ "openai",
+ "openrouter",
+ "gemini",
+ "xai",
+ "console.",
+ "http",
+ "billing",
+ "credit",
)
@@ -100,8 +109,15 @@ class TestCauseAwareProviderDownPhrase:
# phrases; naming the CAUSE ("credit used up") is the whole point, so
# "credit"/"Guthaben" are deliberately allowed here. # i18n-allow
_CAUSE_JARGON = (
- "grok", "anthropic", "openai", "openrouter", "gemini", "xai",
- "console.", "http", "billing",
+ "grok",
+ "anthropic",
+ "openai",
+ "openrouter",
+ "gemini",
+ "xai",
+ "console.",
+ "http",
+ "billing",
)
def test_every_cause_covers_every_supported_language(self) -> None:
@@ -126,9 +142,7 @@ class TestCauseAwareProviderDownPhrase:
assert got == _PROVIDER_DOWN_CAUSE_PHRASES["missing_key"]["en"]
def test_unknown_cause_falls_back_to_generic_rotation(self) -> None:
- assert _provider_down_phrase("en", 1, "weird_kind") == (
- _PROVIDER_DOWN_PHRASES["en"][1]
- )
+ assert _provider_down_phrase("en", 1, "weird_kind") == (_PROVIDER_DOWN_PHRASES["en"][1])
def test_unknown_language_falls_back_to_german_cause_phrase(self) -> None:
from jarvis.brain.manager import _PROVIDER_DOWN_CAUSE_PHRASES
@@ -151,18 +165,12 @@ class TestPrimaryProviderDownCause:
def test_skipped_cooldown_reads_as_rate_limit(self) -> None:
from jarvis.brain.manager import _primary_provider_down_cause
- assert (
- _primary_provider_down_cause([self._err("skipped_cooldown")])
- == "rate_limit"
- )
+ assert _primary_provider_down_cause([self._err("skipped_cooldown")]) == "rate_limit"
def test_unclassified_failure_reads_as_unreachable(self) -> None:
from jarvis.brain.manager import _primary_provider_down_cause
- assert (
- _primary_provider_down_cause([self._err("network_error")])
- == "unreachable"
- )
+ assert _primary_provider_down_cause([self._err("network_error")]) == "unreachable"
def test_empty_response_only_keeps_generic_phrase(self) -> None:
from jarvis.brain.manager import _primary_provider_down_cause
@@ -174,3 +182,21 @@ class TestPrimaryProviderDownCause:
assert _primary_provider_down_cause([]) is None
assert _primary_provider_down_cause(None) is None
+
+ def test_vision_unsupported_is_not_heard_as_a_missing_key(self) -> None:
+ from jarvis.brain.manager import (
+ _PROVIDER_DOWN_CAUSE_PHRASES,
+ _primary_provider_down_cause,
+ _provider_down_phrase,
+ )
+
+ errors = [self._err("vision_unsupported", "grok")]
+ assert _primary_provider_down_cause(errors) == "vision_unsupported"
+ phrase = _provider_down_phrase("de", 0, "vision_unsupported")
+ assert phrase == _PROVIDER_DOWN_CAUSE_PHRASES["vision_unsupported"]["de"]
+ low = phrase.lower()
+ assert "schlüssel" in low or "schluessel" in low # i18n-allow: the honest cause
+ assert "kein" in low # i18n-allow: quoted German spoken phrase
+ # Must not collapse onto the missing-key sentence (the API-Keys card
+ # was green; the model simply cannot inspect images).
+ assert "kein api-schlüssel hinterlegt" not in low # i18n-allow
diff --git a/tests/unit/platform/test_capture_exclusion.py b/tests/unit/platform/test_capture_exclusion.py
new file mode 100644
index 0000000000..e1364127d4
--- /dev/null
+++ b/tests/unit/platform/test_capture_exclusion.py
@@ -0,0 +1,48 @@
+"""Overlay windows must be omitted from screenshots (WDA / NSWindowSharingNone)."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import jarvis.platform.capture_exclusion as exclusion
+
+
+class _FakeUser32:
+ def __init__(self) -> None:
+ self.affinity: list[tuple[int, int]] = []
+ self.parent_of: dict[int, int] = {}
+
+ def GetParent(self, hwnd: int) -> int: # noqa: N802
+ return self.parent_of.get(hwnd, 0)
+
+ def SetWindowDisplayAffinity(self, hwnd: int, affinity: int) -> bool: # noqa: N802
+ self.affinity.append((int(hwnd), int(affinity)))
+ return True
+
+
+def test_exclude_hwnd_is_a_quiet_noop_off_windows(monkeypatch) -> None:
+ monkeypatch.setattr(exclusion.sys, "platform", "linux")
+ assert exclusion.exclude_hwnd_from_capture(0x1234) is False
+
+
+def test_exclude_hwnd_sets_wda_exclude_from_capture(monkeypatch) -> None:
+ fake = _FakeUser32()
+ monkeypatch.setattr(exclusion.sys, "platform", "win32")
+ monkeypatch.setattr(exclusion, "_user32", lambda: fake)
+ assert exclusion.exclude_hwnd_from_capture(0xABCD) is True
+ assert fake.affinity == [(0xABCD, 0x00000011)] # WDA_EXCLUDEFROMCAPTURE
+
+
+def test_exclude_tk_window_targets_the_outer_toplevel(monkeypatch) -> None:
+ fake = _FakeUser32()
+ fake.parent_of[0x1111] = 0x2222
+ monkeypatch.setattr(exclusion.sys, "platform", "win32")
+ monkeypatch.setattr(exclusion, "_user32", lambda: fake)
+ root = SimpleNamespace(winfo_id=lambda: 0x1111)
+ assert exclusion.exclude_tk_window_from_capture(root) is True
+ assert fake.affinity == [(0x2222, 0x00000011)]
+
+
+def test_exclude_tk_window_survives_a_root_without_winfo_id() -> None:
+ assert exclusion.exclude_tk_window_from_capture(object()) is False
+ assert exclusion.exclude_tk_window_from_capture(None) is False
diff --git a/tests/unit/platform/test_win32_ctypes_bindings.py b/tests/unit/platform/test_win32_ctypes_bindings.py
index d0b75a2165..f68bc2d2df 100644
--- a/tests/unit/platform/test_win32_ctypes_bindings.py
+++ b/tests/unit/platform/test_win32_ctypes_bindings.py
@@ -5,6 +5,7 @@ from ctypes import wintypes
from types import SimpleNamespace
from jarvis.cu.indicator.win32 import _configure_user32 as configure_indicator_api
+from jarvis.platform.capture_exclusion import _configure_user32 as configure_exclusion_api
from jarvis.platform.window_state import _configure_window_query_api
@@ -44,9 +45,7 @@ def test_window_query_bindings_preserve_pointer_sized_hwnds() -> None:
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
- )
+ assert ctypes.sizeof(user32.GetWindowRect.argtypes[0]) == ctypes.sizeof(ctypes.c_void_p)
def test_indicator_bindings_preserve_pointer_sized_hwnds() -> None:
@@ -60,6 +59,20 @@ def test_indicator_bindings_preserve_pointer_sized_hwnds() -> None:
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(
+ assert ctypes.sizeof(user32.GetWindowLongW.argtypes[0]) == ctypes.sizeof(ctypes.c_void_p)
+
+
+def test_capture_exclusion_bindings_preserve_pointer_sized_hwnds() -> None:
+ user32 = _api(
+ "GetParent",
+ "SetWindowDisplayAffinity",
+ )
+
+ configure_exclusion_api(user32, ctypes, wintypes)
+
+ assert user32.GetParent.argtypes[0] is wintypes.HWND
+ assert user32.GetParent.restype is wintypes.HWND
+ assert user32.SetWindowDisplayAffinity.argtypes[0] is wintypes.HWND
+ assert ctypes.sizeof(user32.SetWindowDisplayAffinity.argtypes[0]) == ctypes.sizeof(
ctypes.c_void_p
)
diff --git a/tests/unit/test_api_key_error_handling.py b/tests/unit/test_api_key_error_handling.py
index 78028ad11c..b5f55322fb 100644
--- a/tests/unit/test_api_key_error_handling.py
+++ b/tests/unit/test_api_key_error_handling.py
@@ -13,6 +13,7 @@ Drei zusammenhaengende Defekte gefixt:
3. _format_provider_chain_error — User-actionable Account-Block-Message
statt "Provider unerreichbar"-Halluzination.
"""
+
from __future__ import annotations
from jarvis.brain.manager import (
@@ -32,6 +33,7 @@ from jarvis.plugins.brain.gemini import (
# ---- 1. Gemini-Schema-Sanitizer ----------------------------------------
+
class TestGeminiSchemaSanitize:
def test_strips_strict_at_root(self) -> None:
schema = {"type": "object", "strict": True, "properties": {}}
@@ -206,8 +208,7 @@ class TestGeminiSdkAcceptsSanitizedSchema:
"input_schema": {
"type": "object",
"properties": {
- "size": {"type": "integer", "exclusiveMinimum": 0,
- "title": "Size"},
+ "size": {"type": "integer", "exclusiveMinimum": 0, "title": "Size"},
"ratio": {"type": "number", "exclusiveMaximum": 10},
},
"required": ["size"],
@@ -273,6 +274,7 @@ class TestGeminiFunctionNameSanitize:
def test_collision_on_overlong_base_stays_valid_and_distinct(self) -> None:
import re
+
rx = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$")
taken: set[str] = set()
first = _sanitize_gemini_function_name("a" * 400, taken)
@@ -306,11 +308,13 @@ class TestGeminiFunctionNameSanitize:
assert m1["wiki-recall"] == "wiki-recall"
# every sanitized name is Gemini-valid
import re
+
rx = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$")
assert all(rx.match(v) for v in m1.values())
def test_tools_format_emits_only_valid_names(self) -> None:
import re
+
rx = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$")
tools = (
{"name": "Spotify: play track", "description": "d", "input_schema": {}},
@@ -332,8 +336,11 @@ class TestGeminiFunctionNameSanitize:
pytest.skip("google-genai SDK not installed")
tools = tuple(
- {"name": f"plugin {i}/do something!", "description": "d",
- "input_schema": {"type": "object", "properties": {}}}
+ {
+ "name": f"plugin {i}/do something!",
+ "description": "d",
+ "input_schema": {"type": "object", "properties": {}},
+ }
for i in range(40)
)
payload = _tools_gemini_format(tools)
@@ -343,18 +350,23 @@ class TestGeminiFunctionNameSanitize:
# ---- 2. _is_account_blocked_exc ---------------------------------------
+
class TestAccountBlocked:
def test_anthropic_credit_too_low(self) -> None:
- msg = ("Error code: 400 - {'type': 'error', 'error': {"
- "'message': 'Your credit balance is too low to access "
- "the Anthropic API. Please go to Plans & Billing.'}}")
+ msg = (
+ "Error code: 400 - {'type': 'error', 'error': {"
+ "'message': 'Your credit balance is too low to access "
+ "the Anthropic API. Please go to Plans & Billing.'}}"
+ )
assert _is_account_blocked_exc(msg)
assert _classify_provider_error(msg, default="call_fail") == "account_blocked"
def test_xai_team_does_not_have_access(self) -> None:
- msg = ("Error code: 404 - {'code': 'Some requested entity was not "
- "found', 'error': 'The model grok-4.1-fast does not exist or "
- "your team does not have access to it.'}")
+ msg = (
+ "Error code: 404 - {'code': 'Some requested entity was not "
+ "found', 'error': 'The model grok-4.1-fast does not exist or "
+ "your team does not have access to it.'}"
+ )
assert _is_account_blocked_exc(msg)
# Becomes account_blocked, not invalid_model — important for the user message.
assert _classify_provider_error(msg, default="call_fail") == "account_blocked"
@@ -377,11 +389,11 @@ class TestAccountBlocked:
# ---- 3. _format_provider_chain_error ----------------------------------
+
class TestChainErrorFormat:
def test_account_blocked_message_user_actionable(self) -> None:
errors = [
- ("claude-api", "claude-haiku-4-5", "account_blocked",
- "credit balance too low"),
+ ("claude-api", "claude-haiku-4-5", "account_blocked", "credit balance too low"),
]
msg = _format_provider_chain_error(errors)
assert "Account-Problem" in msg
@@ -409,3 +421,12 @@ class TestChainErrorFormat:
# Both areas are addressed
assert "Brain-Key" in msg or "missing" in msg.lower()
assert "Account-Problem" in msg
+
+ def test_vision_unsupported_is_not_reported_as_a_missing_key(self) -> None:
+ errors = [
+ ("grok", "grok-4.3", "vision_unsupported", "vision unsupported"),
+ ]
+ msg = _format_provider_chain_error(errors)
+ assert "Bildverstehen" in msg # i18n-allow: developer diagnostic
+ assert "Kein Brain-Key gefunden" not in msg # i18n-allow: quoted German diagnostic
+ assert "grok" in msg
diff --git a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
index 7f7f123ebc..b63ae61ad3 100644
--- a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
+++ b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
@@ -171,6 +171,24 @@ def test_explicit_z_order_reassert_repins_an_already_mapped_window(
assert root.attrs.get("-transparentcolor") == COLOR_KEY_HEX
+def test_z_order_reassert_excludes_the_bar_from_screenshots(monkeypatch) -> None:
+ """The last transcription bubble / bar must not appear in a screenshot.
+
+ Live 2026-08-31: only the Computer-Use indicator used
+ WDA_EXCLUDEFROMCAPTURE, so a screen look photographed the overlay
+ showing the previous utterance.
+ """
+ seen: list[object] = []
+ monkeypatch.setattr(
+ overlay_module,
+ "_exclude_tk_window_from_capture",
+ lambda root: seen.append(root) or True,
+ )
+ bar, root = _bar_with_fake_root(mapped=True)
+ bar._do_reassert_z_order() # noqa: SLF001
+ assert seen == [root]
+
+
def test_win32_native_pin_targets_toplevel_parent_without_activation() -> None:
root = _FakeNativeRoot()
user32 = _FakeUser32()
diff --git a/ui/orb/overlay.py b/ui/orb/overlay.py
index bdb5c987a3..77d429096a 100644
--- a/ui/orb/overlay.py
+++ b/ui/orb/overlay.py
@@ -306,6 +306,11 @@ def apply_macos_clear_backing() -> None:
win.setOpaque_(False)
win.setBackgroundColor_(NSColor.clearColor())
win.setHasShadow_(False)
+ from jarvis.platform.capture_exclusion import ( # noqa: PLC0415
+ exclude_macos_app_windows,
+ )
+
+ exclude_macos_app_windows()
orb_log.debug("macOS clear-backing applied to %d window(s)", len(wins))
except Exception: # noqa: BLE001 — cosmetic; the grey box is the degrade
orb_log.warning("macOS clear-backing pass failed", exc_info=True)
@@ -499,6 +504,18 @@ def _hide_tk_window_from_task_switcher(root: tk.Tk) -> None:
return
+def _exclude_tk_window_from_capture(root: tk.Tk) -> None:
+ """Keep the orb / transcription bubble out of screenshots. Best-effort."""
+ try:
+ from jarvis.platform.capture_exclusion import ( # noqa: PLC0415
+ exclude_tk_window_from_capture,
+ )
+
+ exclude_tk_window_from_capture(root)
+ except Exception: # noqa: BLE001 — overlay must degrade, never crash
+ return
+
+
class MascotRenderer:
"""Renderer for the SWG/Gigi mascot.
@@ -1206,6 +1223,7 @@ class OrbCommentBubble:
top.wm_attributes("-transparentcolor", COLOR_KEY_HEX)
top.configure(bg=COLOR_KEY_HEX)
_hide_tk_window_from_task_switcher(top)
+ _exclude_tk_window_from_capture(top)
top.withdraw()
canvas = tk.Canvas(
@@ -1663,6 +1681,7 @@ class OrbControlRow:
top.wm_attributes("-transparentcolor", COLOR_KEY_HEX)
top.configure(bg=COLOR_KEY_HEX)
_hide_tk_window_from_task_switcher(top)
+ _exclude_tk_window_from_capture(top)
top.withdraw()
canvas = tk.Canvas(
@@ -2070,6 +2089,7 @@ class OrbOverlay:
# way to override the class-default that drives the taskbar icon).
_apply_jarvis_icon_to_tk_root(self._root)
_hide_tk_window_from_task_switcher(self._root)
+ _exclude_tk_window_from_capture(self._root)
# Resolve mascot anchor. If the user has manually pinned the orb
# in a prior session, restore that position; otherwise compute