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): survive thinking-by-default vision models - reasoning hint + truncation retry (BUG-067)
Ruben Lütke6b50015bed2c
diff --git a/jarvis/brain/streaming.py b/jarvis/brain/streaming.pyindex e8db317f85..160f640ecf 100644--- a/jarvis/brain/streaming.py+++ b/jarvis/brain/streaming.py@@ -116,6 +116,13 @@ def _has_complete_json_action(text: str) -> bool:return True+# Public name: the CU dispatch uses this to decide whether a length-capped+# reply still holds a usable JSON payload (truncation-retry gate).+def has_complete_json_action(text: str) -> bool:+ """Public wrapper around :func:`_has_complete_json_action`."""+ return _has_complete_json_action(text)++async def _aclose_quietly(stream: AsyncIterator[BrainDelta]) -> None:"""Best-effort close of an async stream after an early stop, so theprovider connection/generator is released. Never raises."""@@ -262,6 +269,7 @@ __all__ = ["aggregate","aggregate_first_json","aggregate_with_consumer",+ "has_complete_json_action","tee_text","is_length_truncated",]diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.pyindex 0084278391..c9ed415ea4 100644--- a/jarvis/core/protocols.py+++ b/jarvis/core/protocols.py@@ -91,6 +91,14 @@ class BrainRequest:temperature: float = 0.7max_tokens: int = 4096stream: bool = True+ # Hint for providers whose models spend internal reasoning ("thinking")+ # tokens before answering. "none" asks the provider to disable/minimize+ # internal reasoning for THIS call — used by small deterministic+ # structured-output calls (Computer-Use actions/judges) where thinking+ # would eat the whole ``max_tokens`` budget and truncate the visible+ # reply. ``None`` keeps the provider default; providers without a+ # reasoning knob ignore the field (capability hint, never a hard switch).+ reasoning_effort: Literal["none"] | None = None@dataclass(frozen=True, slots=True)diff --git a/jarvis/cu/brain_call.py b/jarvis/cu/brain_call.pyindex 89e7895ab9..d33803f862 100644--- a/jarvis/cu/brain_call.py+++ b/jarvis/cu/brain_call.py@@ -208,7 +208,12 @@ async def call_vision_brain("CU v2 cannot dispatch",)- from jarvis.brain.streaming import aggregate, aggregate_first_json # noqa: PLC0415+ from jarvis.brain.streaming import ( # noqa: PLC0415+ aggregate,+ aggregate_first_json,+ has_complete_json_action,+ is_length_truncated,+ )from jarvis.harness.computer_use_planner import ( # noqa: PLC0415ComputerUsePlannerSelector,iter_last_resort_vision,@@ -277,17 +282,45 @@ async def call_vision_brain(async def _try(provider: str, model: str | None, brain: Any) -> BrainReply | None:system, user = build_prompt(provider, brain)- req = BrainRequest(- messages=(BrainMessage(- role="user", content=user, images=tuple(images),- ),),- system=system,- temperature=0.0,- max_tokens=max_tokens,- stream=True,- )- result = await agg(brain.complete(req))++ async def _once(tokens: int) -> Any:+ req = BrainRequest(+ messages=(BrainMessage(+ role="user", content=user, images=tuple(images),+ ),),+ system=system,+ temperature=0.0,+ max_tokens=tokens,+ stream=True,+ # CU calls are small deterministic JSON decisions — internal+ # "thinking" only burns the output budget (2026-07-16: every+ # step died "unterminated JSON", thoughts=304 of 320).+ reasoning_effort="none",+ )+ return await agg(brain.complete(req))++ result = await _once(max_tokens)text = (result.text or "").strip()+ if (+ early_stop_json+ and text+ and not has_complete_json_action(text)+ and is_length_truncated(result.finish_reason, text)+ ):+ # The model hit the output-token cap before finishing its JSON —+ # typically a thinking-by-default model whose thoughts consumed+ # 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)+ 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,+ )+ result = await _once(retry_tokens)+ text = (result.text or "").strip()if not text:selector.record_empty(provider, model)return Nonediff --git a/jarvis/cu/indicator/capture_guard.py b/jarvis/cu/indicator/capture_guard.pyindex dc354ce400..bb18684ce7 100644--- a/jarvis/cu/indicator/capture_guard.py+++ b/jarvis/cu/indicator/capture_guard.py@@ -45,14 +45,29 @@ def indicator_suppressed() -> Iterator[None]:returntry:cm = hook()+ enter = getattr(cm, "__enter__", None)+ exit_ = getattr(cm, "__exit__", None)+ if enter is None or exit_ is None:+ yield+ return+ enter()except Exception: # noqa: BLE001 — fail-openyieldreturn+ # The blank succeeded — run the grab exactly once and swallow ONLY the+ # unblank failure. The previous ``with cm: yield`` + ``except: yield``+ # shape resumed the generator into a SECOND yield whenever the hook's+ # __exit__ raised (dead sidecar, late ack), which @contextmanager turns+ # into ``RuntimeError: generator didn't stop`` — killing the very frame+ # grab this guard exists to protect (macOS/Linux path; Windows uses+ # WDA_EXCLUDEFROMCAPTURE and never registers a hook).try:- with cm: # type: ignore[union-attr]- yield- except Exception: # noqa: BLE001 — a guard failure must not kill the grabyield+ finally:+ try:+ exit_(None, None, None)+ except Exception: # noqa: BLE001, S110 — guard failure must not kill the grab+ pass__all__ = ["indicator_suppressed", "register_hook", "unregister_hook"]diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.pyindex c12367d96d..695b7530b9 100644--- a/jarvis/plugins/brain/gemini.py+++ b/jarvis/plugins/brain/gemini.py@@ -78,6 +78,21 @@ def _is_stale_context_cache_error(exc: Exception) -> bool:return False+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).+ """+ msg = str(exc).lower()+ if "thinking" not in msg:+ return False+ return "budget" in msg or "invalid" in msg or "thinking mode" in msg++def _to_gemini_contents(messages: tuple[BrainMessage, ...]) -> list[dict[str, Any]]:"""BrainMessages → Gemini contents array. Role mapping: assistant→model.@@ -601,11 +616,24 @@ class GeminiBrain:# older SDK versions don't have the field and raise AttributeError. In# that case we ignore the value instead of killing the whole brain# call (best-effort optimization).- if self._thinking_budget is not None:+ effective_thinking_budget = self._thinking_budget+ if (+ effective_thinking_budget is None+ and getattr(req, "reasoning_effort", None) == "none"+ ):+ # The caller asked for minimal internal reasoning (small+ # structured-output calls: Computer-Use actions/judges). A+ # thinking-by-default model otherwise spends the whole+ # ``max_output_tokens`` budget on thoughts and the visible reply+ # arrives truncated mid-JSON — live forensic 2026-07-16: every CU+ # step failed "unterminated JSON" with thoughts=304 of+ # max_tokens=320. An explicit constructor budget always wins.+ effective_thinking_budget = 0+ if effective_thinking_budget is not None:try:from google.genai import types as _genai_typesconfig_dict["thinking_config"] = _genai_types.ThinkingConfig(- thinking_budget=self._thinking_budget,+ thinking_budget=effective_thinking_budget,)except (ImportError, AttributeError):pass@@ -804,6 +832,22 @@ class GeminiBrain:if tools_payload:config_dict["tools"] = tools_payloadcontinue+ if (+ not yielded_delta+ and "thinking_config" in config_dict+ and _is_thinking_config_rejected_error(exc)+ ):+ # Some models REQUIRE thinking mode and 400 on budget=0+ # ("Budget 0 is invalid. This model only works in thinking+ # mode."). Capability recovery, not a model-name pin+ # (AP-21): drop the config and retry once. Safe: the+ # rejection fires before any token is generated.+ log.info(+ "Gemini model %s rejected thinking_config — retrying "+ "once without it: %s", self._model, exc,+ )+ config_dict.pop("thinking_config", None)+ continueif (not yielded_deltaand self._transport == _TRANSPORT_NATIVEdiff --git a/tests/unit/brain/test_gemini_reasoning_effort.py b/tests/unit/brain/test_gemini_reasoning_effort.pynew file mode 100644index 0000000000..bc01c4ad26--- /dev/null+++ b/tests/unit/brain/test_gemini_reasoning_effort.py@@ -0,0 +1,140 @@+"""GeminiBrain mapping of ``BrainRequest.reasoning_effort`` to thinking config.++Live forensic 2026-07-16: the fast vision model (``gemini-3.5-flash``,+a preview alias) turned thinking-by-default server-side. Computer-Use calls+cap ``max_output_tokens`` at 320, and Gemini counts thoughts against that+cap — reproduced 1:1 against the live API: thoughts=304, candidate=12,+finish=MAX_TOKENS, visible reply ``{"action": "open_app", "name": "`` →+every CU step failed "unterminated JSON" and the mission aborted.++Contract pinned here:++* ``reasoning_effort="none"`` on the request → ``thinking_config`` with+ ``thinking_budget=0`` goes on the wire (thinking disabled for this call).+* An explicit constructor ``thinking_budget`` always wins over the hint.+* No hint, no constructor budget → no ``thinking_config`` (SDK default).+* A model that REJECTS budget=0 (thinking-mandatory Pro class answers 400+ "Budget 0 is invalid. This model only works in thinking mode.") is+ recovered by ONE retry without the field — capability probe, not a+ model-name pin (AP-21).++Uses the same fake-client shape as ``test_gemini_stale_cache_bug019.py``;+``google.genai`` must be importable for ``ThinkingConfig`` to be attached,+so these tests skip cleanly on environments without the SDK.+"""+from __future__ import annotations++from collections.abc import AsyncIterator+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.core.protocols import BrainMessage, BrainRequest+from jarvis.plugins.brain.gemini import GeminiBrain++pytest.importorskip("google.genai")+++class _FakeGeminiClient:+ """Records every ``config`` passed to ``generate_content_stream``."""++ def __init__(self, *, reject_thinking: bool = False) -> None:+ self.calls: list[dict[str, Any]] = []+ self.reject_thinking = reject_thinking+ self.aio = SimpleNamespace(models=self)++ async def generate_content_stream(+ self,+ *,+ model: str,+ contents: list[Any],+ config: dict[str, Any],+ ) -> 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."+ )++ async def _stream() -> AsyncIterator[Any]:+ yield SimpleNamespace(+ text='{"action": "done"}',+ candidates=[],+ usage_metadata=None,+ )++ return _stream()+++async def _drain(stream: AsyncIterator[Any]) -> list[Any]:+ out: list[Any] = []+ async for chunk in stream:+ out.append(chunk)+ return out+++def _request(reasoning_effort: str | None) -> BrainRequest:+ return BrainRequest(+ messages=(BrainMessage(role="user", content="ping"),),+ max_tokens=320,+ reasoning_effort=reasoning_effort, # type: ignore[arg-type]+ )+++async def test_reasoning_effort_none_disables_thinking() -> None:+ provider = GeminiBrain(model="gemini-3.5-flash")+ fake = _FakeGeminiClient()+ provider._client = fake # type: ignore[assignment]++ await _drain(provider.complete(_request("none")))++ assert fake.calls, "no call captured"+ tc = fake.calls[0].get("thinking_config")+ assert tc is not None, (+ "reasoning_effort='none' must attach a thinking_config — without it "+ "a thinking-by-default model eats the 320-token output budget"+ )+ assert getattr(tc, "thinking_budget", None) == 0+++async def test_explicit_constructor_budget_wins_over_hint() -> None:+ provider = GeminiBrain(model="gemini-3.5-flash", thinking_budget=128)+ fake = _FakeGeminiClient()+ provider._client = fake # type: ignore[assignment]++ await _drain(provider.complete(_request("none")))++ tc = fake.calls[0].get("thinking_config")+ assert getattr(tc, "thinking_budget", None) == 128+++async def test_no_hint_keeps_sdk_default() -> None:+ provider = GeminiBrain(model="gemini-3.5-flash")+ fake = _FakeGeminiClient()+ provider._client = fake # type: ignore[assignment]++ await _drain(provider.complete(_request(None)))++ assert "thinking_config" not in fake.calls[0]+++async def test_thinking_mandatory_model_recovers_without_the_field() -> None:+ """A 400 "only works in thinking mode" rejection retries ONCE without+ ``thinking_config`` and the stream succeeds — the hint can never brick a+ provider whose model insists on thinking."""+ provider = GeminiBrain(model="gemini-3.5-pro")+ fake = _FakeGeminiClient(reject_thinking=True)+ provider._client = fake # type: ignore[assignment]++ deltas = await _drain(provider.complete(_request("none")))++ assert len(fake.calls) == 2+ 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/indicator/test_capture_guard.py b/tests/unit/cu/indicator/test_capture_guard.pyindex ed925b50fa..f9790c1f8c 100644--- a/tests/unit/cu/indicator/test_capture_guard.py+++ b/tests/unit/cu/indicator/test_capture_guard.py@@ -58,3 +58,58 @@ def test_unregister_restores_passthrough() -> None:capture_guard.unregister_hook()with capture_guard.indicator_suppressed():pass+++def test_unblank_failure_does_not_kill_the_grab() -> None:+ """A hook whose __exit__ raises (dead sidecar, late ack) must be+ swallowed. The previous ``with cm: yield`` + ``except: yield`` shape+ resumed the generator into a SECOND yield here, which @contextmanager+ turned into ``RuntimeError: generator didn't stop`` — killing the very+ frame grab the guard exists to protect (macOS/Linux path)."""++ @contextmanager+ def hook():+ yield+ raise RuntimeError("sidecar died before the unblank ack")++ capture_guard.register_hook(hook)+ ran = False+ with capture_guard.indicator_suppressed():+ ran = True+ assert ran is True+++def test_grab_exception_propagates_and_still_unblanks() -> None:+ """A failing grab BODY must surface its own error (never a masked+ RuntimeError from the guard), and the indicator must still be restored."""+ events: list[str] = []++ @contextmanager+ def hook():+ events.append("blank")+ try:+ yield+ finally:+ events.append("unblank")++ capture_guard.register_hook(hook)+ with pytest.raises(ValueError, match="grab exploded"):+ with capture_guard.indicator_suppressed():+ raise ValueError("grab exploded")+ assert events == ["blank", "unblank"]+++def test_blank_failure_fails_open_and_still_grabs() -> None:+ """A hook whose __enter__ raises must fail open: the grab runs, no+ error escapes, and no half-entered context is left behind."""++ @contextmanager+ def hook():+ raise RuntimeError("blank IPC broke")+ yield # pragma: no cover++ capture_guard.register_hook(hook)+ ran = False+ with capture_guard.indicator_suppressed():+ ran = True+ assert ran is Truediff --git a/tests/unit/cu/test_brain_call_truncation_retry.py b/tests/unit/cu/test_brain_call_truncation_retry.pynew file mode 100644index 0000000000..6069ca465d--- /dev/null+++ b/tests/unit/cu/test_brain_call_truncation_retry.py@@ -0,0 +1,168 @@+"""Length-truncation recovery in the CU vision dispatch (brain_call.py).++Live forensic 2026-07-16 (voice session 10:37, and every CU mission that+morning): the fast vision model turned thinking-by-default server-side and+spent 304 of the 320 ``max_tokens`` on internal thoughts — the visible reply+arrived as ``{"action": "open_app", "name": "`` and every step died on+"unterminated JSON" until the mission aborted with "could not get a valid+screen-control response". Two defenses, both provider-agnostic:++1. Every CU request carries ``reasoning_effort="none"`` — providers with a+ thinking knob (Gemini) disable internal reasoning for these small+ deterministic JSON calls; providers without one ignore the hint.+2. When a reply still hits the token cap before completing its JSON+ (``is_length_truncated`` + no complete payload), ``_try`` retries ONCE on+ the same provider with real headroom (``max(2048, 4×max_tokens)``) —+ covering thinking models behind gateways that expose no reasoning knob.++Fakes only (no real network) — mirrors the ``_FakeManager``/``_FakeBrain``+shape used in ``test_brain_call_cu_provider.py``.+"""+from __future__ import annotations++from typing import Any++from jarvis.core.protocols import BrainDelta, ImageBlock+from jarvis.cu.brain_call import call_vision_brain++_TRUNCATED = '{"action": "open_app", "name": "'+_COMPLETE = '[{"action": "open_app", "name": "Discord"}]'+++class _ScriptedBrain:+ """Yields one scripted (text, finish_reason) per call; records requests."""++ supports_tools = False+ supports_vision = True++ def __init__(self, script: list[tuple[str, str | None]]) -> None:+ self.script = list(script)+ self.requests: list[Any] = []++ async def complete(self, req: Any): # type: ignore[no-untyped-def]+ self.requests.append(req)+ text, finish = (+ self.script.pop(0) if self.script else (_COMPLETE, "stop")+ )+ 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 exposing only the CU dispatch surface."""++ active_provider = "brain-primary"++ def __init__(self, brain: _ScriptedBrain) -> None:+ self.brain = brain++ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:+ assert level == "fast"+ return [("brain-primary", None)]++ def _get_brain(self, name: str, model: str | None = None) -> _ScriptedBrain:+ return self.brain++ 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")+++async def test_truncated_json_reply_retries_once_with_headroom() -> None:+ """A MAX_TOKENS-cut reply with incomplete JSON triggers exactly ONE retry+ on the same provider, with a much larger ceiling — and the retry's clean+ reply is what the caller receives."""+ brain = _ScriptedBrain([+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ (_COMPLETE, "stop"),+ ])+ manager = _FakeManager(brain)++ reply = await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[_IMG],+ max_tokens=320, early_stop_json=True,+ )++ assert reply.text == _COMPLETE+ assert len(brain.requests) == 2+ assert brain.requests[0].max_tokens == 320+ assert brain.requests[1].max_tokens == 2048 # max(2048, 4*320)+++async def test_complete_json_never_retries() -> None:+ """A clean single-shot reply dispatches exactly one request."""+ brain = _ScriptedBrain([(_COMPLETE, "stop")])+ manager = _FakeManager(brain)++ reply = await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[_IMG],+ max_tokens=320, early_stop_json=True,+ )++ assert reply.text == _COMPLETE+ assert len(brain.requests) == 1+++async def test_natural_stop_prose_does_not_retry() -> None:+ """A model that finished on its own terms (finish=stop) without JSON is a+ parse problem for the engine's failure budget, not a token-cap problem —+ no retry burned on it."""+ brain = _ScriptedBrain([("I cannot help with that.", "stop")])+ manager = _FakeManager(brain)++ reply = await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[_IMG],+ max_tokens=320, early_stop_json=True,+ )++ assert reply.text == "I cannot help with that."+ assert len(brain.requests) == 1+++async def test_still_truncated_after_retry_returns_text_without_third_call() -> None:+ """The headroom retry is ONE-shot: a second truncated reply is returned+ as-is (the engine counts the parse failure) — never a third dispatch."""+ brain = _ScriptedBrain([+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ ])+ manager = _FakeManager(brain)++ reply = await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[_IMG],+ max_tokens=320, early_stop_json=True,+ )++ assert reply.text == _TRUNCATED+ assert len(brain.requests) == 2+++async def test_every_cu_request_asks_for_minimal_reasoning() -> None:+ """Both the first attempt and the headroom retry carry+ ``reasoning_effort="none"`` — the provider-side thinking kill-switch."""+ brain = _ScriptedBrain([+ (_TRUNCATED, "FinishReason.MAX_TOKENS"),+ (_COMPLETE, "stop"),+ ])+ manager = _FakeManager(brain)++ await call_vision_brain(+ manager, build_prompt=_build_prompt, images=[_IMG],+ max_tokens=320, early_stop_json=True,+ )++ assert [r.reasoning_effort for r in brain.requests] == ["none", "none"]