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.

16.3 KB
Raw Blame
"""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_level=LOW`` (Gemini 3). gemini-3.7-flash has no off switch,
  400s on MINIMAL, and its default is MEDIUM — budget=0 is not the knob.
* A model that rejects ``thinking_level`` (Gemini 2.5) is recovered by a
  retry with ``thinking_budget=0``, then without the field if that 400s
  too — capability probe, not a model-name pin (AP-21).
* An explicit constructor ``thinking_budget`` other than 0 always wins
  over the hint.
* No hint, no constructor budget → no ``thinking_config`` (SDK default).

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, Iterator
from types import SimpleNamespace
from typing import Any

import pytest

from dodaios.core.protocols import BrainMessage, BrainRequest
from dodaios.plugins.brain.gemini import (
    _REJECTED_THINKING_BUDGETS,
    _REJECTED_THINKING_LEVELS,
    GeminiBrain,
)

pytest.importorskip("google.genai")


@pytest.fixture(autouse=True)
def _clear_process_capability_memory() -> Iterator[None]:
    """Keep process-wide production capability memory isolated per test."""
    _REJECTED_THINKING_BUDGETS.clear()
    _REJECTED_THINKING_LEVELS.clear()
    yield
    _REJECTED_THINKING_BUDGETS.clear()
    _REJECTED_THINKING_LEVELS.clear()


class _FakeGeminiClient:
    """Records every ``config`` passed to ``generate_content_stream``."""

    def __init__(
        self,
        *,
        reject_thinking: bool = False,
        reject_message: str = (
            "400 INVALID_ARGUMENT. Budget 0 is invalid. This model only "
            "works in thinking mode."
        ),
        reject_thinking_generic: bool = False,
        reject_everything_generic: bool = False,
    ) -> None:
        self.calls: list[dict[str, Any]] = []
        self.reject_thinking = reject_thinking
        self.reject_message = reject_message
        self.reject_thinking_generic = reject_thinking_generic
        self.reject_everything_generic = reject_everything_generic
        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(self.reject_message)
        if (
            self.reject_everything_generic
            or (
                self.reject_thinking_generic
                and config.get("thinking_config") is not None
            )
        ):
            # The parameterless rejection shape gemini-3.6-flash produced
            # live 2026-07-21 — no field name, no "thinking" token.
            raise RuntimeError(
                "400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': "
                "'Request contains an invalid argument.', 'status': "
                "'INVALID_ARGUMENT'}}"
            )

        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 _level_name(tc: object | None) -> str:
    """``ThinkingLevel.LOW`` and the string ``"LOW"`` both count as LOW."""
    raw = getattr(tc, "thinking_level", None) if tc is not None else None
    if raw is None:
        return ""
    return str(getattr(raw, "value", raw) or "").upper().rsplit(".", 1)[-1]


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]
    )


@pytest.mark.asyncio
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"
    )
    # Gemini 3.7 Flash: LOW is the lowest accepted level. Budget=0 is not
    # an off switch there, and sending both fields 400s.
    assert _level_name(tc) == "LOW"
    assert getattr(tc, "thinking_budget", None) is None


@pytest.mark.asyncio
async def test_constructor_budget_zero_uses_thinking_level_low() -> None:
    """The router cap is thinking_budget=0. On Gemini 3 that is not an off
    switch — LOW is the closest the model accepts."""
    provider = GeminiBrain(model="gemini-3.7-flash", thinking_budget=0)
    fake = _FakeGeminiClient()
    provider._client = fake  # type: ignore[assignment]

    await _drain(provider.complete(_request(None)))

    tc = fake.calls[0].get("thinking_config")
    assert _level_name(tc) == "LOW"
    assert getattr(tc, "thinking_budget", None) is None


@pytest.mark.asyncio
async def test_thinking_level_rejection_falls_back_to_budget_zero() -> None:
    """Gemini 2.5 400s on thinking_level and accepts thinking_budget=0."""

    class _LevelThenBudget(_FakeGeminiClient):
        async def generate_content_stream(  # type: ignore[override]
            self, *, model: str, contents: list[Any], config: dict[str, Any]
        ) -> AsyncIterator[Any]:
            self.calls.append(dict(config))
            tc = config.get("thinking_config")
            if tc is not None and getattr(tc, "thinking_level", None):
                raise RuntimeError(
                    "400 INVALID_ARGUMENT. thinking_level is not supported "
                    "for this model."
                )

            async def _stream() -> AsyncIterator[Any]:
                yield SimpleNamespace(
                    text='{"action": "done"}',
                    candidates=[],
                    usage_metadata=None,
                )

            return _stream()

    provider = GeminiBrain(model="gemini-2.5-flash")
    fake = _LevelThenBudget()
    provider._client = fake  # type: ignore[assignment]

    deltas = await _drain(provider.complete(_request("none")))

    assert len(fake.calls) == 2
    assert _level_name(fake.calls[0].get("thinking_config")) == "LOW"
    assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
    assert any(d.content for d in deltas)

    await _drain(provider.complete(_request("none")))
    assert len(fake.calls) == 3
    assert getattr(fake.calls[2].get("thinking_config"), "thinking_budget", None) == 0


@pytest.mark.asyncio
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


@pytest.mark.asyncio
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]


@pytest.mark.asyncio
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) == 3
    assert _level_name(fake.calls[0].get("thinking_config")) == "LOW"
    assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
    assert "thinking_config" not in fake.calls[2]
    assert any(d.content for d in deltas), "recovered stream must yield text"


@pytest.mark.asyncio
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) == 3, (
        "level rejected → budget=0 → drop the field; three attempts, then text"
    )
    assert fake.calls[0].get("thinking_config") is not None
    assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
    assert "thinking_config" not in fake.calls[2]
    assert any(d.content for d in deltas), "recovered stream must yield text"


@pytest.mark.asyncio
async def test_parameterless_400_recovers_and_is_remembered() -> None:
    """Live 2026-07-21: ``gemini-3.6-flash`` rejects ``thinking_budget=0``
    with the bare "Request contains an invalid argument." — no "thinking" in
    the message. The recovery must (a) retry once without ``thinking_config``
    and yield the answer, and (b) once that retry is accepted, skip the field
    on every later turn so each delegated realtime turn doesn't pay a doomed
    extra round trip."""
    provider = GeminiBrain(model="gemini-3.6-flash")
    fake = _FakeGeminiClient(reject_thinking_generic=True)
    provider._client = fake  # type: ignore[assignment]

    deltas = await _drain(provider.complete(_request("none")))

    assert len(fake.calls) == 3
    assert fake.calls[0].get("thinking_config") is not None
    assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
    assert "thinking_config" not in fake.calls[2]
    assert any(d.content for d in deltas), "recovered stream must yield text"

    # Second turn: both knobs are proven rejected — no thinking_config.
    await _drain(provider.complete(_request("none")))
    assert len(fake.calls) == 4
    assert "thinking_config" not in fake.calls[3]


@pytest.mark.asyncio
async def test_parameterless_400_is_remembered_across_instances() -> None:
    """Short-lived curator brains must share a proven model capability.

    The curator creates a fresh provider for each distilled item. An
    instance-only cache therefore paid one rejected request per item even
    though the first accepted retry had already proved the capability.
    """
    first = GeminiBrain(model="gemini-short-lived-curator")
    first_fake = _FakeGeminiClient(reject_thinking_generic=True)
    first._client = first_fake  # type: ignore[assignment]

    await _drain(first.complete(_request("none")))
    assert len(first_fake.calls) == 3

    second = GeminiBrain(model="gemini-short-lived-curator")
    second_fake = _FakeGeminiClient(reject_thinking_generic=True)
    second._client = second_fake  # type: ignore[assignment]

    await _drain(second.complete(_request("none")))

    assert len(second_fake.calls) == 1
    assert "thinking_config" not in second_fake.calls[0]


@pytest.mark.asyncio
async def test_unrelated_400_still_propagates_and_forgets_nothing() -> None:
    """A parameterless 400 whose retry ALSO fails is not the thinking
    config's fault: the error must propagate and the instance must NOT stop
    sending ``thinking_config`` on later turns."""
    provider = GeminiBrain(model="gemini-3.6-flash")
    fake = _FakeGeminiClient(reject_everything_generic=True)
    provider._client = fake  # type: ignore[assignment]

    with pytest.raises(RuntimeError, match="invalid argument"):
        await _drain(provider.complete(_request("none")))

    # level → budget → drop, then the error surfaced. Budget blame is not
    # proven because the retry without the field also 400'd.
    assert len(fake.calls) == 3

    fake.reject_everything_generic = False
    await _drain(provider.complete(_request("none")))
    # The level was proven rejected (the hop happened). The budget was
    # not: the no-config retry 400'd too, so the next turn still sends it.
    assert fake.calls[3].get("thinking_config") is not None, (
        "an unproven budget blame must not permanently disable thinking_config"
    )
    assert getattr(fake.calls[3].get("thinking_config"), "thinking_budget", None) == 0


@pytest.mark.asyncio
async def test_generic_400_with_live_cache_clears_cache_and_blames_nothing(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """A parameterless 400 while a ``cached_content`` reference is on the
    wire could be a differently-worded dead-cache rejection: the recovery
    must clear the cache reference alongside ``thinking_config`` (else the
    poisoned name survives forever — BUG-019's symptom) and must NOT blame
    the thinking budget, because with two variables changed the accepted
    retry proves nothing."""
    monkeypatch.setenv("JARVIS_GEMINI_CONTEXT_CACHE", "1")

    system_text = "X" * (4096 * 4 + 100)  # above the _MIN_CACHE_TOKENS floor
    provider = GeminiBrain(model="gemini-3.6-flash")
    fake = _FakeGeminiClient()
    provider._client = fake  # type: ignore[assignment]
    provider._cached_content_name = "cachedContents/dead-id"
    provider._cache_signature = (str(hash(system_text)), "")

    async def _reject_cache_or_thinking(
        *, model: str, contents: list[Any], config: dict[str, Any]
    ) -> Any:
        fake.calls.append(dict(config))
        if config.get("cached_content") or config.get("thinking_config"):
            raise RuntimeError(
                "400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': "
                "'Request contains an invalid argument.', 'status': "
                "'INVALID_ARGUMENT'}}"
            )

        async def _stream() -> AsyncIterator[Any]:
            yield SimpleNamespace(text="OK", candidates=[], usage_metadata=None)

        return _stream()

    fake.generate_content_stream = _reject_cache_or_thinking  # type: ignore[method-assign]

    req = BrainRequest(
        messages=(BrainMessage(role="user", content="ping"),),
        max_tokens=320,
        system=system_text,
        reasoning_effort="none",  # type: ignore[arg-type]
    )
    deltas = await _drain(provider.complete(req))

    assert len(fake.calls) == 2
    assert fake.calls[0].get("cached_content") == "cachedContents/dead-id"
    assert fake.calls[0].get("thinking_config") is not None
    assert "cached_content" not in fake.calls[1]
    assert "thinking_config" not in fake.calls[1]
    assert any(d.content for d in deltas), "recovered stream must yield text"
    assert provider._cached_content_name is None, (
        "the possibly-dead cache reference must be invalidated"
    )
    assert provider._rejected_thinking_budgets == set(), (
        "a two-variable retry must not blame the thinking budget"
    )