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(cu): address review findings — window-precise macOS signature with gated re-baseline, BFS AX walk, localized open_app readbacks

Personal Jarvis Maintainer51cc28875c3a
diff --git a/jarvis/cu/actuate/base.py b/jarvis/cu/actuate/base.py
index aaba08a5bb..72077a3211 100644
--- a/jarvis/cu/actuate/base.py
+++ b/jarvis/cu/actuate/base.py
@@ -18,6 +18,7 @@ import abc
import logging
import os
import sys
+import threading
from collections.abc import Callable
from dataclasses import dataclass
@@ -391,9 +392,12 @@ def _require_macos_input_permissions() -> None:
#: Process-wide backend instance. Building a PosixActuator constructs pynput
#: Controllers (keycode tables, layout snapshot) — doing that once per ACTION
-#: was pure per-click overhead. The desktop lock serializes missions, and the
-#: backends hold no per-action state, so one instance serves the process.
+#: was pure per-click overhead. The backends hold no per-action state; the
+#: lock only guards the cache check-and-set (CU missions are additionally
+#: serialized by the harness desktop lock, but the flat click/type/scroll
+#: tools can call this from any worker thread).
_ACTUATOR_CACHE: Actuator | None = None
+_ACTUATOR_CACHE_LOCK = threading.Lock()
def get_actuator() -> Actuator:
@@ -411,9 +415,10 @@ def get_actuator() -> Actuator:
if os.name == "nt":
from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415
- if not isinstance(_ACTUATOR_CACHE, WindowsActuator):
- _ACTUATOR_CACHE = WindowsActuator()
- return _ACTUATOR_CACHE
+ with _ACTUATOR_CACHE_LOCK:
+ if not isinstance(_ACTUATOR_CACHE, WindowsActuator):
+ _ACTUATOR_CACHE = WindowsActuator()
+ return _ACTUATOR_CACHE
from jarvis.platform.probes import display_present, is_wayland # noqa: PLC0415
@@ -425,17 +430,19 @@ def get_actuator() -> Actuator:
from jarvis.cu.actuate.posix import PosixActuator # noqa: PLC0415
- if isinstance(_ACTUATOR_CACHE, PosixActuator):
- return _ACTUATOR_CACHE
- try:
- actuator = PosixActuator()
- except ActuationUnavailable:
- raise
- except Exception as exc: # noqa: BLE001 — import/init of pynput/pyautogui
- raise ActuationUnavailable(f"{_NO_BACKEND_MSG} ({exc})") from exc
- # Only the full pynput backend is retained: a pyautogui-fallback instance
- # (e.g. the keyboard-layout cache was not primed yet at first use) must
- # keep retrying pynput on later actions instead of being frozen in.
- if actuator.name == "posix-pynput":
- _ACTUATOR_CACHE = actuator
- return actuator
+ with _ACTUATOR_CACHE_LOCK:
+ if isinstance(_ACTUATOR_CACHE, PosixActuator):
+ return _ACTUATOR_CACHE
+ try:
+ actuator = PosixActuator()
+ except ActuationUnavailable:
+ raise
+ except Exception as exc: # noqa: BLE001 — import/init of pynput/pyautogui
+ raise ActuationUnavailable(f"{_NO_BACKEND_MSG} ({exc})") from exc
+ # Only the full pynput backend is retained: a pyautogui-fallback
+ # instance (e.g. the keyboard-layout cache was not primed yet at
+ # first use) must keep retrying pynput on later actions instead of
+ # being frozen in.
+ if actuator.name == "posix-pynput":
+ _ACTUATOR_CACHE = actuator
+ return actuator
diff --git a/jarvis/cu/engine.py b/jarvis/cu/engine.py
index 193ecff162..d77ba21637 100644
--- a/jarvis/cu/engine.py
+++ b/jarvis/cu/engine.py
@@ -64,8 +64,9 @@ from jarvis.cu.geometry import (
)
from jarvis.cu.ledger import ActionLedger
from jarvis.cu.target_guard import (
- foreground_matches,
+ foreground_matches_or_same_app,
read_foreground_target,
+ signatures_same_app,
window_signature,
)
from jarvis.cu.verify import (
@@ -336,6 +337,18 @@ async def _live_window_state_signature() -> tuple[Any, ...]:
return (await asyncio.to_thread(read_foreground_target)).signature
+def _signature_still_valid(
+ live: tuple[Any, ...], expected: tuple[Any, ...],
+) -> bool:
+ """Post-action signature re-check: exact match or same-app churn.
+
+ Used only where an action of ours ALREADY ran (zoom-refine after a
+ verified click): the click may legitimately have flipped the frontmost
+ same-app window (macOS dropdown/sheet). A cross-app change still fails.
+ """
+ return live == expected or signatures_same_app(expected, live)
+
+
async def _dispatch_tool(
ctx: Any, tool_name: str, args: dict[str, Any], trace_id: Any,
) -> tuple[bool, str]:
@@ -459,13 +472,14 @@ async def _zoom_refine_point(
import json as _json # noqa: PLC0415
import re as _re # noqa: PLC0415
- if await _live_window_state_signature() != expected_window_signature:
+ if not _signature_still_valid(
+ await _live_window_state_signature(), expected_window_signature,
+ ):
return None
bbox = frame.mapper.region_around(int(x), int(y), _REFINE_RADIUS)
raw = await asyncio.to_thread(grab_region, bbox)
- if (
- raw is None
- or await _live_window_state_signature() != expected_window_signature
+ if raw is None or not _signature_still_valid(
+ await _live_window_state_signature(), expected_window_signature,
):
return None
try:
@@ -497,7 +511,9 @@ async def _zoom_refine_point(
except Exception: # noqa: BLE001 — refine is strictly best-effort
log.debug("[cu] zoom refine call failed", exc_info=True)
return None
- if await _live_window_state_signature() != expected_window_signature:
+ if not _signature_still_valid(
+ await _live_window_state_signature(), expected_window_signature,
+ ):
return None
cleaned = (reply.text or "").strip()
fence = _re.search(r"```(?:json)?\s*(.+?)\s*```", cleaned, _re.DOTALL)
@@ -697,7 +713,12 @@ async def run_cu_loop(
def capture_identity_guard(
expected: tuple[Any, ...] = pre_capture_window_signature,
) -> bool:
- return foreground_matches(expected)
+ # Same-app tolerant: a dropdown/sheet flipping the frontmost
+ # layer-0 window mid-grab (macOS) does not invalidate the
+ # capture — the stability loop delivers the settled frame and
+ # the ACTION baseline is re-read after capture anyway. Only a
+ # cross-app takeover aborts the observation.
+ return foreground_matches_or_same_app(expected)
monitor = await asyncio.to_thread(
select_capture_target,
@@ -736,7 +757,11 @@ async def run_cu_loop(
"foreground window identity is unavailable; refusing "
"unbound Computer-Use input"
)
- if captured_window_signature != pre_capture_window_signature:
+ if captured_window_signature != pre_capture_window_signature and not (
+ signatures_same_app(
+ pre_capture_window_signature, captured_window_signature,
+ )
+ ):
raise RuntimeError(
"foreground window changed during capture; retrying with a fresh frame"
)
@@ -927,6 +952,11 @@ async def run_cu_loop(
# ---- act + verify ---------------------------------------------------
pointer_used = False
batch_acted = False # any executed action invalidates the step frame
+ # Whether an input action of THIS batch already executed successfully.
+ # Gates the same-app re-baseline below: before the first action the
+ # foreground must still be exactly the captured window; after our own
+ # action, same-app churn (a dropdown our click opened) is expected.
+ acted_since_capture = False
for action in actions:
if _is_cancelled(cancel_token):
yield _final(stderr="[cu] cancelled\n", exit_code=_EXIT_CANCEL)
@@ -1078,16 +1108,35 @@ async def run_cu_loop(
break # re-perceive
if kind in {"click", "click_element", "drag", "scroll", "type", "key"}:
- if await _live_window_state_signature() != captured_window_signature:
- msg = (
- f"step {step_idx}: {_summarize_action(action)} REFUSED — "
- "the foreground window changed after the screenshot; "
- "capturing a fresh frame before acting."
- )
- history.append(msg)
- log.info("[cu] %s", msg)
- yield _progress(f"[cu] {msg}")
- break
+ live_signature = await _live_window_state_signature()
+ if live_signature != captured_window_signature:
+ if acted_since_capture and signatures_same_app(
+ captured_window_signature, live_signature,
+ ):
+ # Same app, different frontmost window, AFTER one of
+ # our own actions: the expected consequence of that
+ # action (macOS: a click into the address bar makes
+ # the suggestions dropdown the frontmost layer-0
+ # window). Refusing here broke every click->type
+ # batch (live incident 2026-07-20). Re-baseline so
+ # the rest of the batch lands where the model
+ # intended; a CROSS-APP steal still breaks the batch,
+ # and before the FIRST action the check stays strict.
+ log.debug(
+ "[cu] same-app foreground churn after own action "
+ "— re-baselining window signature",
+ )
+ captured_window_signature = live_signature
+ else:
+ msg = (
+ f"step {step_idx}: {_summarize_action(action)} REFUSED — "
+ "the foreground window changed after the screenshot; "
+ "capturing a fresh frame before acting."
+ )
+ history.append(msg)
+ log.info("[cu] %s", msg)
+ yield _progress(f"[cu] {msg}")
+ break
# -- execute ------------------------------------------------------
t0 = time.monotonic()
@@ -1176,8 +1225,10 @@ async def run_cu_loop(
grab_region, monitor.bbox,
)
if (
- await _live_window_state_signature()
- != captured_window_signature
+ not _signature_still_valid(
+ await _live_window_state_signature(),
+ captured_window_signature,
+ )
or monitor_topology_signature(
await asyncio.to_thread(list_monitors),
)
@@ -1415,6 +1466,8 @@ async def run_cu_loop(
batch_acted = True
summary = _summarize_action(action)
if ok:
+ if kind != "wait":
+ acted_since_capture = True
consecutive_failures = 0
last_step_had_success = True
history.append(
diff --git a/jarvis/cu/target_guard.py b/jarvis/cu/target_guard.py
index bea153c35e..51f4531d3a 100644
--- a/jarvis/cu/target_guard.py
+++ b/jarvis/cu/target_guard.py
@@ -22,17 +22,16 @@ def window_signature(
return ("none",)
pid = getattr(window, "pid", None)
if pid:
- # App-level identity. Only the macOS foreground probe fills ``pid``:
- # there the per-window handle is the CGWindowID of the frontmost
- # layer-0 window, which churns on focus changes INSIDE the same app
- # (an address-bar suggestions dropdown is its own layer-0 window, and
- # frame rects move with it). Comparing on the owning app keeps the
- # guard's purpose — catching a cross-app focus steal between the
- # screenshot and the action — without refusing every click->type
- # batch (live incident 2026-07-20: 9 REFUSED actions in two runs).
- # Windows/Linux probes leave ``pid`` unset and keep the stable
- # per-window handle+rect identity.
- return ("app", int(pid))
+ # Only the macOS foreground probe fills ``pid``. The signature stays
+ # WINDOW-precise (CGWindowID + rect), but leads with the owning app
+ # so callers can distinguish "a different window of the SAME app took
+ # over" (focus churn our own click caused — an address-bar
+ # suggestions dropdown is its own layer-0 window with its own rect,
+ # live incident 2026-07-20) from a cross-app focus steal, via
+ # :func:`signatures_same_app`. Windows/Linux probes leave ``pid``
+ # unset and keep their stable per-window handle+rect identity.
+ handle = getattr(window, "handle", None)
+ return ("app", int(pid), int(handle) if handle else None, rect)
handle = getattr(window, "handle", None)
if handle:
return ("handle", int(handle), rect)
@@ -68,3 +67,38 @@ def foreground_matches(expected: tuple[Any, ...]) -> bool:
return bool(expected) and expected[0] != "none" and (
foreground_signature() == expected
)
+
+
+def signatures_same_app(
+ a: tuple[Any, ...], b: tuple[Any, ...],
+) -> bool:
+ """Whether two signatures identify windows of the SAME owning app.
+
+ Only macOS signatures carry an app identity (``("app", pid, ...)``);
+ Windows/Linux signatures return ``False`` here, so every same-app
+ relaxation is a structural no-op on those platforms — their per-window
+ hwnd/X11-id identity is stable and needs no tolerance.
+ """
+ return (
+ len(a) >= 2
+ and len(b) >= 2
+ and a[0] == "app"
+ and b[0] == "app"
+ and a[1] == b[1]
+ )
+
+
+def foreground_matches_or_same_app(expected: tuple[Any, ...]) -> bool:
+ """Strict signature match, tolerating same-app window churn (macOS).
+
+ The tolerant matcher for RE-checks that run after the engine's strict
+ per-frame baseline: on macOS the frontmost layer-0 window flips whenever
+ a dropdown/sheet/popover opens — usually as the direct consequence of
+ the action we just executed — and a strict equality re-check
+ milliseconds later would refuse the rest of a legitimate batch. A
+ cross-app focus steal still mismatches.
+ """
+ if not expected or expected[0] == "none":
+ return False
+ current = foreground_signature()
+ return current == expected or signatures_same_app(expected, current)
diff --git a/jarvis/plugins/tool/click.py b/jarvis/plugins/tool/click.py
index 61ede73642..7cb10c71ff 100644
--- a/jarvis/plugins/tool/click.py
+++ b/jarvis/plugins/tool/click.py
@@ -27,7 +27,10 @@ from jarvis.cu.actuate.windows import (
from jarvis.cu.actuate.windows import (
normalize_virtualdesk as _normalize_virtualdesk, # noqa: F401 — re-export (tests + callers)
)
-from jarvis.cu.target_guard import foreground_matches, foreground_signature
+from jarvis.cu.target_guard import (
+ foreground_matches_or_same_app,
+ foreground_signature,
+)
from jarvis.overlay.virtual_cursor import get_virtual_cursor
@@ -36,7 +39,10 @@ def _foreground_window_signature() -> tuple[Any, ...]:
def _window_signature_matches(expected: tuple[Any, ...]) -> bool:
- return foreground_matches(expected)
+ # Same-app tolerant (macOS): the engine holds the strict per-frame
+ # baseline; this later re-check must not refuse a batch because our own
+ # click just made a dropdown/sheet the frontmost same-app window.
+ return foreground_matches_or_same_app(expected)
def _send_click(button: str, double: bool, abs_xy: tuple[int, int] | None = None) -> None:
diff --git a/jarvis/plugins/tool/hotkey.py b/jarvis/plugins/tool/hotkey.py
index 62cbf4b5ce..90b8656c01 100644
--- a/jarvis/plugins/tool/hotkey.py
+++ b/jarvis/plugins/tool/hotkey.py
@@ -38,9 +38,11 @@ def _send_for_expected_window(
expected_signature: tuple[Any, ...] | None,
) -> None:
if expected_signature is not None:
- from jarvis.cu.target_guard import foreground_matches # noqa: PLC0415
+ from jarvis.cu.target_guard import ( # noqa: PLC0415
+ foreground_matches_or_same_app,
+ )
- if not foreground_matches(expected_signature):
+ if not foreground_matches_or_same_app(expected_signature):
raise _ForegroundTargetChanged(
"foreground window changed after the screenshot"
)
diff --git a/jarvis/plugins/tool/open_app.py b/jarvis/plugins/tool/open_app.py
index 0bd9aad9a2..98e593f7a1 100644
--- a/jarvis/plugins/tool/open_app.py
+++ b/jarvis/plugins/tool/open_app.py
@@ -1,11 +1,11 @@
-"""open_app-Tool: öffnet eine Windows-Anwendung.
+"""open_app tool: opens an application, file, or URL on this computer.
-Risk-Tier: monitor — schreibt Toast-Notification, läuft aber ohne Approval.
+Risk tier: monitor — emits a toast notification but runs without approval.
-Plausibility-Check (2026-04-24): vor dem OS-Call wird app_name gegen Regex
-+ Whitelist/PATH geprueft. Blockiert STT-Halluzinationen wie
-"WDR mediagroup GmbH im Auftrag des WDR, 2020" die sonst direkt in
-os.startfile landen wuerden.
+Plausibility check (2026-04-24): before the OS call, app_name is vetted
+against a regex + whitelist/PATH/OS-app-registry. Blocks STT hallucinations
+like "WDR mediagroup GmbH im Auftrag des WDR, 2020" that would otherwise
+land directly in os.startfile.
"""
from __future__ import annotations
@@ -24,6 +24,7 @@ from jarvis.plugins.tool.app_resolver import (
launch_services_can_open,
resolve_app_launch_target,
)
+from jarvis.voice.action_phrases import action_phrase, resolve_phrase_language
# Apps for which a second window is normal/expected — never short-circuit these
# to "already running -> focus"; the user almost always wants a fresh instance.
@@ -32,8 +33,8 @@ _MULTI_INSTANCE_APPS: frozenset[str] = frozenset({
"terminal", "conhost", "gnome-terminal", "konsole", "xterm",
})
-# Bekannte Apps + haeufige Aliases. Reicht fuer 95% der Voice-Commands;
-# exotische Apps laufen ueber PATH-Resolve oder expliziten Pfad.
+# Known apps + common aliases. Covers ~95% of voice commands;
+# exotic apps go through PATH resolution or an explicit path.
#
# The whitelist is platform-conditional (AD-15): it keeps the anti-STT-
# hallucination gate intact with the correct per-OS names. The plausibility
@@ -49,14 +50,14 @@ _KNOWN_APPS_WIN: frozenset[str] = frozenset({
# Dev
"code", "vscode", "pycharm", "idea", "webstorm", "clion", "rider",
"cursor", "windsurf", "zed",
- # Kommunikation
+ # Communication
"outlook", "teams", "slack", "discord", "telegram", "whatsapp", "signal",
"zoom", "skype",
# Media
"spotify", "vlc", "mpv", "potplayer", "obs", "obs64",
# Office
"word", "excel", "powerpoint", "onenote", "winword", "excel.exe",
- # Grafik
+ # Graphics
"mspaint", "paint", "photoshop", "illustrator", "figma", "gimp", "inkscape",
# Gaming / Misc
"steam", "epicgameslauncher", "battle.net", "blender",
@@ -64,7 +65,7 @@ _KNOWN_APPS_WIN: frozenset[str] = frozenset({
# resolver, see app_resolver._UWP_PROTOCOLS). Whitelisted so the
# plausibility gate does not reject them as "not found" (live 2026-06-22).
"microsoft store", "windows store", "store",
- # Jarvis-intern
+ # Jarvis itself
"jarvis",
})
@@ -78,18 +79,18 @@ _KNOWN_APPS_DARWIN: frozenset[str] = frozenset({
# Dev
"code", "vscode", "pycharm", "idea", "webstorm", "clion", "rider",
"cursor", "windsurf", "zed", "xcode",
- # Kommunikation
+ # Communication
"mail", "messages", "facetime", "teams", "slack", "discord", "telegram",
"whatsapp", "signal", "zoom", "skype",
# Media
"music", "spotify", "vlc", "mpv", "quicktime player", "obs",
# Office
"pages", "numbers", "keynote", "word", "excel", "powerpoint", "onenote",
- # Grafik
+ # Graphics
"photos", "photoshop", "illustrator", "figma", "gimp", "inkscape",
# Misc
"steam", "blender",
- # Jarvis-intern
+ # Jarvis itself
"jarvis",
})
@@ -104,7 +105,7 @@ _KNOWN_APPS_LINUX: frozenset[str] = frozenset({
# Dev
"code", "vscode", "pycharm", "idea", "webstorm", "clion", "rider",
"cursor", "windsurf", "zed",
- # Kommunikation
+ # Communication
"thunderbird", "evolution", "teams", "slack", "discord", "telegram",
"telegram-desktop", "signal", "signal-desktop", "zoom", "skype",
# Media
@@ -112,11 +113,11 @@ _KNOWN_APPS_LINUX: frozenset[str] = frozenset({
# Office
"libreoffice", "libreoffice-writer", "libreoffice-calc",
"libreoffice-impress", "onlyoffice",
- # Grafik
+ # Graphics
"eog", "gimp", "inkscape", "krita", "blender",
# Misc
"steam", "nautilus-desktop",
- # Jarvis-intern
+ # Jarvis itself
"jarvis",
})
@@ -135,16 +136,16 @@ def _select_known_apps() -> frozenset[str]:
# jarvis.plugins.tool.open_app import KNOWN_APPS`).
KNOWN_APPS: frozenset[str] = _select_known_apps()
-# Regex gegen offensichtlich kaputte app_names:
-# - Max 60 Zeichen
-# - Nur Woerter + Pfad-Zeichen + URL-Schema-Zeichen erlaubt
-# - Keine Komma-Listen oder Satzzeichen-Ketten
+# Regex against obviously broken app_names:
+# - max 60 characters
+# - only word, path, and URL-scheme characters allowed
+# - no comma lists or punctuation chains
_APP_NAME_RE = re.compile(r"^[\w\-\.\:\/\\ ]{1,60}$")
-# STT-Halluzinations-Marker die auf Whisper-Misshearings hindeuten (Werbe-
-# Outros, Copyright-Strings). Doppelter Schutz zusaetzlich zum Pipeline-
-# Level-Guard, falls das Brain direkt aus einem System-Kontext aufgerufen
-# wird (z.B. Text-Chat in der Desktop-App).
+# STT-hallucination markers that indicate Whisper mishearings (advertising
+# outros, copyright strings). Second line of defense in addition to the
+# pipeline-level guard, for when the brain is called directly from a system
+# context (e.g. text chat in the desktop app).
_HALLUCINATION_RE = re.compile(
r"\b("
r"im\s+auftrag\s+des|mediagroup|gmbh|"
@@ -155,6 +156,21 @@ _HALLUCINATION_RE = re.compile(
)
+def _output_language(ctx: ExecutionContext) -> str:
+ """Turn language for the deterministic launch readbacks (de/en/es).
+
+ Prefers the resolved output language the tool-use loop stamps into
+ ``ctx.config`` (honors the ``brain.reply_language`` pin + conversation
+ stickiness); falls back to detecting the user's own words — the same
+ contract as the other deterministic local-action readbacks.
+ """
+ config = getattr(ctx, "config", None)
+ stamped = config.get("output_language") if isinstance(config, dict) else None
+ if stamped:
+ return str(stamped)
+ return resolve_phrase_language(None, ctx.user_utterance)
+
+
def _is_plausible_app_name(app_name: str) -> tuple[bool, str, str]:
"""Check whether ``app_name`` is plausible.
@@ -173,7 +189,7 @@ def _is_plausible_app_name(app_name: str) -> tuple[bool, str, str]:
"misheard",
)
- # Layer 2: Whitelist ODER URL ODER Pfad ODER PATH-Resolve
+ # Layer 2: whitelist OR URL OR path OR PATH resolution
low = app_name.lower().removesuffix(".exe")
is_url = app_name.startswith(("http://", "https://", "file://"))
is_path = (
@@ -249,7 +265,10 @@ class OpenAppTool:
if not app_name:
return ToolResult(success=False, output=None, error="app_name is missing")
- ok, reason, kind = _is_plausible_app_name(app_name)
+ # Off the event loop: the gate's layer-3 registry probes block (a
+ # subprocess `open -Ra` on macOS, .desktop globs on Linux) and would
+ # otherwise stall voice/WS dispatch for seconds.
+ ok, reason, kind = await asyncio.to_thread(_is_plausible_app_name, app_name)
if not ok:
# Error message with an explicit instruction to the brain,
# differentiated by rejection kind — a plausible but simply
@@ -369,17 +388,20 @@ class OpenAppTool:
)
except Exception: # noqa: BLE001 — never fail a successful launch
raised = False
- output = (
- f"Gestartet und nach vorn geholt: {app_name}"
- if raised
- else f"Gestartet: {app_name}"
+ lang = _output_language(ctx)
+ output = action_phrase(
+ "open_app_launched_raised" if raised else "open_app_launched",
+ lang,
+ app=app_name,
)
return ToolResult(success=True, output=output)
except FileNotFoundError:
return ToolResult(
success=False,
output=None,
- error=f"Anwendung '{app_name}' nicht gefunden.",
+ error=action_phrase(
+ "open_app_not_found", _output_language(ctx), app=app_name,
+ ),
)
except OSError as exc:
return ToolResult(success=False, output=None, error=str(exc))
diff --git a/jarvis/plugins/tool/scroll.py b/jarvis/plugins/tool/scroll.py
index a4ca77f617..85b341f2f2 100644
--- a/jarvis/plugins/tool/scroll.py
+++ b/jarvis/plugins/tool/scroll.py
@@ -57,9 +57,11 @@ def _scroll_with_verified_target(
if not landing.ok:
raise RuntimeError(landing.detail)
if expected_window_signature is not None:
- from jarvis.cu.target_guard import foreground_matches # noqa: PLC0415
+ from jarvis.cu.target_guard import ( # noqa: PLC0415
+ foreground_matches_or_same_app,
+ )
- if not foreground_matches(expected_window_signature):
+ if not foreground_matches_or_same_app(expected_window_signature):
raise RuntimeError("foreground window changed after the screenshot")
actuator.scroll(direction, amount)
diff --git a/jarvis/plugins/tool/type_text.py b/jarvis/plugins/tool/type_text.py
index 2a5cb5877f..a4c31e5e41 100644
--- a/jarvis/plugins/tool/type_text.py
+++ b/jarvis/plugins/tool/type_text.py
@@ -30,9 +30,11 @@ def _type_for_expected_window(
expected_signature: tuple[Any, ...] | None,
) -> None:
if expected_signature is not None:
- from jarvis.cu.target_guard import foreground_matches # noqa: PLC0415
+ from jarvis.cu.target_guard import ( # noqa: PLC0415
+ foreground_matches_or_same_app,
+ )
- if not foreground_matches(expected_signature):
+ if not foreground_matches_or_same_app(expected_signature):
raise _ForegroundTargetChanged(
"foreground window changed after the screenshot"
)
diff --git a/jarvis/vision/ax_tree.py b/jarvis/vision/ax_tree.py
index 9056752209..ccaef67a94 100644
--- a/jarvis/vision/ax_tree.py
+++ b/jarvis/vision/ax_tree.py
@@ -8,7 +8,7 @@ and the model prompt are platform-agnostic. The only macOS-specific work is:
1. Resolving the frontmost application via ``NSWorkspace`` and building its
``AXUIElement`` root.
-2. Walking the AX tree depth-first, reading ``kAXRoleAttribute`` /
+2. Walking the AX tree breadth-first, reading ``kAXRoleAttribute`` /
``kAXTitleAttribute`` / ``kAXValueAttribute`` / position+size / enabled /
children, and flattening into ``RawNode``.
3. Normalizing each native ``AX*`` role onto the canonical UIA vocabulary via
@@ -146,9 +146,12 @@ class AXTreeSource:
# ONE native walk at the deepest rung; the retry ladder then shrinks
# the depth at prune time over the same raw nodes. A raw node carries
- # its depth, and prune's first filter is exactly the depth cut — the
- # pruned result is identical to a shallower re-walk without paying
- # the AX IPC again.
+ # its depth, and prune's first filter is exactly the depth cut. The
+ # walk is breadth-first, so even when its time/node budget truncates
+ # a huge tree, every SHALLOW element is already collected — the
+ # ladder's shallower rungs therefore see the same nodes a complete
+ # shallower re-walk would have found, without paying the AX IPC
+ # again.
traverse_fn = self._traverser or self._traverse_via_pyobjc
window_title, active_pid, raw_nodes = await asyncio.to_thread(
traverse_fn,
@@ -454,7 +457,7 @@ def _ax_flatten(
deadline: float | None = None,
max_nodes: int | None = None,
) -> None:
- """Recursive depth-first flatten of an AX element into ``RawNode``.
+ """Iterative BREADTH-FIRST flatten of an AX element into ``RawNode``.
Roles are normalized to the canonical UIA vocabulary at flatten time
(AD-10); a role that ``normalize_role`` drops (``None``) is still recorded
@@ -463,86 +466,91 @@ def _ax_flatten(
interesting-roots root, which prune always keeps).
``deadline`` (``time.monotonic`` timestamp) and ``max_nodes`` bound the
- walk: on either limit the flatten stops descending and the caller gets
- the partial tree collected so far — parents always precede children, so
- the partial list is structurally valid for pruning.
+ walk. Level order is what makes those bounds SAFE: when the budget runs
+ out, everything shallow — toolbar, address bar, buttons — has already
+ been collected, and only the deepest content layers are dropped. A
+ depth-first walk under the same bounds could burn its whole budget
+ inside one huge web-content subtree and never reach a shallow sibling.
+ Parents always precede children, so the partial list stays structurally
+ valid for pruning.
"""
- if depth > max_depth:
- return
- if max_nodes is not None and len(out) >= max_nodes:
- return
- if deadline is not None and time.monotonic() >= deadline:
- return
- try:
- native_role = str(_ax_copy_attr(element, _AX_ROLE) or "")
- native_subrole = str(_ax_copy_attr(element, _AX_SUBROLE) or "")
- canonical = normalize_role(native_role, "darwin")
- role = canonical or ""
-
- is_password = (
- native_role.casefold() == "axsecuretextfield"
- or native_subrole.casefold() == "axsecuretextfield"
- )
- focused = bool(_ax_copy_attr(element, _AX_FOCUSED) or False)
-
- name = _ax_copy_attr(element, _AX_TITLE)
- if not name and not is_password:
- name = _ax_copy_attr(element, _AX_VALUE)
- if not name:
- name = _ax_copy_attr(element, _AX_DESCRIPTION)
- name = str(name or "")
-
- automation_id = str(_ax_copy_attr(element, _AX_IDENTIFIER) or "")
-
- x, y = _ax_point(_ax_copy_attr(element, _AX_POSITION))
- w, h = _ax_size(_ax_copy_attr(element, _AX_SIZE))
- bounds = (x, y, max(0, w), max(0, h))
-
- enabled_raw = _ax_copy_attr(element, _AX_ENABLED)
- enabled = True if enabled_raw is None else bool(enabled_raw)
-
- # L3 value-read: AXValue is the current text of an editable control
- # (search box, text field). Read separately from the name-fallback above
- # so the loop can see what a field already holds.
- value = "" if is_password else str(_ax_copy_attr(element, _AX_VALUE) or "")
- except Exception: # noqa: BLE001
- return
-
- my_index = len(out)
- out.append(RawNode(
- role=role,
- name=name,
- automation_id=automation_id,
- bounds=bounds,
- enabled=enabled,
- is_offscreen=False,
- depth=depth,
- parent_index=parent_index,
- value=value,
- is_password=is_password,
- focused=focused,
- ))
-
- if depth >= max_depth:
- return
-
- children = _ax_copy_attr(element, _AX_CHILDREN)
- if not children:
- return
- try:
- child_list = list(children)
- except Exception: # noqa: BLE001
- return
- for child in child_list:
- _ax_flatten(
- child,
- depth=depth + 1,
- max_depth=max_depth,
- parent_index=my_index,
- out=out,
- deadline=deadline,
- max_nodes=max_nodes,
- )
+ from collections import deque # noqa: PLC0415
+
+ queue: deque[tuple[Any, int, int]] = deque([(element, depth, parent_index)])
+ while queue:
+ current, current_depth, current_parent = queue.popleft()
+ if current_depth > max_depth:
+ continue
+ if max_nodes is not None and len(out) >= max_nodes:
+ return
+ if deadline is not None and time.monotonic() >= deadline:
+ return
+ try:
+ native_role = str(_ax_copy_attr(current, _AX_ROLE) or "")
+ native_subrole = str(_ax_copy_attr(current, _AX_SUBROLE) or "")
+ canonical = normalize_role(native_role, "darwin")
+ role = canonical or ""
+
+ is_password = (
+ native_role.casefold() == "axsecuretextfield"
+ or native_subrole.casefold() == "axsecuretextfield"
+ )
+ focused = bool(_ax_copy_attr(current, _AX_FOCUSED) or False)
+
+ name = _ax_copy_attr(current, _AX_TITLE)
+ if not name and not is_password:
+ name = _ax_copy_attr(current, _AX_VALUE)
+ if not name:
+ name = _ax_copy_attr(current, _AX_DESCRIPTION)
+ name = str(name or "")
+
+ automation_id = str(_ax_copy_attr(current, _AX_IDENTIFIER) or "")
+
+ x, y = _ax_point(_ax_copy_attr(current, _AX_POSITION))
+ w, h = _ax_size(_ax_copy_attr(current, _AX_SIZE))
+ bounds = (x, y, max(0, w), max(0, h))
+
+ enabled_raw = _ax_copy_attr(current, _AX_ENABLED)
+ enabled = True if enabled_raw is None else bool(enabled_raw)
+
+ # L3 value-read: AXValue is the current text of an editable
+ # control (search box, text field). Read separately from the
+ # name-fallback above so the loop can see what a field holds.
+ value = (
+ "" if is_password
+ else str(_ax_copy_attr(current, _AX_VALUE) or "")
+ )
+ except Exception: # noqa: BLE001, S112 — one broken AX element never
+ # aborts the walk; siblings are still valuable.
+ continue
+
+ my_index = len(out)
+ out.append(RawNode(
+ role=role,
+ name=name,
+ automation_id=automation_id,
+ bounds=bounds,
+ enabled=enabled,
+ is_offscreen=False,
+ depth=current_depth,
+ parent_index=current_parent,
+ value=value,
+ is_password=is_password,
+ focused=focused,
+ ))
+
+ if current_depth >= max_depth:
+ continue
+ children = _ax_copy_attr(current, _AX_CHILDREN)
+ if not children:
+ continue
+ try:
+ child_list = list(children)
+ except Exception: # noqa: BLE001, S112 — unreadable children only end
+ # this branch, not the walk.
+ continue
+ for child in child_list:
+ queue.append((child, current_depth + 1, my_index))
__all__ = ["AXTreeSource"]
diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.py
index ccf281d07e..a1b9805989 100644
--- a/jarvis/voice/action_phrases.py
+++ b/jarvis/voice/action_phrases.py
@@ -142,6 +142,23 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "That took too long on screen (over {secs} seconds) and was cancelled.",
"es": "Eso tardó demasiado en la pantalla (más de {secs} segundos) y se canceló.",
},
+ # open_app launch readbacks (deterministic local-action path). The German
+ # column keeps the exact historical wording.
+ "open_app_launched": {
+ "de": "Gestartet: {app}", # i18n-allow
+ "en": "Launched: {app}",
+ "es": "Iniciado: {app}",
+ },
+ "open_app_launched_raised": {
+ "de": "Gestartet und nach vorn geholt: {app}", # i18n-allow
+ "en": "Launched and brought to the front: {app}",
+ "es": "Iniciado y traído al frente: {app}",
+ },
+ "open_app_not_found": {
+ "de": "Anwendung '{app}' nicht gefunden.", # i18n-allow
+ "en": "Application '{app}' was not found.",
+ "es": "No se encontró la aplicación '{app}'.",
+ },
# Computer-use dispatch — the immediate optimistic ACK.
"cu_dispatch_ack": {
"de": "Mach ich. Ich erledige das direkt am Bildschirm " # i18n-allow
diff --git a/tests/unit/cu/test_engine_loop.py b/tests/unit/cu/test_engine_loop.py
index 9269ee9293..4f4e3cc27a 100644
--- a/tests/unit/cu/test_engine_loop.py
+++ b/tests/unit/cu/test_engine_loop.py
@@ -94,6 +94,7 @@ def patched(monkeypatch, tmp_path):
capture_calls=0, # capture_stable_frame invocations
foreground_handle=11,
foreground_rect=(0, 0, 192, 108),
+ foreground_pid=None, # set to an int for macOS-style app identity
)
def fake_select_capture_target(
@@ -153,7 +154,11 @@ def patched(monkeypatch, tmp_path):
monkeypatch.setattr(
ws,
"foreground_window",
- lambda: ws.WindowInfo("Test Window", handle=state.foreground_handle),
+ lambda: ws.WindowInfo(
+ "Test Window",
+ handle=state.foreground_handle,
+ pid=state.foreground_pid,
+ ),
)
monkeypatch.setattr(
ws, "window_frame_rect", lambda _window: state.foreground_rect,
@@ -311,6 +316,99 @@ async def test_foreground_change_after_model_decision_refuses_action(patched):
assert any("foreground window changed" in user for _system, user in brain.calls)
+async def test_same_app_window_swap_before_first_action_refuses(patched):
+ # macOS app-identity signatures stay WINDOW-precise: a second top-level
+ # window of the SAME app stealing focus between screenshot and the FIRST
+ # action must refuse exactly like a cross-app steal (reviewer regression
+ # for the 2026-07-20 signature redesign).
+ patched.foreground_pid = 812
+
+ class _FocusChangingBrain(FakeBrain):
+ async def complete_text(self, *, system: str, user: str) -> str:
+ reply = await super().complete_text(system=system, user=user)
+ if len(self.calls) == 1:
+ patched.foreground_handle = 22 # same app, different window
+ return reply
+
+ brain = _FocusChangingBrain([
+ '{"action":"click","x":500,"y":500}',
+ '{"action":"fail","reason":"the target window changed"}',
+ ])
+ executor = FakeExecutor()
+
+ chunks = await _run(_ctx(brain, executor))
+
+ assert _final(chunks).exit_code == 5
+ assert executor.calls == []
+ assert any("foreground window changed" in user for _system, user in brain.calls)
+
+
+async def test_same_app_churn_after_own_click_rebaselines_and_type_proceeds(patched):
+ # The live 2026-07-20 failure loop: the click makes a same-app dropdown
+ # the frontmost layer-0 window; the batched type must STILL land instead
+ # of "REFUSED — the foreground window changed after the screenshot".
+ patched.foreground_pid = 812
+ state = patched
+
+ class _ChurningExecutor(FakeExecutor):
+ async def execute(self, tool, args, *, user_utterance, trace_id):
+ result = await super().execute(
+ tool, args, user_utterance=user_utterance, trace_id=trace_id,
+ )
+ if tool["name"] == "click":
+ state.foreground_handle = 5177 # dropdown became frontmost
+ return result
+
+ brain = FakeBrain([
+ '[{"action":"click","x":500,"y":500},'
+ '{"action":"type","text":"https://example.com"}]',
+ '{"action":"fail","reason":"stop here"}',
+ ])
+ executor = _ChurningExecutor()
+
+ chunks = await _run(_ctx(brain, executor))
+
+ _final(chunks)
+ tool_names = [name for (name, _) in executor.calls]
+ assert "click" in tool_names
+ assert "type_text" in tool_names, (
+ "same-app churn caused by our own click must not behead the batch"
+ )
+
+
+async def test_cross_app_steal_after_own_click_still_refuses_type(patched):
+ # The relaxation is app-scoped only: a DIFFERENT app taking over after
+ # our click still breaks the batch before the type.
+ patched.foreground_pid = 812
+ state = patched
+
+ class _StealingExecutor(FakeExecutor):
+ async def execute(self, tool, args, *, user_utterance, trace_id):
+ result = await super().execute(
+ tool, args, user_utterance=user_utterance, trace_id=trace_id,
+ )
+ if tool["name"] == "click":
+ state.foreground_handle = 9001
+ state.foreground_pid = 990 # another app stole focus
+ return result
+
+ brain = FakeBrain([
+ '[{"action":"click","x":500,"y":500},'
+ '{"action":"type","text":"https://example.com"}]',
+ '{"action":"fail","reason":"stop here"}',
+ ])
+ executor = _StealingExecutor()
+
+ chunks = await _run(_ctx(brain, executor))
+
+ _final(chunks)
+ tool_names = [name for (name, _) in executor.calls]
+ assert "click" in tool_names
+ assert "type_text" not in tool_names, (
+ "typing after a cross-app focus steal is the blind-input bug"
+ )
+
+
async def test_foreground_change_during_capture_discards_stale_frame(
patched,
monkeypatch,
diff --git a/tests/unit/cu/test_target_guard.py b/tests/unit/cu/test_target_guard.py
index 38dcf479a6..a524c7048a 100644
--- a/tests/unit/cu/test_target_guard.py
+++ b/tests/unit/cu/test_target_guard.py
@@ -3,33 +3,55 @@ from __future__ import annotations
from contextlib import contextmanager
-from jarvis.cu.target_guard import read_foreground_target, window_signature
+from jarvis.cu.target_guard import (
+ read_foreground_target,
+ signatures_same_app,
+ window_signature,
+)
from jarvis.platform.window_state import WindowInfo
class TestWindowSignature:
- """App-level identity when the probe knows the owning pid (macOS)."""
-
- def test_pid_wins_over_handle_and_rect(self):
- window = WindowInfo("Google Chrome", handle=4021, pid=812)
- assert window_signature(window, (0, 25, 1440, 875)) == ("app", 812)
+ """Window-precise identity that still exposes the owning app (macOS)."""
+
+ def test_pid_signature_stays_window_precise(self):
+ # Same app, different window: the SIGNATURES must differ (strict
+ # equality is the engine's pre-first-action baseline — a second
+ # same-app top-level window stealing focus before we acted must
+ # still refuse).
+ main = window_signature(
+ WindowInfo("Google Chrome", handle=4021, pid=812), (0, 25, 1440, 875),
+ )
+ other = window_signature(
+ WindowInfo("Untitled", handle=5177, pid=812), (30, 55, 1440, 875),
+ )
+ assert main != other
+ assert main == ("app", 812, 4021, (0, 25, 1440, 875))
- def test_same_app_window_churn_keeps_signature_stable(self):
+ def test_same_app_churn_is_distinguishable_from_cross_app_steal(self):
# A click into the address bar spawns a suggestions dropdown: new
- # frontmost layer-0 CGWindowID, new rect, same owning app. The guard
- # must NOT see a foreground change (live incident 2026-07-20).
+ # frontmost layer-0 CGWindowID, new rect, same owning app (live
+ # incident 2026-07-20). signatures_same_app separates that from a
+ # different app taking over.
before = window_signature(
WindowInfo("Google Chrome", handle=4021, pid=812), (0, 25, 1440, 875),
)
- after = window_signature(
+ dropdown = window_signature(
WindowInfo("", handle=5177, pid=812), (105, 60, 900, 340),
)
- assert before == after
+ stealer = window_signature(
+ WindowInfo("Zoom Meeting", handle=9001, pid=990), (200, 200, 800, 600),
+ )
+ assert signatures_same_app(before, dropdown) is True
+ assert signatures_same_app(before, stealer) is False
- def test_cross_app_focus_steal_still_detected(self):
- chrome = window_signature(WindowInfo("Google Chrome", pid=812), None)
- stealer = window_signature(WindowInfo("Zoom Meeting", pid=990), None)
- assert chrome != stealer
+ def test_no_pid_signatures_never_count_as_same_app(self):
+ # Windows/Linux signatures carry no pid — the same-app relaxation
+ # must be a structural no-op there.
+ a = window_signature(WindowInfo("Editor", handle=77), (0, 0, 800, 600))
+ b = window_signature(WindowInfo("Editor", handle=77), (0, 0, 800, 600))
+ assert a == b
+ assert signatures_same_app(a, b) is False
def test_no_pid_keeps_per_window_handle_identity(self):
# Windows/Linux probes never set pid — their stable hwnd/X11-id plus
@@ -45,6 +67,7 @@ class TestWindowSignature:
def test_none_window_is_none_signature(self):
assert window_signature(None, None) == ("none",)
+ assert signatures_same_app(("none",), ("none",)) is False
def test_foreground_target_reads_window_and_rect_inside_input_space(monkeypatch):
diff --git a/tests/unit/vision/test_ax_tree.py b/tests/unit/vision/test_ax_tree.py
index 028a559daf..64c2f45e27 100644
--- a/tests/unit/vision/test_ax_tree.py
+++ b/tests/unit/vision/test_ax_tree.py
@@ -314,3 +314,36 @@ def test_flatten_max_nodes_cap_stops_collection() -> None:
nodes: list = []
_ax_flatten(root, depth=0, max_depth=6, parent_index=-1, out=nodes, max_nodes=2)
assert len(nodes) == 2
+
+
+def test_truncated_walk_keeps_shallow_siblings(monkeypatch) -> None:
+ # Breadth-first guarantee: a huge deep subtree visited "first" must not
+ # starve shallow siblings (toolbar/address bar) when the node budget
+ # truncates the walk — the depth-first version lost exactly those.
+ def _leaf(i: int) -> FakeAXElement:
+ return FakeAXElement(role="AXStaticText", title=f"deep-{i}",
+ position=(0, 0), size=(10, 10))
+
+ huge_web_area = FakeAXElement(
+ role="AXGroup", title="web-content", position=(0, 60), size=(800, 500),
+ children=[
+ FakeAXElement(
+ role="AXGroup", title=f"row-{i}", position=(0, 60),
+ size=(800, 20), children=[_leaf(i)],
+ )
+ for i in range(50)
+ ],
+ )
+ toolbar_button = FakeAXElement(
+ role="AXButton", title="Reload", position=(700, 10), size=(40, 30),
+ )
+ root = FakeAXElement(
+ role="AXWindow", title="Browser", position=(0, 0), size=(800, 600),
+ children=[huge_web_area, toolbar_button],
+ )
+ nodes: list = []
+ _ax_flatten(
+ root, depth=0, max_depth=6, parent_index=-1, out=nodes, max_nodes=10,
+ )
+ assert len(nodes) == 10
+ assert any(n.name == "Reload" for n in nodes)