Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(cu): keep Computer-Use working when a vision provider is merely busy
rubenluetke10-beepe34ae2647b46
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 90868c9023..8b34f835b1 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -8735,3 +8735,50 @@ guards), `test_session_postmortem.py`, `test_realtime_probe_eval.py`,`test_realtime_forensics.py`. Probe caveat: the local recognizer rides theconfigured cloud STT; an exhausted quota mutes the harness's groundinghalf — the transport metrics stay valid.++---++## BUG-126: Computer-Use went blind on a busy server, then crawled — and killed every global hotkey on its way out (HIGH, FIXED 2026-08-10)++**Symptoms (one voice session, 18:39–18:43, goal "open Elon's post").** The+first mission announced *"I can't see the screen right now"* although a funded+vision key was configured. The second and third missions did work, but every+single step took ~9 s, so the user hung up before anything finished. Nothing in+the UI said why, and the Escape cancel key stopped responding afterwards.++**Three independent roots in the same run:**++1. **A capacity blip was treated as a broken credential.** Gemini answered+ `503 … This model is currently experiencing high demand … usually+ temporary`. `_classify_provider_error` has no bucket for infra failures, so+ it fell to the `call_fail` default and `ComputerUsePlannerSelector`+ mission-blocked the candidate. The chain then walked into OpenRouter (402,+ no credits) and OpenAI (429, no credits) and raised+ `CUNoVisionProviderError` — the honest "no eyes" readback, for a provider+ that served a full mission three minutes later. Fix:+ `is_transient_provider_error` (capacity/infra codes and wordings, with+ credential/quota/rate-limit failures explicitly excluded), ONE in-place+ retry after 0.6 s, and a per-candidate transient budget so a first blip is+ forgiven while a real outage still falls out of the chain.+2. **The token headroom was re-discovered on every step.** `_DECIDE_MAX_TOKENS`+ is 320; the vision model cut its JSON at the cap on EVERY decision, so the+ existing one-shot headroom retry fired every time and the first reply was+ always thrown away — ~3 s of each ~9 s step. Truncation is a property of the+ MODEL, not of one call, so `brain_call` now remembers the (provider, model)+ pair in `_NEEDS_HEADROOM` and starts subsequent calls at the headroom. Safe+ only because the early-stop aggregator cuts the stream at the JSON boundary,+ so the raised ceiling costs nothing on a short reply.+3. **Arming the cancel key killed the hotkey poller.** `HotkeyChecker.run`+ binds `id_list = self.hotkeys.keys()` once and iterates that LIVE dict view+ every 20 ms. Arming `cu_cancel=[escape]` from the mission thread resized the+ dict mid-iteration → `RuntimeError: dictionary changed size during+ iteration` inside the poller thread, which died silently and took the Escape+ kill-switch plus the call/dictation shortcuts with it for the rest of the+ process. The library exposes no lock, so `_registry_mutation` pauses the+ shared poller, waits out one loop period, writes, and restarts it.++**Guards:** `tests/unit/cu/test_brain_call_resilience.py` (transient retry,+account failures never retried, per-mission transient budget, learned+headroom), `tests/unit/trigger/test_hotkey_registry_mutation_guard.py` (the+`FakeGlobalHotkeys.strict_poller` knob reproduces the live thread death — the+guard test fails without `_registry_mutation`).diff --git a/jarvis/cu/brain_call.py b/jarvis/cu/brain_call.pyindex 220d995745..61fa323192 100644--- a/jarvis/cu/brain_call.py+++ b/jarvis/cu/brain_call.py@@ -19,6 +19,7 @@ credential readback the legacy engine had."""from __future__ import annotations+import asyncioimport loggingfrom collections.abc import Callablefrom dataclasses import dataclass@@ -54,6 +55,45 @@ PromptBuilder = Callable[[str, Any], tuple[str, str]]#: step, so the log names the brain that ACTUALLY steps without flooding._serving_logged: tuple[str, str | None] | None = None+#: Pause before the single in-place retry of a transient provider failure —+#: long enough for a capacity spike to pass, short enough that the user does+#: not perceive a stall on top of the failed call.+_TRANSIENT_RETRY_DELAY_S = 0.6++#: (provider, model) pairs that already proved they cannot finish their JSON+#: inside the small per-call cap. Process-global on purpose: the truncation is+#: a property of the MODEL (thinking-by-default, or a gateway with no reasoning+#: knob), not of one mission — see :func:`_starting_tokens`.+_NEEDS_HEADROOM: set[tuple[str, str | None]] = set()+++def _headroom_tokens(max_tokens: int) -> int:+ """The ceiling a truncated candidate is (re-)tried with."""+ return max(2048, max_tokens * 4)+++def _starting_tokens(+ provider: str, model: str | None, max_tokens: int, *, early_stop_json: bool,+) -> int:+ """The cap the FIRST attempt uses for this candidate.++ A model that hit the cap once will hit it again on the very next step, so+ re-discovering it per step costs a wasted round-trip every single time —+ live 2026-08-10: EVERY Gemini step logged "hit the 320-token cap …+ retrying once with 2048" and spent ~3 s of a ~9 s decision on the reply+ that was thrown away. Once seen, start at the headroom directly. Safe only+ with the early-stop aggregator, which cuts the stream at the JSON boundary+ — so the raised ceiling costs nothing when the reply is short.+ """+ if early_stop_json and (provider, model) in _NEEDS_HEADROOM:+ return _headroom_tokens(max_tokens)+ return max_tokens+++def _reset_headroom_memory_for_tests() -> None:+ """Clear the learned per-model headroom — test-isolation hook only."""+ _NEEDS_HEADROOM.clear()+def _log_serving(provider: str, model: str | None) -> None:"""Log the serving brain identity once per change (the ground truth)."""@@ -225,6 +265,7 @@ async def call_vision_brain()from jarvis.harness.computer_use_planner import ( # noqa: PLC0415ComputerUsePlannerSelector,+ is_transient_provider_error,iter_last_resort_vision,)@@ -308,11 +349,16 @@ async def call_vision_brain()return await agg(brain.complete(req))- result = await _once(max_tokens)+ start_tokens = _starting_tokens(+ provider, model, max_tokens, early_stop_json=early_stop_json,+ )+ result = await _once(start_tokens)text = (result.text or "").strip()+ retry_tokens = _headroom_tokens(max_tokens)if (early_stop_jsonand text+ and start_tokens < retry_tokensand not has_complete_json_action(text)and is_length_truncated(result.finish_reason, text)):@@ -321,12 +367,15 @@ async def call_vision_brain(# the budget despite the reasoning hint (or a provider without a# thinking knob at all). ONE retry with real headroom; the# early-stop aggregator still cuts the stream at the JSON- # boundary, so the extra ceiling costs nothing on success.- retry_tokens = max(2048, max_tokens * 4)+ # boundary, so the extra ceiling costs nothing on success. The+ # candidate is remembered so the NEXT step starts at the headroom+ # instead of paying for this discovery again.+ _NEEDS_HEADROOM.add((provider, model))logger.info("[cu] %s(%s) reply hit the %d-token cap before completing "- "its JSON — retrying once with %d",- provider, model, max_tokens, retry_tokens,+ "its JSON — retrying once with %d (and starting there from "+ "now on)",+ provider, model, start_tokens, retry_tokens,)result = await _once(retry_tokens)text = (result.text or "").strip()@@ -335,12 +384,38 @@ async def call_vision_brain(return Nonereturn BrainReply(text=text, provider=provider, model=model)+ async def _try_with_transient_retry(+ provider: str, model: str | None, brain: Any,+ ) -> BrainReply | None:+ """``_try`` plus ONE in-place retry for a capacity/infra blip.++ Falling straight through to the next provider on a 503 is what left a+ mission blind while its only funded vision brain was merely busy (live+ 2026-08-10 18:39: Gemini answered "experiencing high demand", CU moved+ on to two out-of-credit providers and told the user it could not see+ the screen). Credential and quota failures are excluded by+ ``is_transient_provider_error`` — those must still fall through+ immediately so the honest "check your keys/credit" readback survives.+ """+ try:+ return await _try(provider, model, brain)+ except Exception as exc: # noqa: BLE001+ if not is_transient_provider_error(exc):+ raise+ logger.info(+ "[cu] %s(%s) hit a transient failure (%s) — one retry before "+ "falling through to the next provider",+ provider, model, str(exc)[:160],+ )+ await asyncio.sleep(_TRANSIENT_RETRY_DELAY_S)+ return await _try(provider, model, brain)+for idx, provider, model, brain in selector.iter_candidates(images_attached=images_attached,):attempted += 1try:- reply = await _try(provider, model, brain)+ reply = await _try_with_transient_retry(provider, model, brain)except Exception as exc: # noqa: BLE001selector.record_failure(provider, model, exc)logger.warning("[cu] brain provider %s(%s) failed: %s", provider, model, exc)diff --git a/jarvis/harness/computer_use_planner.py b/jarvis/harness/computer_use_planner.pyindex da379eacdd..b1dac9f219 100644--- a/jarvis/harness/computer_use_planner.py+++ b/jarvis/harness/computer_use_planner.py@@ -14,6 +14,62 @@ from jarvis.brain.manager import (log = logging.getLogger(__name__)+# Wordings that mean "the provider is momentarily overloaded / had a blip", NOT+# "your account is broken". Kept separate from the manager's classifier because+# only Computer-Use pays the full price for confusing the two: a mission runs one+# vision call PER STEP, so a single 30-second capacity spike used to knock the+# only funded vision brain out for the WHOLE mission (live 2026-08-10 18:39:25 —+# Gemini answered 503 "This model is currently experiencing high demand", CU+# mission-blocked it, fell through to two out-of-credit providers and told the+# user "I can't see the screen right now").+_TRANSIENT_MARKERS: tuple[str, ...] = (+ "service unavailable",+ "unavailable",+ "overloaded",+ "high demand",+ "try again later",+ "temporarily",+ "internal server error",+ "bad gateway",+ "gateway timeout",+ "timed out",+ "timeout",+ "connection reset",+ "connection aborted",+ "server disconnected",+)++#: HTTP codes that are capacity/infra, never credentials.+_TRANSIENT_STATUS: frozenset[int] = frozenset({500, 502, 503, 504, 529})++#: How many transient failures one (provider, model) may take before CU stops+#: offering it for the rest of the mission. One blip is forgiven; a provider+#: that is genuinely down falls out instead of costing every step a round-trip.+_MAX_TRANSIENT_PER_CANDIDATE = 2+++def is_transient_provider_error(exc: Exception, detail: str | None = None) -> bool:+ """True when *exc* reads as a capacity/infra blip worth one more try.++ Deliberately narrow: an account or credential problem (401/402/403, quota,+ billing) must NEVER land here, or CU would hammer a dead key on every step+ instead of degrading to the honest "check your keys/credit" readback.+ """+ from jarvis.brain.manager import ( # noqa: PLC0415+ _http_status_code,+ _is_account_blocked_exc,+ _is_missing_key_exc,+ _is_rate_limit_exc,+ )++ msg = (detail if detail is not None else str(exc)).lower()+ if _is_rate_limit_exc(exc) or _is_missing_key_exc(msg) or _is_account_blocked_exc(msg):+ return False+ code = _http_status_code(msg)+ if code is not None:+ return code in _TRANSIENT_STATUS+ return any(marker in msg for marker in _TRANSIENT_MARKERS)+@dataclass(frozen=True)class ProviderAttemptError:@@ -32,6 +88,9 @@ class ComputerUsePlannerSelector:errors: list[ProviderAttemptError] = field(default_factory=list)mission_blocked: set[tuple[str, str | None]] = field(default_factory=set)blind_skipped: int = 0+ #: Transient (capacity/infra) failures counted per candidate — see+ #: ``_MAX_TRANSIENT_PER_CANDIDATE``.+ transient_hits: dict[tuple[str, str | None], int] = field(default_factory=dict)def iter_candidates(self, *, images_attached: bool,@@ -120,6 +179,22 @@ class ComputerUsePlannerSelector:dead_providers.add(provider)return+ if kind == "overloaded":+ # A capacity blip is not a broken provider. Blocking it for the rest+ # of the mission is what turned a 30-second Gemini spike into "CU has+ # no eyes at all" (live 2026-08-10). Forgive the first hit; a second+ # one means the outage is real, so the candidate falls out normally.+ key = (provider, model)+ hits = self.transient_hits.get(key, 0) + 1+ self.transient_hits[key] = hits+ if hits < _MAX_TRANSIENT_PER_CANDIDATE:+ log.info(+ "[cu] %s(%s) had a transient failure (%d/%d) — kept in the "+ "chain for the next step",+ provider, model, hits, _MAX_TRANSIENT_PER_CANDIDATE,+ )+ return+self.mission_blocked.add((provider, model))def error_message(self, *, images_attached: bool, attempted: int) -> str:@@ -155,6 +230,8 @@ class ComputerUsePlannerSelector:kind = _classify_provider_error(detail, default="call_fail")if kind == "call_fail" and _looks_invalid_auth_error(detail):return "missing_key"+ if kind == "call_fail" and is_transient_provider_error(exc, detail):+ return "overloaded"return kinddiff --git a/jarvis/trigger/backends/global_hotkeys.py b/jarvis/trigger/backends/global_hotkeys.pyindex b55696addd..763375da28 100644--- a/jarvis/trigger/backends/global_hotkeys.py+++ b/jarvis/trigger/backends/global_hotkeys.py@@ -25,8 +25,10 @@ module on a host without the package must stay clean.from __future__ import annotations+import contextlibimport loggingimport threading+import timelog = logging.getLogger(__name__)@@ -142,6 +144,68 @@ def _reset_checker_state_for_tests() -> None:_CHECKER_REFCOUNT = 0+# --------------------------------------------------------------------------+# Registry-mutation guard.+#+# ``HotkeyChecker.run`` binds ``id_list = self.hotkeys.keys()`` ONCE and then+# iterates that LIVE dict view every 20 ms for the life of the thread. Any+# register/remove from another thread therefore raises+# ``RuntimeError: dictionary changed size during iteration`` INSIDE the poller,+# which kills it — and with it EVERY global hotkey for the rest of the process+# (live 2026-08-10 18:39:29: arming and releasing the Computer-Use cancel key+# while the voice trigger's checker was polling killed the poller, so the+# Escape kill-switch and the call/dictation shortcuts were silently dead from+# then on).+#+# The library offers no lock, so the only correct sequence is: pause the+# poller, let it leave its loop, mutate, restart. The pause is bounded by+# ``_CHECKER_SETTLE_S`` — a fraction of a second in which no hotkey fires,+# which is invisible next to losing them entirely.+# --------------------------------------------------------------------------++#: Poller loop period is 20 ms; this is comfortably more than one pass, so the+#: old thread is provably gone before the registry is touched (which also rules+#: out two live pollers double-firing a press across the restart).+_CHECKER_SETTLE_S = 0.06++#: Serializes our own registry writes against each other. Re-entrant: a nested+#: guard (register -> pre-remove) must not deadlock.+_MUTATION_LOCK = threading.RLock()+++def _registry_mutation(gh):+ """Hold the shared checker still while the hotkey registry is written."""+ with _MUTATION_LOCK:+ paused = False+ with _CHECKER_LOCK:+ if _CHECKER_REFCOUNT > 0:+ try:+ gh.stop_checking_hotkeys()+ paused = True+ except Exception: # noqa: BLE001 — never block the mutation+ log.debug("Could not pause the hotkey checker", exc_info=True)+ if paused:+ time.sleep(_CHECKER_SETTLE_S)+ try:+ yield+ finally:+ if paused:+ with _CHECKER_LOCK:+ # Only restart while someone still wants the checker — a+ # stop() during the mutation must not resurrect it.+ if _CHECKER_REFCOUNT > 0:+ try:+ gh.start_checking_hotkeys()+ except Exception: # noqa: BLE001+ log.error(+ "Hotkey checker could not be restarted after a "+ "registry change — shortcuts are dead until the "+ "next re-arm.",+ exc_info=True,+ )++def _normalize_combo(combo: str) -> str:"""`ctrl+right_alt+j` -> `control + alt + j`."""parts = [p.strip().lower() for p in combo.split("+")]@@ -255,59 +319,66 @@ class GlobalHotkeysBackend:# EVERY hotkey dies. Removing an unregistered combo is a no-op. Done# per-combo so one un-removable combo cannot abort the cleanup of the# others (the real remove_hotkeys raises on an unknown key mid-list).- for cs in combo_strings:- try:- gh.remove_hotkeys([cs])- except Exception: # noqa: BLE001 — best-effort cleanup of stale state- log.debug("Pre-register cleanup of %r skipped", cs, exc_info=True)-- # Register each binding INDIVIDUALLY. The old single- # ``register_hotkeys(all)`` was all-or-nothing: one unknown key name- # (e.g. a numpad combo emitted under the wrong token) raised and took- # EVERY hotkey down with it — the "I set a key and now nothing works"- # report. Now a bad combo is skipped and logged; the rest stay live. An- # exception must never propagate — it would crash the whole voice- # pipeline at ``async with HotkeyTrigger(...)`` — so we degrade instead.+ #+ # Every write below happens under ``_registry_mutation``: a second+ # trigger's poller may be running right now, and the library iterates a+ # LIVE view of the very dict these calls resize (see the guard).registered_rows: list[list] = []registered_strings: list[str] = []- for row in bindings:- try:- gh.register_hotkeys([row])- except Exception: # noqa: BLE001 — skip the bad combo, keep the rest- log.error(- "Hotkey combo %r could not be registered (unknown key / "- "invalid combo) — skipping it; the other hotkeys stay active.",- row[0],- exc_info=True,- )- continue- registered_rows.append(row)- registered_strings.append(row[0])-- # Second pass: the compatibility chords. Skipping one is normal, not a- # fault — it means the same chord is already armed, either because- # another action named it outright or because two bindings produced the- # same variant. The library keys its registry off the token ORDER, so a- # hand-written jarvis.toml could spell an existing chord differently and- # slip past its duplicate check; comparing the token SETS ourselves is- # what keeps that from arming one physical press twice.- taken = {frozenset(c.replace(" ", "").split("+")) for c in registered_strings}- for row in compat:- keys = frozenset(row[0].replace(" ", "").split("+"))- if keys in taken:- continue- try:- gh.register_hotkeys([row])- except Exception: # noqa: BLE001 — the primary chord is what matters- log.debug(- "Compatibility chord %r not armed (already registered).",- row[0],- exc_info=True,- )- continue- taken.add(keys)- registered_rows.append(row)- registered_strings.append(row[0])+ with _registry_mutation(gh):+ for cs in combo_strings:+ try:+ gh.remove_hotkeys([cs])+ except Exception: # noqa: BLE001 — best-effort cleanup of stale state+ log.debug("Pre-register cleanup of %r skipped", cs, exc_info=True)++ # Register each binding INDIVIDUALLY. The old single+ # ``register_hotkeys(all)`` was all-or-nothing: one unknown key name+ # (e.g. a numpad combo emitted under the wrong token) raised and took+ # EVERY hotkey down with it — the "I set a key and now nothing works"+ # report. Now a bad combo is skipped and logged; the rest stay live. An+ # exception must never propagate — it would crash the whole voice+ # pipeline at ``async with HotkeyTrigger(...)`` — so we degrade instead.+ for row in bindings:+ try:+ gh.register_hotkeys([row])+ except Exception: # noqa: BLE001 — skip the bad combo, keep the rest+ log.error(+ "Hotkey combo %r could not be registered (unknown key / "+ "invalid combo) — skipping it; the other hotkeys stay active.",+ row[0],+ exc_info=True,+ )+ continue+ registered_rows.append(row)+ registered_strings.append(row[0])++ # Second pass: the compatibility chords. Skipping one is normal, not a+ # fault — it means the same chord is already armed, either because+ # another action named it outright or because two bindings produced the+ # same variant. The library keys its registry off the token ORDER, so a+ # hand-written jarvis.toml could spell an existing chord differently and+ # slip past its duplicate check; comparing the token SETS ourselves is+ # what keeps that from arming one physical press twice.+ taken = {+ frozenset(c.replace(" ", "").split("+")) for c in registered_strings+ }+ for row in compat:+ keys = frozenset(row[0].replace(" ", "").split("+"))+ if keys in taken:+ continue+ try:+ gh.register_hotkeys([row])+ except Exception: # noqa: BLE001 — the primary chord is what matters+ log.debug(+ "Compatibility chord %r not armed (already registered).",+ row[0],+ exc_info=True,+ )+ continue+ taken.add(keys)+ registered_rows.append(row)+ registered_strings.append(row[0])if not registered_rows:# Package present but NOT ONE combo registered — degrade like a hard@@ -346,13 +417,14 @@ class GlobalHotkeysBackend:self._combo_strings = []returnif self._combo_strings:- try:- # Correct format: a list of combo STRINGS (NOT the binding- # rows). Passing the rows is the bug that left stale state.- gh.remove_hotkeys(self._combo_strings)- except Exception: # noqa: BLE001 — teardown must never propagate- log.debug("remove_hotkeys during teardown failed (non-fatal)",- exc_info=True)+ with _registry_mutation(gh):+ try:+ # Correct format: a list of combo STRINGS (NOT the binding+ # rows). Passing the rows is the bug that left stale state.+ gh.remove_hotkeys(self._combo_strings)+ except Exception: # noqa: BLE001 — teardown must never propagate+ log.debug("remove_hotkeys during teardown failed (non-fatal)",+ exc_info=True)self._registered = []self._combo_strings = []self._gh = None@@ -378,5 +450,7 @@ __all__ = ["_start_checker_once","_stop_checker_once","_reset_checker_state_for_tests",+ "_registry_mutation","_CHECKER_LOCK",+ "_CHECKER_SETTLE_S",]diff --git a/tests/fakes/fake_global_hotkeys.py b/tests/fakes/fake_global_hotkeys.pyindex 3888da208a..eb54bc8c03 100644--- a/tests/fakes/fake_global_hotkeys.py+++ b/tests/fakes/fake_global_hotkeys.py@@ -51,11 +51,27 @@ class FakeGlobalHotkeys:# registration, mirroring the real package raising on an unknown key# name — used to prove a single bad combo does NOT disable the rest.self.register_error_combos: set[str] = set()+ # Test knob: reproduce the real poller's fatal flaw. HotkeyChecker.run+ # binds ``id_list = self.hotkeys.keys()`` once and iterates that LIVE+ # view forever, so ANY registry write while it polls raises+ # "dictionary changed size during iteration" INSIDE the thread and+ # kills it — silently taking every global hotkey with it (live+ # 2026-08-10). The crash never surfaces to the caller, so the fake+ # records it and drops the live count instead of raising.+ self.strict_poller = False+ self.poller_crashed = False# ------------------------------------------------------------------# Real API surface (what HotkeyTrigger imports as ``gh``)# ------------------------------------------------------------------+ def _note_registry_write(self) -> None:+ """Kill the poller when the registry is written while it is live."""+ if self.strict_poller and self._live > 0:+ self.poller_crashed = True+ self._live = 0+def register_hotkeys(self, bindings: list[list]) -> None:+ self._note_registry_write()self.register_calls.append(bindings)if self.register_error is not None:raise self.register_error@@ -73,6 +89,7 @@ class FakeGlobalHotkeys:self.registered[combo] = (on_press, on_release)def remove_hotkeys(self, bindings: list[str]) -> None:+ self._note_registry_write()self.remove_calls.append(bindings)for _binding in bindings:# Faithful to the real module: ``_binding.replace(" ", "")``.diff --git a/tests/unit/cu/conftest.py b/tests/unit/cu/conftest.pyindex 581b65fea6..e40804f22b 100644--- a/tests/unit/cu/conftest.py+++ b/tests/unit/cu/conftest.py@@ -32,3 +32,20 @@ def _screen_recording_gate_open(monkeypatch.setattr(capture, "_require_macos_screen_recording_permission", lambda: None)++[email protected](autouse=True)+def _forget_learned_token_headroom() -> None:+ """Clear the per-model token-headroom memory between tests.++ ``brain_call`` remembers process-wide which (provider, model) pairs cannot+ finish their JSON inside the small per-call cap, so the next step starts at+ the headroom instead of re-discovering it. That memory is deliberately+ global; leaking it across tests would make a truncation test's outcome+ depend on execution order.+ """+ from jarvis.cu.brain_call import _reset_headroom_memory_for_tests++ _reset_headroom_memory_for_tests()+ yield+ _reset_headroom_memory_for_tests()diff --git a/tests/unit/cu/test_brain_call_resilience.py b/tests/unit/cu/test_brain_call_resilience.pynew file mode 100644index 0000000000..dd22780fb2--- /dev/null+++ b/tests/unit/cu/test_brain_call_resilience.py@@ -0,0 +1,259 @@+"""Two latency/availability defenses in the CU vision dispatch.++Both were written from one live mission (2026-08-10 18:39-18:43, voice goal+"open Elon's post"), where Computer-Use first announced "I can't see the screen+right now" and then crawled at ~9 s per step:++1. **Transient failures no longer blind the mission.** Gemini answered+ ``503 … This model is currently experiencing high demand``. The chain treated+ that exactly like a broken credential: it moved on to OpenRouter (402, no+ credits) and OpenAI (429, no credits) and gave up — while the very same+ Gemini key served a full mission three minutes later. A capacity blip now+ earns ONE in-place retry, and a single blip no longer blocks the candidate+ for the rest of the mission. Credential/quota failures are explicitly+ excluded so the honest "check your keys/credit" readback survives.++2. **The token headroom is learned once, not per step.** Every single step+ logged "hit the 320-token cap … retrying once with 2048" — the first reply+ was always discarded, costing a full round-trip per decision. The+ (provider, model) pair is now remembered and the next call starts at the+ headroom.++Fakes only (no real network) — same ``_ScriptedBrain``/``_FakeManager`` shape as+``test_brain_call_truncation_retry.py``.+"""+from __future__ import annotations++from typing import Any++import pytest++from jarvis.core.protocols import BrainDelta, ImageBlock+from jarvis.cu.brain_call import CUNoVisionProviderError, call_vision_brain++_TRUNCATED = '{"action": "open_app", "name": "'+_COMPLETE = '[{"action": "open_app", "name": "Discord"}]'++_OVERLOADED = (+ "503 Service Unavailable. {'message': '{\\n \"error\": {\\n \"code\": 503,"+ "\\n \"message\": \"This model is currently experiencing high demand. "+ "Spikes in demand are usually temporary. Please try again later.\",\\n "+ "\"status\": \"UNAVAILABLE\"\\n }\\n}\\n', 'status': 'Service Unavailable'}"+)+_NO_CREDITS = (+ "Error code: 429 - {'error': {'message': 'You have no credits remaining. "+ "Add credits to continue using the API.', 'type': 'insufficient_quota', "+ "'code': 'credit_balance_exhausted'}}"+)+_BAD_KEY = (+ "Error code: 401 - {'type': 'error', 'error': {'type': "+ "'authentication_error', 'message': 'invalid x-api-key'}}"+)+++class _ScriptedBrain:+ """Yields one scripted step per call: a reply tuple, or an Exception."""++ supports_tools = False+ supports_vision = True++ def __init__(self, script: list[Any]) -> None:+ self.script = list(script)+ self.requests: list[Any] = []++ async def complete(self, req: Any): # type: ignore[no-untyped-def]+ self.requests.append(req)+ step = self.script.pop(0) if self.script else (_COMPLETE, "stop")+ if isinstance(step, Exception):+ raise step+ text, finish = step+ if text:+ yield BrainDelta(content=text)+ if finish:+ yield BrainDelta(finish_reason=finish)++ def estimate_cost(self, req: Any) -> float:+ return 0.0+++class _FakeManager:+ """BrainManager-shaped fake with an ordered multi-provider chain."""++ active_provider = "alpha"++ def __init__(self, brains: dict[str, _ScriptedBrain]) -> None:+ self.brains = brains+ self._dead_providers: set[str] = set()++ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:+ assert level == "fast"+ return [(name, "m") for name in self.brains]++ def _get_brain(self, name: str, model: str | None = None) -> _ScriptedBrain:+ return self.brains[name]++ def _cu_model(self, name: str) -> str | None:+ return None++ def _cu_provider(self) -> str:+ return ""+++def _build_prompt(provider: str, brain: Any) -> tuple[str, str]:+ return "system", "user"+++_IMG = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")++[email protected](autouse=True)+def _no_backoff_sleep(monkeypatch: pytest.MonkeyPatch) -> None:+ """The transient retry waits 0.6 s in production — not in the suite."""+ import jarvis.cu.brain_call as bc++ monkeypatch.setattr(bc, "_TRANSIENT_RETRY_DELAY_S", 0.0)+++async def _call(manager: _FakeManager, **kw: Any):+ return await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[_IMG],+ max_tokens=320, early_stop_json=True, **kw,+ )+++# ----------------------------------------------------------------------+# 1. Transient failures+# ----------------------------------------------------------------------+++async def test_overloaded_provider_gets_one_in_place_retry() -> None:+ """A 503 is a busy server, not a broken key — the SAME provider is asked+ again instead of the chain falling through to an out-of-credit sibling."""+ alpha = _ScriptedBrain([RuntimeError(_OVERLOADED), (_COMPLETE, "stop")])+ beta = _ScriptedBrain([RuntimeError(_NO_CREDITS)])+ manager = _FakeManager({"alpha": alpha, "beta": beta})++ reply = await _call(manager)++ assert reply.provider == "alpha"+ assert reply.text == _COMPLETE+ assert len(alpha.requests) == 2+ assert not beta.requests # never reached+++async def test_persistent_outage_still_falls_through_to_the_next_provider() -> None:+ """The retry is ONE-shot: a provider that is genuinely down does not trap+ the mission — the chain continues to a healthy brain."""+ alpha = _ScriptedBrain([RuntimeError(_OVERLOADED), RuntimeError(_OVERLOADED)])+ beta = _ScriptedBrain([(_COMPLETE, "stop")])+ manager = _FakeManager({"alpha": alpha, "beta": beta})++ reply = await _call(manager)++ assert reply.provider == "beta"+ assert len(alpha.requests) == 2++[email protected]("detail", [_NO_CREDITS, _BAD_KEY])+async def test_account_failures_are_never_retried_in_place(detail: str) -> None:+ """No credits / invalid key must fall through IMMEDIATELY. Retrying them+ would burn a round-trip per step and delay the honest credential readback."""+ alpha = _ScriptedBrain([RuntimeError(detail)])+ beta = _ScriptedBrain([(_COMPLETE, "stop")])+ manager = _FakeManager({"alpha": alpha, "beta": beta})++ reply = await _call(manager)++ assert reply.provider == "beta"+ assert len(alpha.requests) == 1+++async def test_exhausted_chain_still_raises_the_no_provider_error() -> None:+ """The retry must not swallow a genuinely dead chain — the engine maps this+ exception to exit 3 ("no eyes — check your keys/credit")."""+ alpha = _ScriptedBrain([RuntimeError(_BAD_KEY)])+ beta = _ScriptedBrain([RuntimeError(_NO_CREDITS)])+ manager = _FakeManager({"alpha": alpha, "beta": beta})++ with pytest.raises(CUNoVisionProviderError):+ await _call(manager)+++async def test_one_blip_does_not_block_the_candidate_for_the_mission() -> None:+ """The selector's mission-block is what made a 30-second spike cost the+ whole mission. A first transient failure keeps the candidate available."""+ from jarvis.harness.computer_use_planner import ComputerUsePlannerSelector++ selector = ComputerUsePlannerSelector(manager=object(), chain=[("alpha", "m")])+ selector.record_failure("alpha", "m", RuntimeError(_OVERLOADED))+ assert ("alpha", "m") not in selector.mission_blocked++ selector.record_failure("alpha", "m", RuntimeError(_OVERLOADED))+ assert ("alpha", "m") in selector.mission_blocked # a real outage falls out+++async def test_account_failure_blocks_or_dead_lists_immediately() -> None:+ """A terminal credential state still leaves the chain on the FIRST hit."""+ from jarvis.harness.computer_use_planner import ComputerUsePlannerSelector++ class _Mgr:+ _dead_providers: set[str] = set()++ manager = _Mgr()+ selector = ComputerUsePlannerSelector(manager=manager, chain=[("alpha", "m")])+ selector.record_failure("alpha", "m", RuntimeError(_BAD_KEY))+ assert "alpha" in manager._dead_providers+++# ----------------------------------------------------------------------+# 2. Learned token headroom+# ----------------------------------------------------------------------+++async def test_second_call_starts_at_the_learned_headroom() -> None:+ """After one truncation, the next call skips the doomed small-cap attempt —+ that discarded round-trip was ~a third of every step's latency."""+ brain = _ScriptedBrain([+ (_TRUNCATED, "FinishReason.MAX_TOKENS"), # call 1, attempt 1+ (_COMPLETE, "stop"), # call 1, headroom retry+ (_COMPLETE, "stop"), # call 2, straight to headroom+ ])+ manager = _FakeManager({"alpha": brain})++ await _call(manager)+ await _call(manager)++ assert [r.max_tokens for r in brain.requests] == [320, 2048, 2048]+++async def test_headroom_is_remembered_per_model_not_globally() -> None:+ """A different model keeps the cheap small cap — the truncation is a+ property of the model, not of Computer-Use."""+ import jarvis.cu.brain_call as bc++ brain = _ScriptedBrain([+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ (_COMPLETE, "stop"),+ ])+ manager = _FakeManager({"alpha": brain})+ await _call(manager)++ assert ("alpha", "m") in bc._NEEDS_HEADROOM+ assert ("alpha", "other-model") not in bc._NEEDS_HEADROOM+++async def test_learned_headroom_never_costs_a_second_retry() -> None:+ """A call that already STARTS at the headroom and is still truncated is+ returned as-is — the engine counts the parse failure. No third dispatch."""+ brain = _ScriptedBrain([+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ ])+ manager = _FakeManager({"alpha": brain})++ await _call(manager) # 2 requests: 320 then 2048+ reply = await _call(manager) # 1 request: straight to 2048, no retry++ assert reply.text == _TRUNCATED+ assert [r.max_tokens for r in brain.requests] == [320, 2048, 2048]diff --git a/tests/unit/trigger/test_hotkey_registry_mutation_guard.py b/tests/unit/trigger/test_hotkey_registry_mutation_guard.pynew file mode 100644index 0000000000..34d272e015--- /dev/null+++ b/tests/unit/trigger/test_hotkey_registry_mutation_guard.py@@ -0,0 +1,128 @@+"""The Windows hotkey registry may only be written while the poller is paused.++Live forensic 2026-08-10 18:39:29 (Computer-Use mission "open Elon's post"):++ Thread 'Thread-34 (run)' died on an unhandled exception+ File ".../global_hotkeys/hotkey_checker.py", line 216, in run+ for id in id_list:+ RuntimeError: dictionary changed size during iteration++``HotkeyChecker.run`` binds ``id_list = self.hotkeys.keys()`` ONCE and then+iterates that LIVE dict view every 20 ms for the life of the thread. Arming the+Computer-Use cancel key (``cu_cancel=[escape]``) from the mission thread resized+that dict mid-iteration, so the poller died — and with it the Escape kill-switch+plus every other global shortcut for the rest of the process. Nothing surfaced+to the user; the keys just stopped working.++The library exposes no lock, so ``_registry_mutation`` pauses the shared poller,+lets it leave its loop, performs the write, and restarts it.+"""+from __future__ import annotations++import sys++import pytest++from tests.fakes.fake_global_hotkeys import FakeGlobalHotkeys+++def strict_gh():+ """A fake whose poller dies on a registry write, exactly like the real one."""+ import jarvis.trigger.backends.global_hotkeys as ghb++ fake = FakeGlobalHotkeys()+ fake.strict_poller = True+ saved = sys.modules.get("global_hotkeys")+ sys.modules["global_hotkeys"] = fake+ ghb._reset_checker_state_for_tests()+ try:+ yield fake+ finally:+ ghb._reset_checker_state_for_tests()+ if saved is not None:+ sys.modules["global_hotkeys"] = saved+ else:+ sys.modules.pop("global_hotkeys", None)+++def test_arming_a_second_trigger_does_not_kill_the_running_poller(strict_gh):+ """The exact live sequence: the voice trigger polls, a Computer-Use mission+ arms its cancel key, the mission ends and releases it. The poller must+ survive all of it and still deliver presses."""+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ fired: list[str] = []+ voice = GlobalHotkeysBackend()+ voice.register([["f1 + f2", None, lambda: fired.append("hangup")]])+ voice.start()+ assert strict_gh.checker_running++ cu_cancel = GlobalHotkeysBackend()+ cu_cancel.register([["escape", None, lambda: fired.append("cancel")]])+ cu_cancel.start()+ cu_cancel.stop()+ cu_cancel.unregister()++ assert not strict_gh.poller_crashed+ assert strict_gh.checker_running++ strict_gh.fire("f1 + f2")+ assert fired == ["hangup"]++ voice.stop()+ voice.unregister()+++def test_first_registration_needs_no_pause(strict_gh):+ """With no poller running yet there is nothing to protect — and nothing to+ restart, so the checker must not be started behind ``start()``'s back."""+ import jarvis.trigger.backends.global_hotkeys as ghb+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ backend = GlobalHotkeysBackend()+ backend.register([["f3 + f4", None, lambda: None]])++ assert strict_gh.start_calls == 0+ assert strict_gh.stop_calls == 0+ assert ghb._CHECKER_REFCOUNT == 0+++def test_paused_poller_is_restarted_after_the_write(strict_gh):+ """Pause and resume are balanced: one stop, one start, never a leak that+ leaves the shortcuts dead or a second poller double-firing."""+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ voice = GlobalHotkeysBackend()+ voice.register([["f1 + f2", None, lambda: None]])+ voice.start()+ starts_before, stops_before = strict_gh.start_calls, strict_gh.stop_calls++ other = GlobalHotkeysBackend()+ other.register([["escape", None, lambda: None]])++ assert strict_gh.start_calls == starts_before + 1+ assert strict_gh.stop_calls == stops_before + 1+ assert strict_gh.peak_live == 1 # never two pollers at once+ assert strict_gh.checker_running++ voice.stop()+++def test_teardown_write_also_runs_under_the_guard(strict_gh):+ """``unregister`` removes combos by string — that is a registry write too,+ and it happened at exactly the moment the live poller died."""+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ voice = GlobalHotkeysBackend()+ voice.register([["f1 + f2", None, lambda: None]])+ voice.start()++ doomed = GlobalHotkeysBackend()+ doomed.register([["escape", None, lambda: None]])+ doomed.unregister()++ assert not strict_gh.poller_crashed+ assert strict_gh.checker_running++ voice.stop()