Skip to content

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

fix(cu): recover Gemini thinking-mandatory 400s and stop the blind vision last resort

Ruben Lütkeea084e60cad8
diff --git a/jarvis/cu/brain_call.py b/jarvis/cu/brain_call.py
index 399e512d30..220d995745 100644
--- a/jarvis/cu/brain_call.py
+++ b/jarvis/cu/brain_call.py
@@ -354,8 +354,21 @@ async def call_vision_brain(
_log_serving(provider, model)
return reply
- # Stale-dead-flag resilience: retry every REGISTERED vision provider once.
- if images_attached:
+ # Stale-dead-flag resilience: retry every REGISTERED vision provider once,
+ # IGNORING transient dead/cooldown flags — BUT only when the normal pass
+ # dispatched NOTHING (``attempted == 0``). That is the one case this rescue
+ # exists for: every vision brain was filtered OUT of the chain (a stale
+ # dead-flag on CU's only eyes, live 2026-06-21). When real vision providers
+ # WERE dispatched and each failed for real (``attempted > 0``), the chain is
+ # genuinely exhausted, not wrongly filtered — resurrecting a provider here
+ # only drags in a brain whose usable path is BLIND (live forensic
+ # 2026-07-23: every real vision provider 400/401'd, the last resort reached
+ # codex whose API key was 429'd so it answered from the image-dropping CLI,
+ # burned ~68 s producing unparseable prose, and surfaced the misleading
+ # exit-2 "couldn't get a valid screen-control response" instead of the
+ # honest exit-3 "no eyes — check your keys/credit"). Skipping it here lets
+ # the CUNoVisionProviderError below carry that honest, actionable readback.
+ if images_attached and attempted == 0:
already = set(chain) | {(e.provider, e.model) for e in selector.errors}
for provider, model, brain in iter_last_resort_vision(
manager, already_tried=already,
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index ca3161b83f..543b24471a 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -91,16 +91,31 @@ def _is_stale_context_cache_error(exc: Exception) -> bool:
def _is_thinking_config_rejected_error(exc: Exception) -> bool:
"""True when the API rejected the ``thinking_config`` itself.
- Thinking-mandatory models answer 400 "Budget 0 is invalid. This model
- only works in thinking mode." when asked to disable thinking. The
- concrete exception class differs across ``google-genai`` versions, so we
- match on the message. Recoverable by retrying once without the field —
- a capability probe, never a model-name pin (AP-21).
+ Thinking-mandatory models answer 400 when asked to disable thinking
+ (``thinking_budget=0``), in two message shapes both seen live:
+
+ * The SPECIFIC form — "Budget 0 is invalid. This model only works in
+ thinking mode." (thinking-mandatory Pro class, 2026-07-16).
+ * The GENERIC form — a bare "Request contains an invalid argument." /
+ INVALID_ARGUMENT with NO "thinking" or "budget" token at all (live
+ forensic 2026-07-23: ``gemini-3.6-flash`` 400'd every Computer-Use step
+ this way; the vision chain then fell through to a blind last-resort
+ brain that burned ~68 s and the user heard the misleading "couldn't get
+ a valid screen-control response"). Matching only the specific form left
+ the generic one unrecovered.
+
+ The concrete exception class differs across ``google-genai`` versions, so
+ we match on the message. The caller consults this ONLY when a
+ ``thinking_config`` is actually on the wire and no delta has been emitted
+ yet, so treating a pre-stream INVALID_ARGUMENT as a thinking rejection is
+ safe: the retry merely drops ``thinking_config``; an unrelated
+ invalid-argument still fails the retry and degrades normally. A capability
+ probe, never a model-name pin (AP-21).
"""
msg = str(exc).lower()
- if "thinking" not in msg:
- return False
- return "budget" in msg or "invalid" in msg or "thinking mode" in msg
+ if "thinking" in msg:
+ return "budget" in msg or "invalid" in msg or "thinking mode" in msg
+ return "invalid_argument" in msg or "invalid argument" in msg
def _to_gemini_contents(
diff --git a/tests/unit/brain/test_gemini_reasoning_effort.py b/tests/unit/brain/test_gemini_reasoning_effort.py
index bc01c4ad26..0c4aa1e892 100644
--- a/tests/unit/brain/test_gemini_reasoning_effort.py
+++ b/tests/unit/brain/test_gemini_reasoning_effort.py
@@ -39,9 +39,18 @@ pytest.importorskip("google.genai")
class _FakeGeminiClient:
"""Records every ``config`` passed to ``generate_content_stream``."""
- def __init__(self, *, reject_thinking: bool = False) -> None:
+ def __init__(
+ self,
+ *,
+ reject_thinking: bool = False,
+ reject_message: str = (
+ "400 INVALID_ARGUMENT. Budget 0 is invalid. This model only "
+ "works in thinking mode."
+ ),
+ ) -> None:
self.calls: list[dict[str, Any]] = []
self.reject_thinking = reject_thinking
+ self.reject_message = reject_message
self.aio = SimpleNamespace(models=self)
async def generate_content_stream(
@@ -53,10 +62,7 @@ class _FakeGeminiClient:
) -> AsyncIterator[Any]:
self.calls.append(dict(config))
if self.reject_thinking and config.get("thinking_config") is not None:
- raise RuntimeError(
- "400 INVALID_ARGUMENT. Budget 0 is invalid. This model only "
- "works in thinking mode."
- )
+ raise RuntimeError(self.reject_message)
async def _stream() -> AsyncIterator[Any]:
yield SimpleNamespace(
@@ -138,3 +144,33 @@ async def test_thinking_mandatory_model_recovers_without_the_field() -> None:
assert fake.calls[0].get("thinking_config") is not None
assert "thinking_config" not in fake.calls[1]
assert any(d.content for d in deltas), "recovered stream must yield text"
+
+
+async def test_generic_invalid_argument_recovers_without_the_field() -> None:
+ """A NEWER thinking-mandatory model (live 2026-07-23: gemini-3.6-flash)
+ rejects ``thinking_budget=0`` with only the GENERIC "Request contains an
+ invalid argument." 400 — no "thinking"/"budget" token. It must still be
+ recognised as a thinking-config rejection and recover via ONE retry
+ without the field, or the whole vision chain falls through to a blind
+ last-resort brain and the user hears "couldn't get a valid screen-control
+ response"."""
+ provider = GeminiBrain(model="gemini-3.6-flash")
+ fake = _FakeGeminiClient(
+ reject_thinking=True,
+ reject_message=(
+ '400 Bad Request. {"error": {"code": 400, "message": "Request '
+ 'contains an invalid argument.", "status": "INVALID_ARGUMENT"}}'
+ ),
+ )
+ provider._client = fake # type: ignore[assignment]
+
+ deltas = await _drain(provider.complete(_request("none")))
+
+ assert len(fake.calls) == 2, (
+ "the generic INVALID_ARGUMENT 400 must trigger exactly one retry "
+ "without thinking_config"
+ )
+ assert fake.calls[0].get("thinking_config") is not None
+ assert "thinking_config" not in fake.calls[1]
+ assert any(d.content for d in deltas), "recovered stream must yield text"
diff --git a/tests/unit/cu/test_brain_call_last_resort_guard.py b/tests/unit/cu/test_brain_call_last_resort_guard.py
new file mode 100644
index 0000000000..26bebb4013
--- /dev/null
+++ b/tests/unit/cu/test_brain_call_last_resort_guard.py
@@ -0,0 +1,182 @@
+"""The CU v2 vision dispatch reaches the blind-flag last resort ONLY when the
+normal pass dispatched nothing.
+
+Live forensic 2026-07-23 (Computer-Use "open Gemini"): every real vision
+provider failed for real this turn — ``gemini`` 400 INVALID_ARGUMENT,
+``openrouter`` 400 "reasoning is mandatory", ``nvidia`` no-multimodal,
+``anthropic`` 401. The stale-dead-flag last resort then reached ``codex``,
+whose API key was 429'd so it answered from the image-dropping ChatGPT CLI:
+~68 s of unparseable prose, ending in the misleading exit-2 phrase "I couldn't
+get a valid screen-control response, so I stopped." while the screen sat
+frozen.
+
+The last resort exists for ONE case — a stale ``_dead_providers`` flag filtered
+the only vision brain OUT of the chain, so the normal pass dispatched NOTHING
+(``attempted == 0``). When real vision providers WERE dispatched and each
+failed (``attempted > 0``), the chain is genuinely exhausted; resurrecting a
+provider only drags in a blind path. This module pins both directions:
+
+* ``attempted > 0`` (real failures) → NO last resort, honest
+ :class:`CUNoVisionProviderError` (engine maps it to exit 3, "check keys/
+ credit") — and the rescue brain is never dispatched.
+* ``attempted == 0`` (chain filtered empty) → last resort still runs and
+ reaches the wrongly-flagged vision brain (the 2026-06-21 fix stays green).
+
+Fakes only, no network — mirrors ``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
+
+_COMPLETE = '{"action": "done"}'
+_IMG = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+
+class _OkBrain:
+ """A vision-capable brain that answers cleanly; counts its dispatches."""
+
+ supports_tools = False
+ supports_vision = True
+
+ def __init__(self, text: str = _COMPLETE) -> None:
+ self.text = text
+ self.calls = 0
+
+ async def complete(self, req: Any): # type: ignore[no-untyped-def]
+ self.calls += 1
+ yield BrainDelta(content=self.text)
+ yield BrainDelta(finish_reason="stop")
+
+ def estimate_cost(self, req: Any) -> float:
+ return 0.0
+
+
+class _FailingVisionBrain:
+ """A vision-capable brain that raises a real (non-dead) provider error."""
+
+ supports_tools = False
+ supports_vision = True
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def complete(self, req: Any): # type: ignore[no-untyped-def]
+ self.calls += 1
+ raise RuntimeError("400 Bad Request: request contains an invalid argument")
+ yield # pragma: no cover — makes this an async generator
+
+ def estimate_cost(self, req: Any) -> float:
+ return 0.0
+
+
+class _BlindBrain:
+ """The active provider that cannot see the screen (supports_vision=False)."""
+
+ supports_tools = True
+ supports_vision = False
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def complete(self, req: Any): # type: ignore[no-untyped-def]
+ self.calls += 1
+ yield BrainDelta(content='{"action": "click", "x": 1, "y": 1}')
+ yield BrainDelta(finish_reason="stop")
+
+ def estimate_cost(self, req: Any) -> float:
+ return 0.0
+
+
+class _Registry:
+ def __init__(self, names: list[str]) -> None:
+ self._names = names
+
+ def available(self) -> list[str]:
+ return list(self._names)
+
+
+class _Manager:
+ """BrainManager-shaped fake exposing the CU dispatch + last-resort surface."""
+
+ def __init__(
+ self,
+ *,
+ chain: list[tuple[str, str | None]],
+ brains: dict[str, Any],
+ registry: list[str],
+ ) -> None:
+ self.active_provider = chain[0][0] if chain else ""
+ self._chain = chain
+ self._brains = brains
+ self._registry = _Registry(registry)
+ self._dead_providers: set[str] = set()
+
+ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
+ assert level == "fast"
+ return list(self._chain)
+
+ def _get_brain(self, name: str, model: str | None = None) -> Any:
+ return self._brains.get(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"
+
+
+async def test_real_vision_failures_skip_the_blind_last_resort() -> None:
+ """Every real vision provider failed this turn (attempted > 0) → the last
+ resort must NOT run, so CU raises the honest ``CUNoVisionProviderError``
+ (exit 3) instead of dragging in a resurrected brain."""
+ failing = _FailingVisionBrain()
+ rescue = _OkBrain()
+ manager = _Manager(
+ chain=[("vision-a", None)],
+ brains={"vision-a": failing, "rescue-b": rescue},
+ registry=["vision-a", "rescue-b"],
+ )
+
+ with pytest.raises(CUNoVisionProviderError):
+ await call_vision_brain(
+ manager, build_prompt=_build_prompt, images=[_IMG],
+ max_tokens=320, early_stop_json=True,
+ )
+
+ assert failing.calls == 1, "the real vision provider must be dispatched once"
+ assert rescue.calls == 0, (
+ "the last resort must NOT resurrect a provider after a real failure — "
+ "that is how the blind codex CLI got dispatched for 68 s"
+ )
+
+
+async def test_stale_dead_flag_still_rescued_when_chain_dispatched_nothing() -> None:
+ """The chain reached NO vision brain (the only candidate is blind, so
+ attempted == 0). The last resort MUST still run and reach the wrongly
+ filtered vision provider — the 2026-06-21 resilience stays intact."""
+ blind = _BlindBrain()
+ rescue = _OkBrain()
+ manager = _Manager(
+ chain=[("blind-active", None)],
+ brains={"blind-active": blind, "rescue-b": rescue},
+ registry=["blind-active", "rescue-b"],
+ )
+
+ reply = await call_vision_brain(
+ manager, build_prompt=_build_prompt, images=[_IMG],
+ max_tokens=320, early_stop_json=True,
+ )
+
+ assert reply.text == _COMPLETE
+ assert reply.provider == "rescue-b"
+ assert blind.calls == 0, "the blind active provider must never plan a screenshot"
+ assert rescue.calls == 1, "the last resort must reach the vision-capable brain"