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.

feat(cu): Codex-style screen indicator — gold glow border + Esc-to-cancel

Ruben Lütke47c44c5176ab
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 632056b0f7..3782d93f49 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -1202,8 +1202,19 @@ def _phase2_full_brain(
# ("setze Schrittlimit auf N" -> computer_use.step_budget) applies
# to the next mission without an app restart (idempotent per bus).
subscribe_context_reload(bus)
+ # Screen indicator (yellow CU border + Esc-to-cancel): a bus
+ # subscription only — the PySide6 sidecar spawns lazily on the
+ # first CUControlStarted (AP-26).
+ try:
+ from jarvis.cu.indicator.controller import ( # noqa: PLC0415
+ wire_cu_indicator,
+ )
+
+ wire_cu_indicator(bus)
+ except Exception as _ind_exc: # noqa: BLE001
+ log.warning("CU indicator not wired: %s", _ind_exc)
log.info(
- "ComputerUseContext verdrahtet (tools=%s, step_budget=%d, "
+ "ComputerUseContext wired (tools=%s, step_budget=%d, "
"verify=%s, max_replans=%d)",
sorted(cu_tools.keys()),
cu_cfg.step_budget,
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index f471b13bdd..c7b1167791 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1663,6 +1663,13 @@ class ComputerUseConfig(BaseModel):
model_config = {"extra": "allow"}
enabled: bool = False
+ # Screen indicator (2026-07-15): while a CU mission controls the local
+ # mouse/keyboard, a pulsing gold border glows on every monitor edge and
+ # an "Esc to cancel" pill is shown (jarvis/cu/indicator, Codex-style).
+ # Default ON; turning it off also skips the sidecar process entirely.
+ # The global Escape-to-cancel listener is armed per mission regardless
+ # of this flag (it is a safety affordance, not a visual).
+ screen_indicator: bool = True
# Which Computer-Use engine runs. "v2" (default) = the
# rebuilt perceive->act->verify engine (jarvis/cu/engine.py): per-frame
# coordinate mapping, provider coordinate conventions, UI-idle capture,
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 8e63abaa83..254ad3d1f1 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -667,11 +667,38 @@ class CUStepProfiled(Event):
cache_read_tokens: int = 0
+@dataclass(frozen=True, slots=True)
+class CUControlStarted(Event):
+ """A Computer-Use mission took control of the local mouse/keyboard.
+
+ Published by ``ComputerUseHarness.invoke()`` the moment the mission's
+ cancel token is registered — exactly when "Jarvis is controlling this
+ computer" begins. Drives user-facing control indicators (the yellow
+ screen border in ``jarvis.cu.indicator``). Concurrent missions each
+ publish their own Started/Ended pair; subscribers refcount.
+ """
+ mission_id: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class CUControlEnded(Event):
+ """A Computer-Use mission released control of the local mouse/keyboard.
+
+ Always published in the ``finally`` of ``ComputerUseHarness.invoke()``
+ — on success, timeout, cancel, and crash alike. ``reason`` is a short
+ machine-readable tag: "finished" | "cancelled" | "timeout" | "error".
+ """
+ mission_id: str = ""
+ reason: str = "finished"
+
+
#: Heartbeat contract (2026-06-09): every event type the Computer-Use loop
#: publishes as a liveness signal. The speech pipeline subscribes its
#: ``_on_agent_progress`` handler to EXACTLY this tuple — extending the loop
#: with a new progress event means adding it here, and the contract test in
#: tests/unit/harness/test_cu_wave0.py keeps both sides honest.
+#: (CUControlStarted/Ended are deliberately NOT part of this tuple — they
+#: fire once per mission, not per step, so they carry no liveness signal.)
CU_PROGRESS_EVENTS: tuple[type, ...] = (
ObservationCaptured,
ActionPlanned,
diff --git a/jarvis/cu/actuate/windows.py b/jarvis/cu/actuate/windows.py
index bc9b5369f1..f261657031 100644
--- a/jarvis/cu/actuate/windows.py
+++ b/jarvis/cu/actuate/windows.py
@@ -345,6 +345,11 @@ class WindowsActuator(Actuator):
def key_combo(self, keys: list[str]) -> None:
expanded = expand_combo_keys([str(k) for k in keys])
+ # A Jarvis-typed Esc must not trip the Escape-to-cancel listener
+ # (jarvis.cu.indicator) — stamp BEFORE the OS sees the keystroke.
+ from jarvis.cu.indicator.self_input import stamp_if_escape # noqa: PLC0415
+
+ stamp_if_escape(expanded)
vk_codes: list[int] = []
for k in expanded:
vk = resolve_vk(k)
diff --git a/jarvis/cu/capture.py b/jarvis/cu/capture.py
index e06dc0ed6b..919b77933e 100644
--- a/jarvis/cu/capture.py
+++ b/jarvis/cu/capture.py
@@ -96,10 +96,19 @@ def _require_macos_screen_recording_permission() -> None:
def mss_grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
- """Default grabber via mss, inside the thread DPI pin."""
+ """Default grabber via mss, inside the thread DPI pin.
+
+ Wrapped in the indicator capture guard: on hosts without a native
+ capture-exclusion API (non-Windows) the yellow CU screen border is
+ blanked for the duration of the grab so the model never sees it.
+ """
import mss # noqa: PLC0415
- with input_space(), mss.mss() as sct:
+ from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415
+ indicator_suppressed,
+ )
+
+ with indicator_suppressed(), input_space(), mss.mss() as sct:
raw = sct.grab(bbox)
return (tuple(raw.size), raw.rgb)
@@ -123,9 +132,15 @@ def grabber_for(target: MonitorInfo) -> Grabber:
def grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
nonlocal native_alive
if native_alive:
+ from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415
+ indicator_suppressed,
+ )
from jarvis.platform import window_capture # noqa: PLC0415
- raw = window_capture.grab_window(handle, bbox)
+ # Native per-window capture can still include an overlapping
+ # topmost overlay on some platforms — same guard as mss_grab.
+ with indicator_suppressed():
+ raw = window_capture.grab_window(handle, bbox)
if raw is not None:
return raw
native_alive = False
diff --git a/jarvis/cu/indicator/__init__.py b/jarvis/cu/indicator/__init__.py
new file mode 100644
index 0000000000..9479b4a891
--- /dev/null
+++ b/jarvis/cu/indicator/__init__.py
@@ -0,0 +1,27 @@
+"""Computer-Use screen indicator — the yellow "Jarvis is controlling this
+computer" glow border (Codex-style) plus the Esc-to-cancel hint.
+
+Architecture (2026-07, replaces the removed OS-Level edge-glow):
+
+- ``renderer`` + ``__main__`` — a minimal PySide6 sidecar process
+ (``python -m jarvis.cu.indicator``) that draws a pulsing gold glow along
+ every monitor's edges and an "Esc to cancel" pill. Spawned lazily per
+ Computer-Use mission, killed when the last mission ends. PySide6 is
+ imported ONLY inside the sidecar, never in the main process.
+- ``controller`` — main-process glue: subscribes to
+ ``CUControlStarted``/``CUControlEnded``, refcounts concurrent missions,
+ arms the global Escape hotkey while a mission runs, and cancels the
+ CU-scoped tokens on Escape.
+- ``protocol`` — the JSON-lines stdin/stdout vocabulary between the two.
+- ``capture_guard`` — hides the border for the split second of CU's own
+ frame grabs on platforms without a capture-exclusion API (non-Windows).
+- ``self_input`` — suppression stamps so a synthetic Esc typed BY Jarvis
+ never cancels Jarvis.
+
+Headless / Wayland / missing-PySide6 hosts: the controller never spawns
+the sidecar and logs one English line — a quiet no-op, never a crash.
+"""
+
+from __future__ import annotations
+
+__all__: list[str] = []
diff --git a/jarvis/cu/indicator/__main__.py b/jarvis/cu/indicator/__main__.py
new file mode 100644
index 0000000000..f2dcc7bf7b
--- /dev/null
+++ b/jarvis/cu/indicator/__main__.py
@@ -0,0 +1,30 @@
+"""Sidecar entry: ``python -m jarvis.cu.indicator``.
+
+Guards the PySide6 import so a host without the GUI stack (headless VPS,
+base install) exits with ``protocol.EXIT_NO_GUI`` and one English line on
+stderr instead of a traceback. The controller treats that exit code as an
+expected degradation.
+"""
+
+from __future__ import annotations
+
+import sys
+
+from jarvis.cu.indicator.protocol import EXIT_NO_GUI
+
+
+def main() -> int:
+ try:
+ from jarvis.cu.indicator.renderer import run # noqa: PLC0415
+ except ImportError as exc:
+ sys.stderr.write(
+ f"cu-indicator: PySide6 unavailable ({exc}) — indicator disabled. "
+ "Install the [desktop] extra to enable the Computer-Use screen "
+ "indicator.\n"
+ )
+ return EXIT_NO_GUI
+ return run()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jarvis/cu/indicator/capture_guard.py b/jarvis/cu/indicator/capture_guard.py
new file mode 100644
index 0000000000..dc354ce400
--- /dev/null
+++ b/jarvis/cu/indicator/capture_guard.py
@@ -0,0 +1,58 @@
+"""Keep the indicator out of Computer-Use's own perception frames.
+
+On Windows the sidecar windows carry ``WDA_EXCLUDEFROMCAPTURE`` and are
+invisible to every grab — this module stays a no-op there. On macOS/Linux
+no such API exists, so the controller registers a hook that hides the
+border for the split second of each frame grab (blank → grab → unblank).
+
+Fail-open by design: a missing hook, a dead sidecar, or a late ack must
+NEVER delay or break the grab beyond the small ack timeout — a border
+pixel in one frame is a cosmetic defect, a broken perception loop kills
+the mission.
+"""
+
+from __future__ import annotations
+
+import threading
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+
+# The registered hook is itself a contextmanager factory: entering it
+# blanks the indicator, leaving it restores. ``None`` → no indicator.
+_hook_lock = threading.Lock()
+_hook: Callable[[], object] | None = None
+
+
+def register_hook(hook: Callable[[], object]) -> None:
+ global _hook
+ with _hook_lock:
+ _hook = hook
+
+
+def unregister_hook() -> None:
+ global _hook
+ with _hook_lock:
+ _hook = None
+
+
+@contextmanager
+def indicator_suppressed() -> Iterator[None]:
+ """Wrap a frame grab; the indicator is hidden while inside (best effort)."""
+ with _hook_lock:
+ hook = _hook
+ if hook is None:
+ yield
+ return
+ try:
+ cm = hook()
+ except Exception: # noqa: BLE001 — fail-open
+ yield
+ return
+ try:
+ with cm: # type: ignore[union-attr]
+ yield
+ except Exception: # noqa: BLE001 — a guard failure must not kill the grab
+ yield
+
+
+__all__ = ["indicator_suppressed", "register_hook", "unregister_hook"]
diff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.py
new file mode 100644
index 0000000000..db9d77b9ff
--- /dev/null
+++ b/jarvis/cu/indicator/controller.py
@@ -0,0 +1,360 @@
+"""Main-process controller for the Computer-Use screen indicator.
+
+Wired once at boot (``wire_cu_indicator(bus)`` from the brain factory,
+right where the ComputerUseContext is set). Boot cost is a bus
+subscription and nothing else (AP-26): the PySide6 sidecar is spawned
+lazily when the FIRST Computer-Use mission starts and terminated when the
+LAST one ends (missions can overlap — the controller refcounts
+``CUControlStarted``/``CUControlEnded`` pairs).
+
+While at least one mission runs, a global Escape listener is armed
+through the existing cross-platform ``HotkeyTrigger`` backends; a real
+(non-Jarvis-synthesized, see ``self_input``) Escape press cancels EVERY
+active mission through the same CU-scoped token registry the voice hangup
+uses — the engine exits with code 130 and reports an honest cancel.
+
+Degradations (each logs one English line, never crashes, never blocks a
+mission): headless / Wayland / PySide6 missing → no border; hotkey
+backend unavailable (Wayland, missing macOS permission) → no Escape and
+therefore no "Esc to cancel" pill (the border must not promise a key that
+cannot work).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import logging
+import os
+import queue
+import subprocess
+import sys
+import threading
+from contextlib import contextmanager
+from typing import Any
+
+from jarvis.cu.indicator import capture_guard, protocol, self_input
+from jarvis.cu.indicator.win32 import capture_exclusion_available
+
+log = logging.getLogger(__name__)
+
+# "Esc to cancel" pill copy — ALL supported output locales (repo rule:
+# a phrase table always carries every supported language and resolves its
+# key through the one turn-language resolver).
+_ESC_HINTS: dict[str, str] = {
+ "de": "Esc zum Abbrechen", # i18n-allow: localized product-surface UI string
+ "en": "Esc to cancel",
+ "es": "Esc para cancelar", # i18n-allow: localized product-surface UI string
+}
+
+_QUIT_GRACE_S = 1.5
+_BLANK_ACK_TIMEOUT_S = 0.15
+
+
+def _screen_indicator_enabled() -> bool:
+ try:
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ cu = getattr(load_config(), "computer_use", None)
+ return bool(getattr(cu, "screen_indicator", True))
+ except Exception: # noqa: BLE001 — config trouble must not break missions
+ return True
+
+
+def _resolve_hint_language() -> str:
+ """Pill language: reply-language pin → DEFAULT_LOCALE (honesty rule —
+ this layer has no turn text, so it never guesses beyond the resolver)."""
+ from jarvis.core.turn_language import ( # noqa: PLC0415
+ DEFAULT_LOCALE,
+ resolve_output_language,
+ )
+
+ pin = ""
+ try:
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ pin = str(getattr(load_config().brain, "reply_language", "") or "")
+ except Exception: # noqa: BLE001
+ pin = ""
+ return resolve_output_language(pin, "", "", default=DEFAULT_LOCALE)
+
+
+class CUIndicatorController:
+ """Refcounts CU missions; owns the sidecar process + Escape listener."""
+
+ def __init__(self, bus: Any) -> None:
+ self._bus = bus
+ self._active = 0
+ self._lock = asyncio.Lock()
+ self._proc: subprocess.Popen[str] | None = None
+ self._stdin_lock = threading.Lock()
+ self._acks: queue.Queue[str] = queue.Queue()
+ self._esc_task: asyncio.Task | None = None
+ self._sidecar_warned = False
+
+ # ------------------------------------------------------------------ wiring
+ def wire(self) -> None:
+ from jarvis.core.events import ( # noqa: PLC0415
+ CUControlEnded,
+ CUControlStarted,
+ )
+
+ self._bus.subscribe(CUControlStarted, self._on_started)
+ self._bus.subscribe(CUControlEnded, self._on_ended)
+
+ async def _on_started(self, event: Any) -> None:
+ del event
+ async with self._lock:
+ self._active += 1
+ if self._active == 1:
+ await self._activate()
+
+ async def _on_ended(self, event: Any) -> None:
+ del event
+ async with self._lock:
+ if self._active == 0:
+ return
+ self._active -= 1
+ if self._active == 0:
+ await self._deactivate()
+
+ # ------------------------------------------------------------- activation
+ async def _activate(self) -> None:
+ esc_armed = self._arm_escape()
+ if not _screen_indicator_enabled():
+ log.debug("[cu-indicator] disabled via [computer_use].screen_indicator")
+ return
+ ok, reason = self._border_capability()
+ if not ok:
+ if not self._sidecar_warned:
+ self._sidecar_warned = True
+ log.info("[cu-indicator] screen border unavailable: %s", reason)
+ return
+ await asyncio.to_thread(self._spawn_sidecar)
+ hint = _ESC_HINTS.get(_resolve_hint_language(), _ESC_HINTS["en"]) if esc_armed else ""
+ self._send(protocol.CMD_SHOW, hint=hint)
+ if not capture_exclusion_available() and self._proc is not None:
+ capture_guard.register_hook(self._suppress_for_grab)
+
+ async def _deactivate(self) -> None:
+ self._disarm_escape()
+ capture_guard.unregister_hook()
+ if self._proc is None:
+ return
+ self._send(protocol.CMD_HIDE)
+ self._send(protocol.CMD_QUIT)
+ proc, self._proc = self._proc, None
+ await asyncio.to_thread(self._reap, proc)
+
+ @staticmethod
+ def _border_capability() -> tuple[bool, str]:
+ try:
+ from jarvis.platform.probes import ( # noqa: PLC0415
+ display_present,
+ is_wayland,
+ )
+
+ if not display_present():
+ return False, "no display on this host (headless)"
+ if is_wayland():
+ return False, (
+ "Wayland session (no always-on-top overlay surface)"
+ )
+ except Exception: # noqa: BLE001
+ return False, "platform probes unavailable"
+ if importlib.util.find_spec("PySide6") is None:
+ return False, (
+ "PySide6 not installed (install the [desktop] extra)"
+ )
+ return True, ""
+
+ # ---------------------------------------------------------------- sidecar
+ def _spawn_sidecar(self) -> None:
+ if self._proc is not None and self._proc.poll() is None:
+ return
+ try:
+ from jarvis.core.process_utils import ( # noqa: PLC0415
+ NO_WINDOW_CREATIONFLAGS,
+ )
+
+ self._proc = subprocess.Popen(
+ [sys.executable, "-m", "jarvis.cu.indicator"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ encoding="utf-8",
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ env=os.environ.copy(),
+ )
+ except Exception: # noqa: BLE001
+ self._proc = None
+ if not self._sidecar_warned:
+ self._sidecar_warned = True
+ log.warning(
+ "[cu-indicator] sidecar spawn failed — border disabled "
+ "for this session.", exc_info=True,
+ )
+ return
+ threading.Thread(
+ target=self._pump_acks,
+ args=(self._proc,),
+ name="cu-indicator-acks",
+ daemon=True,
+ ).start()
+
+ def _pump_acks(self, proc: subprocess.Popen[str]) -> None:
+ try:
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ ack = protocol.decode_ack(line)
+ if ack is not None:
+ self._acks.put(ack)
+ except Exception: # noqa: BLE001
+ log.debug("[cu-indicator] ack pipe closed", exc_info=True)
+
+ def _send(self, cmd: str, **fields: Any) -> bool:
+ """Fire-and-forget command write; a dead pipe disables the sidecar."""
+ proc = self._proc
+ if proc is None or proc.stdin is None or proc.poll() is not None:
+ return False
+ try:
+ with self._stdin_lock:
+ proc.stdin.write(protocol.encode_command(cmd, **fields))
+ proc.stdin.flush()
+ return True
+ except Exception: # noqa: BLE001
+ log.info(
+ "[cu-indicator] sidecar pipe broke — border disabled for the "
+ "rest of this mission."
+ )
+ self._proc = None
+ capture_guard.unregister_hook()
+ return False
+
+ def _reap(self, proc: subprocess.Popen[str]) -> None:
+ try:
+ proc.wait(timeout=_QUIT_GRACE_S)
+ except Exception: # noqa: BLE001
+ try:
+ proc.kill()
+ proc.wait(timeout=1.0)
+ except Exception: # noqa: BLE001
+ log.debug("[cu-indicator] sidecar reap failed", exc_info=True)
+
+ # ----------------------------------------------------------- capture guard
+ @contextmanager
+ def _suppress_for_grab(self):
+ """Blank the border around one CU frame grab (non-Windows only).
+
+ Fail-open: a late/lost ack only costs the timeout, never the grab.
+ """
+ while True: # drop stale acks so we wait on OUR blank
+ try:
+ self._acks.get_nowait()
+ except queue.Empty:
+ break
+ sent = self._send(protocol.CMD_BLANK)
+ if sent:
+ try:
+ self._acks.get(timeout=_BLANK_ACK_TIMEOUT_S)
+ except queue.Empty:
+ pass # fail-open: grab anyway
+ try:
+ yield
+ finally:
+ if sent:
+ self._send(protocol.CMD_UNBLANK)
+
+ # ---------------------------------------------------------------- escape
+ def _arm_escape(self) -> bool:
+ try:
+ from jarvis.platform.probes import has_hotkey # noqa: PLC0415
+
+ if not has_hotkey():
+ log.info(
+ "[cu-indicator] no global-hotkey backend on this host — "
+ "Escape-to-cancel unavailable."
+ )
+ return False
+ except Exception: # noqa: BLE001
+ return False
+ if self._esc_task is None or self._esc_task.done():
+ self._esc_task = asyncio.get_running_loop().create_task(
+ self._esc_watch(), name="cu-indicator-esc",
+ )
+ return True
+
+ def _disarm_escape(self) -> None:
+ task, self._esc_task = self._esc_task, None
+ if task is not None and not task.done():
+ task.cancel()
+
+ async def _esc_watch(self) -> None:
+ """Armed only while ≥1 CU mission runs; Esc cancels them all."""
+ try:
+ from jarvis.trigger.hotkey import HotkeyTrigger # noqa: PLC0415
+
+ # Bare "esc" is intentionally NOT run through validate_hotkey():
+ # that guard protects user-configured push-to-talk combos; this
+ # binding exists only while Jarvis itself is typing/clicking.
+ trigger = HotkeyTrigger({"cu_cancel": ["esc"]})
+ async with trigger:
+ async for event_name in trigger.events():
+ if event_name != "cu_cancel":
+ continue
+ if self_input.esc_recently_synthesized():
+ log.debug(
+ "[cu-indicator] ignoring Esc synthesized by the "
+ "CU engine itself."
+ )
+ continue
+ self._cancel_all_missions()
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001
+ log.warning(
+ "[cu-indicator] Escape listener failed — cancel via voice/"
+ "tray/kill-hotkey still works.", exc_info=True,
+ )
+
+ @staticmethod
+ def _cancel_all_missions() -> None:
+ from jarvis.harness.computer_use_context import ( # noqa: PLC0415
+ cancel_active_cu,
+ )
+
+ cancelled = cancel_active_cu("user_escape", suppress_new=False)
+ log.info(
+ "[cu-indicator] Escape pressed — %s.",
+ "cancelled the running Computer-Use mission(s)"
+ if cancelled
+ else "no active Computer-Use mission to cancel",
+ )
+
+
+_controller: CUIndicatorController | None = None
+
+
+def wire_cu_indicator(bus: Any) -> CUIndicatorController | None:
+ """Idempotent boot hook: subscribe the indicator controller to ``bus``.
+
+ Cheap by contract (AP-26): no Qt import, no process spawn, no probe —
+ everything heavy waits for the first CUControlStarted.
+ """
+ global _controller
+ if bus is None:
+ return None
+ if _controller is not None and _controller._bus is bus:
+ return _controller
+ try:
+ controller = CUIndicatorController(bus)
+ controller.wire()
+ except Exception: # noqa: BLE001 — the indicator must never break boot
+ log.warning("[cu-indicator] wiring failed", exc_info=True)
+ return None
+ _controller = controller
+ return controller
+
+
+__all__ = ["CUIndicatorController", "wire_cu_indicator"]
diff --git a/jarvis/cu/indicator/protocol.py b/jarvis/cu/indicator/protocol.py
new file mode 100644
index 0000000000..6010c4d5c6
--- /dev/null
+++ b/jarvis/cu/indicator/protocol.py
@@ -0,0 +1,90 @@
+"""JSON-lines IPC vocabulary between the indicator controller (main
+process) and the renderer sidecar.
+
+One JSON object per line on the sidecar's stdin::
+
+ {"cmd": "show", "hint": "Esc to cancel"} # fade the border in
+ {"cmd": "hide"} # fade the border out
+ {"cmd": "blank"} # hide INSTANTLY (capture guard)
+ {"cmd": "unblank"} # restore after a frame grab
+ {"cmd": "quit"} # exit the sidecar
+
+The sidecar answers each command with one JSON line on stdout::
+
+ {"ok": "<cmd>"}
+
+and exits on stdin EOF (parent death) even without a ``quit``. Everything
+is best-effort: the controller treats a missing/late ack as "sidecar gone"
+and degrades; the sidecar ignores lines it cannot parse.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+CMD_SHOW = "show"
+CMD_HIDE = "hide"
+CMD_BLANK = "blank"
+CMD_UNBLANK = "unblank"
+CMD_QUIT = "quit"
+
+ALL_COMMANDS = frozenset(
+ {CMD_SHOW, CMD_HIDE, CMD_BLANK, CMD_UNBLANK, CMD_QUIT}
+)
+
+#: Sidecar exit code when no usable GUI stack exists (PySide6 missing or
+#: no display). The controller logs it as an expected degradation.
+EXIT_NO_GUI = 3
+
+
+def encode_command(cmd: str, **fields: Any) -> str:
+ """Serialize one command line (newline-terminated)."""
+ payload = {"cmd": cmd, **fields}
+ return json.dumps(payload, ensure_ascii=False) + "\n"
+
+
+def decode_command(line: str) -> dict[str, Any] | None:
+ """Parse one stdin line; ``None`` for blank/garbled/unknown input."""
+ line = line.strip()
+ if not line:
+ return None
+ try:
+ payload = json.loads(line)
+ except (ValueError, TypeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ if payload.get("cmd") not in ALL_COMMANDS:
+ return None
+ return payload
+
+
+def encode_ack(cmd: str) -> str:
+ return json.dumps({"ok": cmd}) + "\n"
+
+
+def decode_ack(line: str) -> str | None:
+ """Parse one ack line from the sidecar; ``None`` if it isn't one."""
+ try:
+ payload = json.loads(line.strip())
+ except (ValueError, TypeError):
+ return None
+ if isinstance(payload, dict) and isinstance(payload.get("ok"), str):
+ return payload["ok"]
+ return None
+
+
+__all__ = [
+ "ALL_COMMANDS",
+ "CMD_BLANK",
+ "CMD_HIDE",
+ "CMD_QUIT",
+ "CMD_SHOW",
+ "CMD_UNBLANK",
+ "EXIT_NO_GUI",
+ "decode_ack",
+ "decode_command",
+ "encode_ack",
+ "encode_command",
+]
diff --git a/jarvis/cu/indicator/renderer.py b/jarvis/cu/indicator/renderer.py
new file mode 100644
index 0000000000..8d3a526f9f
--- /dev/null
+++ b/jarvis/cu/indicator/renderer.py
@@ -0,0 +1,368 @@
+"""PySide6 renderer for the Computer-Use screen indicator.
+
+Runs ONLY inside the sidecar process (``python -m jarvis.cu.indicator``).
+This module imports PySide6 at module level — the main Jarvis process must
+never import it (boot-path discipline, AP-26); the ``__main__`` entry
+guards the import and exits with ``protocol.EXIT_NO_GUI`` when the GUI
+stack is unavailable.
+
+Visual contract (maintainer-approved 2026-07-15):
+
+- A soft gold glow along every edge of EVERY monitor, breathing on a
+ ~2.4 s sine loop, 300 ms fade in/out — Codex-style, in Jarvis gold.
+- An "Esc to cancel" pill top-center on the primary monitor (text arrives
+ pre-localized from the controller; omitted when Escape isn't armable).
+- Frameless, always-on-top, fully click-through, never activates, and on
+ Windows excluded from screen capture (see ``win32.py``).
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import threading
+from contextlib import suppress
+
+from PySide6.QtCore import (
+ QEasingCurve,
+ QObject,
+ Qt,
+ QVariantAnimation,
+ Signal,
+ Slot,
+)
+from PySide6.QtGui import (
+ QColor,
+ QFont,
+ QFontMetricsF,
+ QGuiApplication,
+ QLinearGradient,
+ QPainter,
+ QPen,
+)
+from PySide6.QtWidgets import QApplication, QWidget
+
+from jarvis.cu.indicator import protocol
+from jarvis.cu.indicator.win32 import exclude_from_capture, harden_window
+
+# Jarvis gold — matches ui/orb BUBBLE_BORDER_HEX (#FFE500) at the crisp
+# edge, falling off through the softer [ui].bar_accent gold (#e7c46e).
+_EDGE_RGB = (255, 229, 0)
+_SOFT_RGB = (231, 196, 110)
+
+_GLOW_MIN_PX = 28
+_GLOW_MAX_PX = 90
+_EDGE_LINE_PX = 3
+
+_PULSE_PERIOD_MS = 2400
+_PULSE_FLOOR = 0.55 # breathing dims to 55 %, never fully out
+_FADE_MS = 300
+
+
+class _GlowWindow(QWidget):
+ """One click-through glow window covering one monitor."""
+
+ def __init__(self, screen, *, with_pill: bool, hint: str) -> None:
+ super().__init__(None)
+ self._with_pill = with_pill
+ self._hint = hint
+ self.setWindowFlags(
+ Qt.WindowType.FramelessWindowHint
+ | Qt.WindowType.WindowStaysOnTopHint
+ | Qt.WindowType.WindowTransparentForInput
+ | Qt.WindowType.WindowDoesNotAcceptFocus
+ | Qt.WindowType.Tool
+ | Qt.WindowType.NoDropShadowWindowHint
+ )
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ self.setScreen(screen)
+ self.setGeometry(screen.geometry())
+ self.setWindowOpacity(0.0)
+
+ def set_hint(self, hint: str) -> None:
+ if hint != self._hint:
+ self._hint = hint
+ self.update()
+
+ # -- Windows hardening ------------------------------------------------
+ def _apply_native_styles(self) -> None:
+ hwnd = int(self.winId())
+ harden_window(hwnd)
+ exclude_from_capture(hwnd)
+
+ def showEvent(self, event) -> None: # noqa: N802 (Qt override)
+ super().showEvent(event)
+ # Reapply on EVERY show: Windows silently drops layered styles on
+ # some style mutations (BUG-030 class), and blank/unblank cycles
+ # re-show the window.
+ self._apply_native_styles()
+
+ # -- painting ----------------------------------------------------------
+ def paintEvent(self, event) -> None: # noqa: N802 (Qt override)
+ del event
+ w = self.width()
+ h = self.height()
+ if w <= 0 or h <= 0:
+ return
+ glow = max(_GLOW_MIN_PX, min(_GLOW_MAX_PX, int(min(w, h) * 0.05)))
+
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ painter.setPen(Qt.PenStyle.NoPen)
+
+ edge = QColor(*_EDGE_RGB, 190)
+ soft = QColor(*_SOFT_RGB, 110)
+ clear = QColor(*_SOFT_RGB, 0)
+
+ def _edge_gradient(x1: float, y1: float, x2: float, y2: float):
+ grad = QLinearGradient(x1, y1, x2, y2)
+ grad.setColorAt(0.0, edge)
+ grad.setColorAt(0.35, soft)
+ grad.setColorAt(1.0, clear)
+ return grad
+
+ painter.fillRect(0, 0, w, glow, _edge_gradient(0, 0, 0, glow))
+ painter.fillRect(0, h - glow, w, glow, _edge_gradient(0, h, 0, h - glow))
+ painter.fillRect(0, 0, glow, h, _edge_gradient(0, 0, glow, 0))
+ painter.fillRect(w - glow, 0, glow, h, _edge_gradient(w, 0, w - glow, 0))
+
+ # Crisp definition line at the very edge.
+ pen = QPen(QColor(*_EDGE_RGB, 235))
+ pen.setWidth(_EDGE_LINE_PX)
+ painter.setPen(pen)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ inset = _EDGE_LINE_PX // 2
+ painter.drawRect(inset, inset, w - _EDGE_LINE_PX, h - _EDGE_LINE_PX)
+
+ if self._with_pill and self._hint:
+ self._paint_pill(painter, w)
+ painter.end()
+
+ def _paint_pill(self, painter: QPainter, w: int) -> None:
+ font = QFont()
+ font.setPointSizeF(10.5)
+ font.setWeight(QFont.Weight.Medium)
+ painter.setFont(font)
+ metrics = QFontMetricsF(font)
+ pad_x, pad_y = 16.0, 7.0
+ text_w = metrics.horizontalAdvance(self._hint)
+ pill_w = text_w + 2 * pad_x
+ pill_h = metrics.height() + 2 * pad_y
+ x = (w - pill_w) / 2.0
+ y = 18.0
+ radius = pill_h / 2.0
+
+ painter.setPen(QPen(QColor(*_SOFT_RGB, 200), 1.0))
+ painter.setBrush(QColor(18, 18, 18, 175))
+ painter.drawRoundedRect(int(x), int(y), int(pill_w), int(pill_h), radius, radius)
+ painter.setPen(QColor(255, 240, 200, 235))
+ painter.drawText(
+ int(x),
+ int(y),
+ int(pill_w),
+ int(pill_h),
+ Qt.AlignmentFlag.AlignCenter,
+ self._hint,
+ )
+
+
+class Renderer(QObject):
+ """Owns the per-monitor windows, the animations, and the IPC slots."""
+
+ def __init__(self, app: QApplication) -> None:
+ super().__init__()
+ self._app = app
+ self._windows: list[_GlowWindow] = []
+ self._hint = ""
+ self._active = False # "show" was requested and not yet "hide"
+ self._blanked = False # capture guard currently hiding the border
+
+ # Breathing pulse: 0 → 1 → 0 per period, applied as a factor on
+ # top of the master fade so show/hide and breathing compose.
+ self._pulse_value = 1.0
+ self._pulse = QVariantAnimation(self)
+ self._pulse.setStartValue(0.0)
+ self._pulse.setEndValue(0.0)
+ self._pulse.setKeyValueAt(0.5, 1.0)
+ self._pulse.setDuration(_PULSE_PERIOD_MS)
+ self._pulse.setEasingCurve(QEasingCurve.Type.InOutSine)
+ self._pulse.setLoopCount(-1)
+ self._pulse.valueChanged.connect(self._on_pulse)
+
+ # Master fade 0..1 (show/hide).
+ self._master_value = 0.0
+ self._master = QVariantAnimation(self)
+ self._master.setDuration(_FADE_MS)
+ self._master.valueChanged.connect(self._on_master)
+ self._master.finished.connect(self._on_master_done)
+
+ # -- IPC entry (runs on the Qt main thread via queued signal) ---------
+ @Slot(str)
+ def on_line(self, raw: str) -> None:
+ payload = protocol.decode_command(raw)
+ if payload is None:
+ return
+ cmd = payload["cmd"]
+ if cmd == protocol.CMD_SHOW:
+ self._show(str(payload.get("hint", "")))
+ elif cmd == protocol.CMD_HIDE:
+ self._hide()
+ elif cmd == protocol.CMD_BLANK:
+ # hide() reaches the platform window synchronously and the
+ # subsequent grab travels through the same display-server
+ # queue, so an immediate ack keeps ordering AND correctness.
+ self._blank()
+ elif cmd == protocol.CMD_UNBLANK:
+ self._unblank()
+ elif cmd == protocol.CMD_QUIT:
+ _ack(cmd)
+ self._app.quit()
+ return
+ _ack(cmd)
+
+ # -- commands ----------------------------------------------------------
+ def _show(self, hint: str) -> None:
+ self._hint = hint
+ self._active = True
+ self._blanked = False
+ self._ensure_windows()
+ for win in self._windows:
+ win.set_hint(hint)
+ win.show()
+ self._pulse.start()
+ self._fade_to(1.0)
+
+ def _hide(self) -> None:
+ self._active = False
+ self._fade_to(0.0)
+
+ def _blank(self) -> None:
+ if not self._active:
+ return
+ self._blanked = True
+ for win in self._windows:
+ win.hide()
+
+ def _unblank(self) -> None:
+ if not self._active or not self._blanked:
+ return
+ self._blanked = False
+ for win in self._windows:
+ win.show()
+
+ # -- screens -----------------------------------------------------------
+ def _ensure_windows(self) -> None:
+ for win in self._windows:
+ win.close()
+ win.deleteLater()
+ primary = QGuiApplication.primaryScreen()
+ self._windows = [
+ _GlowWindow(screen, with_pill=screen is primary, hint=self._hint)
+ for screen in QGuiApplication.screens()
+ ]
+ self._apply_opacity()
+
+ def on_screens_changed(self, *_args) -> None:
+ """Monitor hotplug while visible → rebuild windows in place."""
+ if self._active:
+ self._ensure_windows()
+ if not self._blanked:
+ for win in self._windows:
+ win.show()
+
+ # -- animation plumbing --------------------------------------------------
+ def _fade_to(self, target: float) -> None:
+ self._master.stop()
+ self._master.setStartValue(self._master_value)
+ self._master.setEndValue(target)
+ self._master.start()
+
+ def _on_pulse(self, value) -> None:
+ self._pulse_value = float(value)
+ self._apply_opacity()
+
+ def _on_master(self, value) -> None:
+ self._master_value = float(value)
+ self._apply_opacity()
+
+ def _on_master_done(self) -> None:
+ if self._master_value <= 0.0 and not self._active:
+ self._pulse.stop()
+ for win in self._windows:
+ win.hide()
+
+ def _apply_opacity(self) -> None:
+ breathing = _PULSE_FLOOR + (1.0 - _PULSE_FLOOR) * self._pulse_value
+ opacity = max(0.0, min(1.0, self._master_value * breathing))
+ for win in self._windows:
+ win.setWindowOpacity(opacity)
+
+
+class _StdinPump(QObject):
+ """Reads stdin on a daemon thread; signals deliver to the Qt thread."""
+
+ line = Signal(str)
+ eof = Signal()
+
+ def start(self) -> None:
+ threading.Thread(
+ target=self._run, name="cu-indicator-stdin", daemon=True
+ ).start()
+
+ def _run(self) -> None:
+ # A dying pipe simply means "parent gone" — treated as EOF.
+ with suppress(Exception):
+ for raw in sys.stdin:
+ self.line.emit(raw)
+ self.eof.emit()
+
+
+def _ack(cmd: str) -> None:
+ # A failed ack means the parent is gone; the EOF path quits the app.
+ with suppress(Exception):
+ sys.stdout.write(protocol.encode_ack(cmd))
+ sys.stdout.flush()
+
+
+def run() -> int:
+ """Sidecar main loop. Returns the process exit code."""
+ # Per-monitor DPI: hand Qt the real per-screen scale factors so the
+ # glow hugs the true monitor edges on mixed-DPI setups.
+ QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
+ Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
+ )
+ try:
+ app = QApplication(sys.argv[:1] or ["cu-indicator"])
+ except Exception as exc: # noqa: BLE001 — no display / no platform plugin
+ sys.stderr.write(
+ f"cu-indicator: no usable display ({exc!r}) — indicator disabled.\n"
+ )
+ return protocol.EXIT_NO_GUI
+ # All windows are frequently hidden (blank/hide) — that must never
+ # terminate the sidecar; only stdin EOF or "quit" does.
+ app.setQuitOnLastWindowClosed(False)
+
+ renderer = Renderer(app)
+ QGuiApplication.instance().screenAdded.connect(renderer.on_screens_changed)
+ QGuiApplication.instance().screenRemoved.connect(renderer.on_screens_changed)
+
+ pump = _StdinPump()
+ pump.line.connect(renderer.on_line, Qt.ConnectionType.QueuedConnection)
+ pump.eof.connect(app.quit, Qt.ConnectionType.QueuedConnection)
+ pump.start()
+
+ if os.environ.get("JARVIS_CU_INDICATOR_AUTOSHOW"):
+ # Debug/verification convenience: show immediately without a parent.
+ renderer.on_line(
+ protocol.encode_command(
+ protocol.CMD_SHOW,
+ hint=os.environ.get("JARVIS_CU_INDICATOR_HINT", "Esc to cancel"),
+ )
+ )
+
+ return app.exec()
+
+
+__all__ = ["Renderer", "run"]
diff --git a/jarvis/cu/indicator/self_input.py b/jarvis/cu/indicator/self_input.py
new file mode 100644
index 0000000000..a340181aea
--- /dev/null
+++ b/jarvis/cu/indicator/self_input.py
@@ -0,0 +1,60 @@
+"""Self-input suppression for the Escape-to-cancel listener.
+
+The Computer-Use engine can legitimately SEND an Escape keystroke as part
+of a mission (close a dialog, leave a menu). OS-level hotkey listeners see
+synthetic input exactly like human input, so without suppression Jarvis
+would cancel itself the moment it types Esc.
+
+The actuation layer stamps a monotonic timestamp right before it
+synthesizes any combo containing Escape; the indicator controller ignores
+Escape hotkey events that arrive within ``SUPPRESS_WINDOW_MS`` of the
+stamp. Thread-safe (actuation runs off the event loop).
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+
+SUPPRESS_WINDOW_MS = 400
+
+_ESC_NAMES = frozenset({"esc", "escape"})
+
+_lock = threading.Lock()
+_last_synthetic_esc_ns = 0
+
+
+def stamp_if_escape(keys: list[str] | tuple[str, ...]) -> bool:
+ """Record "Jarvis is about to type Esc" when the combo contains it."""
+ if not any(str(k).strip().lower() in _ESC_NAMES for k in keys):
+ return False
+ global _last_synthetic_esc_ns
+ with _lock:
+ _last_synthetic_esc_ns = time.monotonic_ns()
+ return True
+
+
+def esc_recently_synthesized(
+ window_ms: int = SUPPRESS_WINDOW_MS,
+) -> bool:
+ """True while a Jarvis-typed Esc is fresh enough to explain a hotkey hit."""
+ with _lock:
+ stamp = _last_synthetic_esc_ns
+ if stamp == 0:
+ return False
+ return (time.monotonic_ns() - stamp) < window_ms * 1_000_000
+
+
+def reset() -> None:
+ """Test hook: forget any previous stamp."""
+ global _last_synthetic_esc_ns
+ with _lock:
+ _last_synthetic_esc_ns = 0
+
+
+__all__ = [
+ "SUPPRESS_WINDOW_MS",
+ "esc_recently_synthesized",
+ "reset",
+ "stamp_if_escape",
+]
diff --git a/jarvis/cu/indicator/win32.py b/jarvis/cu/indicator/win32.py
new file mode 100644
index 0000000000..05229417c0
--- /dev/null
+++ b/jarvis/cu/indicator/win32.py
@@ -0,0 +1,91 @@
+"""Win32 window hardening for the indicator sidecar (ctypes, lazy).
+
+Two jobs, both quiet no-ops on every non-Windows platform:
+
+- ``harden_window(hwnd)`` — belt-and-suspenders click-through: Qt already
+ sets ``WindowTransparentForInput``, but Windows silently drops layered
+ styles on some style mutations (BUG-030 class), so the extended styles
+ are (re)applied directly and must be reapplied after show/screen-change.
+- ``exclude_from_capture(hwnd)`` — ``SetWindowDisplayAffinity`` with
+ ``WDA_EXCLUDEFROMCAPTURE`` so the border never appears in screenshots,
+ including Computer-Use's OWN perception frames (Windows 10 2004+).
+ Set ``JARVIS_CU_INDICATOR_CAPTURABLE=1`` to skip this — used by the
+ live-verification flow, which needs to SEE the border in a screenshot.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+
+log = logging.getLogger(__name__)
+
+_GWL_EXSTYLE = -20
+_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"
+
+
+def _user32():
+ if os.name != "nt":
+ return None
+ import ctypes # noqa: PLC0415
+
+ return ctypes.windll.user32 # type: ignore[attr-defined]
+
+
+def harden_window(hwnd: int) -> bool:
+ """OR the click-through/no-activate extended styles onto ``hwnd``."""
+ user32 = _user32()
+ if user32 is None or not hwnd:
+ return False
+ try:
+ style = user32.GetWindowLongW(hwnd, _GWL_EXSTYLE)
+ 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
+ except Exception: # noqa: BLE001
+ log.debug("harden_window failed for hwnd=%s", hwnd, exc_info=True)
+ return False
+
+
+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
+
+
+def capture_exclusion_available() -> bool:
+ """True where the OS can hide the border from screenshots (Windows).
+
+ Platforms without this API need the blank/unblank capture guard
+ around Computer-Use's own frame grabs instead.
+ """
+ return os.name == "nt"
+
+
+__all__ = [
+ "CAPTURABLE_ENV",
+ "capture_exclusion_available",
+ "exclude_from_capture",
+ "harden_window",
+]
diff --git a/jarvis/harness/computer_use_context.py b/jarvis/harness/computer_use_context.py
index a40eca5f78..7ee7283fde 100644
--- a/jarvis/harness/computer_use_context.py
+++ b/jarvis/harness/computer_use_context.py
@@ -153,21 +153,29 @@ _CU_SUPPRESS_UNTIL = 0.0
_CU_SUPPRESS_GRACE_S = 8.0
-def cancel_active_cu(reason: str = "voice_hangup") -> bool:
- """Cancel EVERY active Computer-Use mission AND open the post-hangup
- suppression window so a mission starting moments later is aborted too.
+def cancel_active_cu(
+ reason: str = "voice_hangup", *, suppress_new: bool = True,
+) -> bool:
+ """Cancel EVERY active Computer-Use mission AND (by default) open the
+ post-hangup suppression window so a mission starting moments later is
+ aborted too.
Cancels ALL registered tokens (overlapping missions are common — CU runs as
a detached background task), not just the most recent. Returns True if at
least one live token was cancelled. Never raises (the hangup path must never
crash) — a token whose ``cancel`` raises is skipped, the rest still cancel.
+
+ ``suppress_new=False`` skips the suppression window: the Escape-to-cancel
+ indicator path means "stop what is running NOW", not "and refuse the next
+ request" — a user may press Esc and immediately ask for something else.
"""
global _CU_SUPPRESS_UNTIL
- try:
- import time # noqa: PLC0415
- _CU_SUPPRESS_UNTIL = time.monotonic() + _CU_SUPPRESS_GRACE_S
- except Exception: # noqa: BLE001
- pass
+ if suppress_new:
+ try:
+ import time # noqa: PLC0415
+ _CU_SUPPRESS_UNTIL = time.monotonic() + _CU_SUPPRESS_GRACE_S
+ except Exception: # noqa: BLE001
+ pass
cancelled_any = False
for tok in list(_ACTIVE_CU_TOKENS):
try:
diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.py
index f79a9869e0..08f9e46254 100644
--- a/jarvis/plugins/harness/computer_use.py
+++ b/jarvis/plugins/harness/computer_use.py
@@ -14,9 +14,11 @@ import asyncio
import logging
import sys
import time
+import uuid
from collections.abc import AsyncIterator
from jarvis.control import CancelScope
+from jarvis.core.events import CUControlEnded, CUControlStarted
from jarvis.core.protocols import HarnessResult, HarnessTask
from jarvis.harness.computer_use_context import (
ComputerUseContext,
@@ -29,6 +31,18 @@ from jarvis.harness.computer_use_context import (
_log = logging.getLogger(__name__)
_TIMEOUT_EXIT_CODE = 124
+_CANCEL_EXIT_CODE = 130
+
+
+async def _publish_cu_control(bus, event) -> None:
+ """Publish a control-indicator event; a publish failure must never
+ break the mission (the indicator is strictly best-effort)."""
+ if bus is None:
+ return
+ try:
+ await bus.publish(event)
+ except Exception: # noqa: BLE001
+ _log.debug("[cu] control event publish failed", exc_info=True)
def _resolve_run_cu_loop():
@@ -158,6 +172,15 @@ class ComputerUseHarness:
# registry is a SET — concurrent CU missions each register so a
# single hangup cancels them ALL (BUG-CU-CONCURRENT-CANCEL).
register_active_cu_token(token)
+ # Control-indicator contract (jarvis.cu.indicator): Started fires
+ # once the token is registered — i.e. the moment this mission may
+ # actually drive mouse/keyboard — and Ended ALWAYS fires in the
+ # finally below, on every exit path.
+ mission_id = uuid.uuid4().hex[:12]
+ await _publish_cu_control(
+ ctx.bus, CUControlStarted(mission_id=mission_id)
+ )
+ end_reason = "finished"
run_cu_loop = _resolve_run_cu_loop()
stream = run_cu_loop(task, ctx, cancel_token=token)
try:
@@ -174,8 +197,13 @@ class ComputerUseHarness:
return
yield chunk
if chunk.is_final:
+ if chunk.exit_code == _CANCEL_EXIT_CODE:
+ end_reason = "cancelled"
+ elif chunk.exit_code != 0:
+ end_reason = "error"
return
except TimeoutError:
+ end_reason = "timeout"
token.cancel("computer_use_harness_timeout")
duration_ms = (time.time_ns() - t_start) // 1_000_000
yield HarnessResult(
@@ -192,6 +220,10 @@ class ComputerUseHarness:
# CANCEL: clearing the whole registry here orphaned the sibling
# so a later hangup found no token at all).
unregister_active_cu_token(token)
+ await _publish_cu_control(
+ ctx.bus,
+ CUControlEnded(mission_id=mission_id, reason=end_reason),
+ )
async def cancel(self) -> None:
"""Aborts the running invoke.
diff --git a/pyproject.toml b/pyproject.toml
index f9a196e8e5..2dd69a3b37 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -228,6 +228,12 @@ desktop = [
# no-op when they are absent.
"pyautogui>=0.9.54",
"mss>=10.0",
+ # Computer-Use screen indicator (jarvis/cu/indicator): the yellow glow
+ # border + "Esc to cancel" pill rendered by a small PySide6 sidecar
+ # process. Essentials only (QtCore/QtGui/QtWidgets — no WebEngine).
+ # Imported ONLY inside the sidecar; the controller probes for it and
+ # degrades to a logged no-op when absent (headless/base install).
+ "pyside6-essentials>=6.7",
# Drag-drop ONTO the floating overlay (bar/mascot): the cross-platform tkdnd
# Tcl extension, with bundled binaries for Windows / macOS / Linux. Registered
# onto the live Tk root in place (jarvis/overlay/drop_target.py). All-platform
diff --git a/tests/unit/cu/indicator/test_capture_guard.py b/tests/unit/cu/indicator/test_capture_guard.py
new file mode 100644
index 0000000000..ed925b50fa
--- /dev/null
+++ b/tests/unit/cu/indicator/test_capture_guard.py
@@ -0,0 +1,60 @@
+"""Fail-open capture guard around CU frame grabs."""
+from __future__ import annotations
+
+from contextlib import contextmanager
+
+import pytest
+
+from jarvis.cu.indicator import capture_guard
+
+
[email protected](autouse=True)
+def _clean_hook():
+ capture_guard.unregister_hook()
+ yield
+ capture_guard.unregister_hook()
+
+
+def test_no_hook_is_a_passthrough() -> None:
+ with capture_guard.indicator_suppressed():
+ pass # must not raise, must not block
+
+
+def test_hook_wraps_the_grab() -> None:
+ events: list[str] = []
+
+ @contextmanager
+ def hook():
+ events.append("blank")
+ try:
+ yield
+ finally:
+ events.append("unblank")
+
+ capture_guard.register_hook(hook)
+ with capture_guard.indicator_suppressed():
+ events.append("grab")
+ assert events == ["blank", "grab", "unblank"]
+
+
+def test_hook_factory_raising_fails_open() -> None:
+ def broken_hook():
+ raise RuntimeError("sidecar gone")
+
+ capture_guard.register_hook(broken_hook)
+ ran = False
+ with capture_guard.indicator_suppressed():
+ ran = True
+ assert ran is True
+
+
+def test_unregister_restores_passthrough() -> None:
+ @contextmanager
+ def hook():
+ raise AssertionError("must not be called after unregister")
+ yield # pragma: no cover
+
+ capture_guard.register_hook(hook)
+ capture_guard.unregister_hook()
+ with capture_guard.indicator_suppressed():
+ pass
diff --git a/tests/unit/cu/indicator/test_controller.py b/tests/unit/cu/indicator/test_controller.py
new file mode 100644
index 0000000000..69adf745f5
--- /dev/null
+++ b/tests/unit/cu/indicator/test_controller.py
@@ -0,0 +1,183 @@
+"""CUIndicatorController: refcount, capability gating, Escape cancel, hints."""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import CUControlEnded, CUControlStarted
+from jarvis.cu.indicator import controller as controller_mod
+from jarvis.cu.indicator.controller import (
+ _ESC_HINTS,
+ CUIndicatorController,
+ wire_cu_indicator,
+)
+
+
+def _quiet_controller(
+ monkeypatch: pytest.MonkeyPatch, bus: EventBus
+) -> tuple[CUIndicatorController, list[str]]:
+ """A wired controller whose heavy sides (sidecar, hotkey) are recorded
+ fakes — the refcount logic runs for real."""
+ calls: list[str] = []
+ ctl = CUIndicatorController(bus)
+
+ async def fake_activate() -> None:
+ calls.append("activate")
+
+ async def fake_deactivate() -> None:
+ calls.append("deactivate")
+
+ monkeypatch.setattr(ctl, "_activate", fake_activate)
+ monkeypatch.setattr(ctl, "_deactivate", fake_deactivate)
+ ctl.wire()
+ return ctl, calls
+
+
+async def test_refcount_two_concurrent_missions(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ bus = EventBus()
+ _ctl, calls = _quiet_controller(monkeypatch, bus)
+
+ await bus.publish(CUControlStarted(mission_id="a"))
+ await bus.publish(CUControlStarted(mission_id="b"))
+ assert calls == ["activate"], "second overlapping mission must not re-show"
+
+ await bus.publish(CUControlEnded(mission_id="a"))
+ assert calls == ["activate"], "border must stay while a sibling still runs"
+
+ await bus.publish(CUControlEnded(mission_id="b"))
+ assert calls == ["activate", "deactivate"]
+
+
+async def test_stray_ended_without_started_is_ignored(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ bus = EventBus()
+ _ctl, calls = _quiet_controller(monkeypatch, bus)
+ await bus.publish(CUControlEnded(mission_id="ghost"))
+ assert calls == []
+
+
+async def test_headless_host_never_spawns_sidecar(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No display → activate arms nothing visual and never touches Popen."""
+ bus = EventBus()
+ ctl = CUIndicatorController(bus)
+ ctl.wire()
+
+ monkeypatch.setattr(ctl, "_arm_escape", lambda: False)
+ monkeypatch.setattr(
+ CUIndicatorController,
+ "_border_capability",
+ staticmethod(lambda: (False, "no display on this host (headless)")),
+ )
+
+ def _explode() -> None: # pragma: no cover — the assertion IS the test
+ raise AssertionError("sidecar must not spawn on a headless host")
+
+ monkeypatch.setattr(ctl, "_spawn_sidecar", _explode)
+ await bus.publish(CUControlStarted(mission_id="a"))
+ await bus.publish(CUControlEnded(mission_id="a"))
+
+
+async def test_disabled_config_skips_border_but_arms_escape(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ bus = EventBus()
+ ctl = CUIndicatorController(bus)
+ ctl.wire()
+ armed: list[bool] = []
+ monkeypatch.setattr(
+ ctl, "_arm_escape", lambda: armed.append(True) or True
+ )
+ monkeypatch.setattr(
+ controller_mod, "_screen_indicator_enabled", lambda: False
+ )
+ monkeypatch.setattr(
+ ctl,
+ "_spawn_sidecar",
+ lambda: (_ for _ in ()).throw(AssertionError("no sidecar when off")),
+ )
+ await bus.publish(CUControlStarted(mission_id="a"))
+ assert armed == [True], "Escape is a safety affordance — armed even with the visual off"
+ await bus.publish(CUControlEnded(mission_id="a"))
+
+
+async def test_escape_cancels_missions_without_suppression(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ seen: dict[str, Any] = {}
+
+ def fake_cancel(reason: str = "", *, suppress_new: bool = True) -> bool:
+ seen["reason"] = reason
+ seen["suppress_new"] = suppress_new
+ return True
+
+ import jarvis.harness.computer_use_context as cu_ctx
+
+ monkeypatch.setattr(cu_ctx, "cancel_active_cu", fake_cancel)
+ CUIndicatorController._cancel_all_missions()
+ assert seen == {"reason": "user_escape", "suppress_new": False}
+
+
+def test_hint_table_covers_every_supported_locale() -> None:
+ """Repo language rule: a phrase table carries ALL supported locales and
+ resolves through the one resolver."""
+ from jarvis.core.turn_language import resolve_output_language
+
+ supported = {
+ resolve_output_language(pin, "", "", default="en")
+ for pin in ("de", "en", "es")
+ }
+ assert supported == set(_ESC_HINTS.keys())
+ assert all(hint.strip() for hint in _ESC_HINTS.values())
+
+
+def test_wire_cu_indicator_is_idempotent_per_bus() -> None:
+ bus = EventBus()
+ first = wire_cu_indicator(bus)
+ second = wire_cu_indicator(bus)
+ assert first is not None
+ assert first is second
+ assert wire_cu_indicator(None) is None
+
+
+async def test_dead_pipe_disables_sidecar_quietly() -> None:
+ bus = EventBus()
+ ctl = CUIndicatorController(bus)
+
+ class _DeadStdin:
+ def write(self, _data: str) -> None:
+ raise BrokenPipeError
+
+ def flush(self) -> None: # pragma: no cover
+ raise BrokenPipeError
+
+ class _DeadProc:
+ stdin = _DeadStdin()
+
+ @staticmethod
+ def poll() -> None:
+ return None
+
+ ctl._proc = _DeadProc() # type: ignore[assignment]
+ assert ctl._send("show", hint="x") is False
+ assert ctl._proc is None, "a broken pipe must drop the sidecar handle"
+
+
+async def test_suppress_for_grab_fails_open_without_acks() -> None:
+ """A blank that never gets acked must still let the grab run."""
+ bus = EventBus()
+ ctl = CUIndicatorController(bus)
+ monkeypatch_sent: list[str] = []
+ ctl._send = lambda cmd, **f: monkeypatch_sent.append(cmd) or True # type: ignore[method-assign]
+
+ ran = False
+ with ctl._suppress_for_grab():
+ ran = True
+ assert ran is True
+ assert monkeypatch_sent == ["blank", "unblank"]
diff --git a/tests/unit/cu/indicator/test_protocol.py b/tests/unit/cu/indicator/test_protocol.py
new file mode 100644
index 0000000000..4fc63e2a40
--- /dev/null
+++ b/tests/unit/cu/indicator/test_protocol.py
@@ -0,0 +1,40 @@
+"""IPC protocol round-trip + garbage tolerance for the CU screen indicator."""
+from __future__ import annotations
+
+from jarvis.cu.indicator import protocol
+
+
+def test_command_round_trip_with_fields() -> None:
+ line = protocol.encode_command(protocol.CMD_SHOW, hint="Esc to cancel")
+ assert line.endswith("\n")
+ payload = protocol.decode_command(line)
+ assert payload == {"cmd": "show", "hint": "Esc to cancel"}
+
+
+def test_every_command_round_trips() -> None:
+ for cmd in protocol.ALL_COMMANDS:
+ assert protocol.decode_command(protocol.encode_command(cmd)) == {
+ "cmd": cmd
+ }
+
+
+def test_decode_command_tolerates_garbage() -> None:
+ assert protocol.decode_command("") is None
+ assert protocol.decode_command(" \n") is None
+ assert protocol.decode_command("not json") is None
+ assert protocol.decode_command('"a bare string"') is None
+ assert protocol.decode_command('{"cmd": "reboot"}') is None
+ assert protocol.decode_command("[1, 2, 3]") is None
+
+
+def test_ack_round_trip_and_garbage() -> None:
+ assert protocol.decode_ack(protocol.encode_ack("blank")) == "blank"
+ assert protocol.decode_ack("nonsense") is None
+ assert protocol.decode_ack('{"err": "x"}') is None
+
+
+def test_hint_survives_non_ascii() -> None:
+ line = protocol.encode_command(protocol.CMD_SHOW, hint="Esc zum Abbrechen — läuft") # noqa: E501 # i18n-allow: localized pill copy under test
+ payload = protocol.decode_command(line)
+ assert payload is not None
+ assert payload["hint"].endswith("läuft") # i18n-allow: assertion on the same fixture
diff --git a/tests/unit/cu/indicator/test_self_input.py b/tests/unit/cu/indicator/test_self_input.py
new file mode 100644
index 0000000000..1b85cdaffb
--- /dev/null
+++ b/tests/unit/cu/indicator/test_self_input.py
@@ -0,0 +1,41 @@
+"""Self-typed-Escape suppression stamps (jarvis/cu/indicator/self_input)."""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.cu.indicator import self_input
+
+
[email protected](autouse=True)
+def _clean_stamp():
+ self_input.reset()
+ yield
+ self_input.reset()
+
+
+def test_escape_combo_stamps_and_suppresses() -> None:
+ assert self_input.stamp_if_escape(["esc"]) is True
+ assert self_input.esc_recently_synthesized() is True
+
+
+def test_escape_full_name_and_case_insensitive() -> None:
+ assert self_input.stamp_if_escape(["Escape"]) is True
+ assert self_input.stamp_if_escape(["ESC"]) is True
+
+
+def test_non_escape_combo_does_not_stamp() -> None:
+ assert self_input.stamp_if_escape(["ctrl", "s"]) is False
+ assert self_input.esc_recently_synthesized() is False
+
+
+def test_suppression_window_expires() -> None:
+ self_input.stamp_if_escape(["esc"])
+ # A zero-width window means the stamp is already stale.
+ assert self_input.esc_recently_synthesized(window_ms=0) is False
+ assert self_input.esc_recently_synthesized(window_ms=60_000) is True
+
+
+def test_reset_clears_stamp() -> None:
+ self_input.stamp_if_escape(["esc"])
+ self_input.reset()
+ assert self_input.esc_recently_synthesized() is False
diff --git a/tests/unit/cu/indicator/test_sidecar_smoke.py b/tests/unit/cu/indicator/test_sidecar_smoke.py
new file mode 100644
index 0000000000..a7cbb26320
--- /dev/null
+++ b/tests/unit/cu/indicator/test_sidecar_smoke.py
@@ -0,0 +1,72 @@
+"""Offscreen smoke test: the indicator sidecar boots, acks, and exits.
+
+Runs the real ``python -m jarvis.cu.indicator`` subprocess on Qt's
+offscreen platform plugin so it works on CI boxes without a display.
+Auto-skips when PySide6 is not installed (base install / headless floor).
+"""
+from __future__ import annotations
+
+import importlib.util
+import os
+import subprocess
+import sys
+
+import pytest
+
+from jarvis.cu.indicator import protocol
+
+pytestmark = pytest.mark.skipif(
+ importlib.util.find_spec("PySide6") is None,
+ reason="PySide6 not installed (indicator sidecar is a [desktop] extra)",
+)
+
+
+def test_sidecar_show_quit_round_trip() -> None:
+ env = os.environ.copy()
+ env["QT_QPA_PLATFORM"] = "offscreen"
+ env.pop("JARVIS_CU_INDICATOR_AUTOSHOW", None)
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "jarvis.cu.indicator"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ env=env,
+ )
+ try:
+ assert proc.stdin is not None and proc.stdout is not None
+ proc.stdin.write(
+ protocol.encode_command(protocol.CMD_SHOW, hint="Esc to cancel")
+ )
+ proc.stdin.write(protocol.encode_command(protocol.CMD_BLANK))
+ proc.stdin.write(protocol.encode_command(protocol.CMD_UNBLANK))
+ proc.stdin.write(protocol.encode_command(protocol.CMD_QUIT))
+ proc.stdin.flush()
+ out, err = proc.communicate(timeout=30)
+ except Exception:
+ proc.kill()
+ raise
+ acks = [
+ protocol.decode_ack(line)
+ for line in out.splitlines()
+ if protocol.decode_ack(line) is not None
+ ]
+ assert proc.returncode == 0, f"sidecar exited {proc.returncode}: {err}"
+ assert acks == ["show", "blank", "unblank", "quit"], f"acks={acks} err={err}"
+
+
+def test_sidecar_exits_cleanly_on_stdin_eof() -> None:
+ env = os.environ.copy()
+ env["QT_QPA_PLATFORM"] = "offscreen"
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "jarvis.cu.indicator"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ env=env,
+ )
+ assert proc.stdin is not None
+ proc.stdin.close() # parent "dies" — EOF must end the sidecar
+ assert proc.wait(timeout=30) == 0
diff --git a/tests/unit/harness/test_cu_control_events.py b/tests/unit/harness/test_cu_control_events.py
new file mode 100644
index 0000000000..d0aba8db31
--- /dev/null
+++ b/tests/unit/harness/test_cu_control_events.py
@@ -0,0 +1,165 @@
+"""CUControlStarted/Ended contract at the ComputerUseHarness boundary.
+
+The screen indicator (jarvis/cu/indicator) refcounts exactly these events,
+so the pair must fire once per mission on EVERY exit path — normal finish,
+cancel (exit 130), non-zero error exit, and harness timeout.
+"""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+
+import pytest
+
+from jarvis.control import KillSwitch
+from jarvis.core.bus import EventBus
+from jarvis.core.events import CUControlEnded, CUControlStarted
+from jarvis.core.protocols import HarnessResult, HarnessTask
+from jarvis.harness.computer_use_context import ComputerUseContext
+from jarvis.plugins.harness import computer_use as cu_mod
+from jarvis.plugins.harness.computer_use import ComputerUseHarness
+
+
+class _Recorder:
+ def __init__(self, bus: EventBus) -> None:
+ self.started: list[CUControlStarted] = []
+ self.ended: list[CUControlEnded] = []
+ bus.subscribe(CUControlStarted, self._on_started)
+ bus.subscribe(CUControlEnded, self._on_ended)
+
+ async def _on_started(self, ev: CUControlStarted) -> None:
+ self.started.append(ev)
+
+ async def _on_ended(self, ev: CUControlEnded) -> None:
+ self.ended.append(ev)
+
+
+def _ctx(bus: EventBus) -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=object(),
+ brain_manager=object(),
+ tool_executor=object(),
+ bus=bus,
+ kill_switch=KillSwitch(),
+ )
+
+
+def _stub_loop(*chunks: HarnessResult, hang: bool = False):
+ def factory(task: HarnessTask, ctx, cancel_token=None) -> AsyncIterator[HarnessResult]:
+ async def run() -> AsyncIterator[HarnessResult]:
+ for chunk in chunks:
+ yield chunk
+ if hang:
+ await asyncio.sleep(3600)
+ return run()
+
+ return factory
+
+
+async def _invoke_all(harness: ComputerUseHarness, task: HarnessTask) -> list[HarnessResult]:
+ return [chunk async for chunk in harness.invoke(task)]
+
+
[email protected](autouse=True)
+def _clean_cu_registry():
+ """Isolate from other tests: no stale suppression window / tokens."""
+ from jarvis.harness.computer_use_context import (
+ clear_cu_suppression,
+ register_active_cu_token,
+ )
+
+ clear_cu_suppression()
+ register_active_cu_token(None) # clears the registry (test-only path)
+ yield
+ clear_cu_suppression()
+ register_active_cu_token(None)
+
+
+def bus() -> EventBus:
+ return EventBus()
+
+
+async def test_started_and_ended_fire_once_on_success(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ rec = _Recorder(bus)
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(HarnessResult(stdout="done", exit_code=0, is_final=True)),
+ )
+ harness = ComputerUseHarness(context=_ctx(bus))
+ await _invoke_all(harness, HarnessTask(prompt="click something", timeout_s=5))
+
+ assert len(rec.started) == 1
+ assert len(rec.ended) == 1
+ assert rec.ended[0].reason == "finished"
+ assert rec.started[0].mission_id == rec.ended[0].mission_id
+ assert rec.started[0].mission_id != ""
+
+
+async def test_cancel_exit_code_reports_cancelled(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ rec = _Recorder(bus)
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(
+ HarnessResult(stdout="", exit_code=130, is_final=True)
+ ),
+ )
+ harness = ComputerUseHarness(context=_ctx(bus))
+ await _invoke_all(harness, HarnessTask(prompt="x", timeout_s=5))
+ assert [ev.reason for ev in rec.ended] == ["cancelled"]
+
+
+async def test_error_exit_code_reports_error(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ rec = _Recorder(bus)
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(HarnessResult(stdout="", exit_code=7, is_final=True)),
+ )
+ harness = ComputerUseHarness(context=_ctx(bus))
+ await _invoke_all(harness, HarnessTask(prompt="x", timeout_s=5))
+ assert [ev.reason for ev in rec.ended] == ["error"]
+
+
+async def test_timeout_reports_timeout_and_still_ends(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ rec = _Recorder(bus)
+ monkeypatch.setattr(cu_mod, "_resolve_run_cu_loop", lambda: _stub_loop(hang=True))
+ harness = ComputerUseHarness(context=_ctx(bus))
+ chunks = await _invoke_all(
+ harness, HarnessTask(prompt="x", timeout_s=1)
+ )
+ assert chunks and chunks[-1].exit_code == 124
+ assert len(rec.started) == 1
+ assert [ev.reason for ev in rec.ended] == ["timeout"]
+
+
+async def test_concurrent_missions_pair_up(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ rec = _Recorder(bus)
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(HarnessResult(stdout="ok", exit_code=0, is_final=True)),
+ )
+ ctx = _ctx(bus)
+ a = ComputerUseHarness(context=ctx)
+ b = ComputerUseHarness(context=ctx)
+ await asyncio.gather(
+ _invoke_all(a, HarnessTask(prompt="a", timeout_s=5)),
+ _invoke_all(b, HarnessTask(prompt="b", timeout_s=5)),
+ )
+ assert len(rec.started) == 2
+ assert len(rec.ended) == 2
+ assert {e.mission_id for e in rec.started} == {e.mission_id for e in rec.ended}
+ assert len({e.mission_id for e in rec.started}) == 2