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(agentic-ide): keep pane recaps alive on a depleted provider key
Ruben Lütke4e1affc2a644
diff --git a/jarvis/agentic_ide/recap.py b/jarvis/agentic_ide/recap.pyindex 103e57e6df..a2049cad9f 100644--- a/jarvis/agentic_ide/recap.py+++ b/jarvis/agentic_ide/recap.py@@ -304,12 +304,20 @@ def _typed_into(term: Any) -> bool:return spec is None or bool(getattr(spec, "is_coding_agent", True))-def _task_sentence(task: str, *, sent: int) -> str:- """What this pane was told to do, or an honest note that nothing was."""+def _task_sentence(task: str, *, sent: int, working: bool = False) -> str:+ """What this pane was told to do, or an honest note that nothing was.++ ``working`` distinguishes the two panes the no-instruction sentence used to+ conflate: one that is genuinely idle, and one whose prompt was typed+ straight into the terminal — busy the whole time, yet captioned with a+ sentence that read like "nothing is happening here".+ """if task:return f'Last asked to: "{task}".'if sent:return "Its last instruction came from Jarvis."+ if working:+ return "It is being driven directly in the terminal, not through Jarvis."return "No instruction has been sent to it from Jarvis yet."@@ -335,15 +343,18 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:status = str(getattr(term, "status", "") or "pending")task = _task(term)sent = int(getattr(term, "prompts_sent", 0) or 0)+ activity = _activity(tail)+ idle = idle_phrase(term)+ # A live pane that is visibly producing output but was never sent a prompt+ # is being driven by hand — the caption must say that, not imply idleness.+ working = status == "live" and bool(activity or idle)# One sentence about the instruction, computed once: every branch below# opens with it, and a plain terminal answers it differently.asked = (- _task_sentence(task, sent=sent)+ _task_sentence(task, sent=sent, working=working)if _typed_into(term)else "This is a plain terminal — you type into it yourself.")- activity = _activity(tail)- idle = idle_phrase(term)if status == "error":problem = condense(getattr(term, "error", ""), HEADLINE_CHARS)diff --git a/jarvis/agentic_ide/recap_engine.py b/jarvis/agentic_ide/recap_engine.pyindex baab1c2960..46398d752d 100644--- a/jarvis/agentic_ide/recap_engine.py+++ b/jarvis/agentic_ide/recap_engine.py@@ -26,10 +26,12 @@ fallback rather than as the product:* **Bounded.** At most :data:`MAX_CONCURRENT` summaries are in flight across thewhole app, each with its own timeout, and a pane whose summaries keep failinggoes quiet for a while instead of retrying every poll.-* **Optional by construction** (§3). No key, no reachable provider, a provider- that 429s — every one of those paths ends at the deterministic recap, which is- exactly what the pane showed before this module existed. Nothing here is- load-bearing, and nothing here may raise into a state read.+* **Optional by construction** (§3). No key, no reachable provider — those+ paths end at the deterministic recap, which is exactly what the pane showed+ before this module existed. A provider that fails at CALL time (a depleted+ key's 429, a 402) first crosses to the next provider FAMILY in the resolver+ chain (AP-22) and only then falls back to the deterministic floor. Nothing+ here is load-bearing, and nothing here may raise into a state read.Above the model sits one more layer, and it outranks both: **what the userwrote themselves**. No summarizer can know that a pane is "the branch I'm about@@ -101,6 +103,13 @@ INPUT_TAIL_CHARS = INPUT_CHARS - INPUT_HEAD_CHARS#: recap nobody is waiting for does not deserve a long leash.CALL_TIMEOUT_S = 30.0+#: How many provider FAMILIES a single summary may try before giving up. A+#: depleted key fails at call time, after instantiating fine — the next try+#: must come from a different family (AP-22), and two spare families cover+#: every install that has anything to cross to without turning one recap into+#: a tour of every configured provider.+MAX_PROVIDER_TRIES = 3+#: After this many consecutive failures a pane stops asking for a while. A#: depleted key, an unreachable provider, or a model that refuses the format#: fails for every pane and every poll; without this it would fail loudly and@@ -164,6 +173,27 @@ NO_PROVIDER_NOTE = "No model is reachable to summarize this pane."#: providers put the API key in the request URL, and this string is rendered in#: the recap card — where a screenshot would carry it straight out of the app._SECRET_RE = re.compile(r"(?i)(key|token|secret|password|authorization)=[^\s&\"']+")++#: Failure shapes worth a plain sentence. The raw provider error is a wall of+#: JSON — the screenshot-famous one opened with ``ClientError: 429 Too Many+#: Requests. {'message': '{\\n "error": …`` — and the recap card is read by+#: someone deciding what to DO, so the first words must say that. Matched+#: against ``TypeName: message`` so an empty-message ``TimeoutError`` still+#: lands on its sentence. First match wins; order the specific ones first.+_FAILURE_HINTS: tuple[tuple[re.Pattern[str], str], ...] = (+ (+ re.compile(r"(?i)\b429\b|too many requests|rate.?limit|quota|depleted|exhausted"),+ "Its provider is out of credits or rate-limited.",+ ),+ (+ re.compile(r"(?i)\b40[13]\b|unauthorized|forbidden|api.?key|invalid.*credential"),+ "Its provider rejected the credential.",+ ),+ (+ re.compile(r"(?i)timeout|timed?[ -]?out"),+ "Its provider did not answer in time.",+ ),+)_TITLE_WORD_RE = re.compile(r"\b[^\W\d_][\w'-]*\b", flags=re.UNICODE)_SHELL_FRAGMENT_RE = re.compile(r"(?:^|\s)--?[a-zA-Z]\w*|[*?][./\\\w]")_DETAIL_SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")@@ -292,15 +322,22 @@ _inflight = 0def describe_failure(exc: BaseException) -> str:"""A failed summary in one short line the recap card can show.- The type is always there, because a bare provider message is often empty or- a wall of JSON, and knowing it was an authentication error rather than a- timeout is most of the answer. Whatever the provider said follows, truncated- and with anything credential-shaped removed: this string ends up on screen,- and some providers put the API key in the URL they echo back (AP-2/AP-12).+ A recognized shape — a depleted or rate-limited key, a rejected credential,+ a timeout — leads with a plain sentence, because the card is read by someone+ deciding what to do, not by someone parsing provider JSON. The type is+ always there, because a bare provider message is often empty or a wall of+ JSON, and knowing it was an authentication error rather than a timeout is+ most of the answer. Whatever the provider said follows, truncated and with+ anything credential-shaped removed: this string ends up on screen, and some+ providers put the API key in the URL they echo back (AP-2/AP-12)."""text = _SECRET_RE.sub(r"\1=…", str(exc or "").strip())kind = type(exc).__name__- return recap.condense(f"{kind}: {text}" if text else kind, 200)+ raw = f"{kind}: {text}" if text else kind+ for pattern, sentence in _FAILURE_HINTS:+ if pattern.search(raw):+ return recap.condense(f"{sentence} ({raw})", 200)+ return recap.condense(raw, 200)def _state(key: str) -> _PaneState:@@ -541,22 +578,29 @@ def _store(entry.note = ""-def _resolve_brain(): # noqa: ANN202 - Brain | None, avoids an import cycle- """A model that can write the recap, or None when the install has none.+def _resolve_brains() -> list[Any]:+ """The brains that could write the recap, best first. Empty when none can.Resolution goes through ``jarvis.brain.resolver`` so this module never grows- its own opinion about providers (AP-21/AP-22): whatever single key the user- has is what writes the recap, and an install with none gets None and the- deterministic floor.+ its own opinion about providers (AP-21/AP-22): whatever keys the user has+ are what write the recap, and an install with none gets an empty list and+ the deterministic floor. More than one candidate comes back because the+ ordinary failure is CALL-time — a depleted key instantiates fine and only+ 429s when asked to write — and the retry must cross to a different family."""try:- from jarvis.brain.resolver import resolve_frontier_brain+ from jarvis.brain.resolver import frontier_brain_candidatesfrom jarvis.core.config import load_config- return resolve_frontier_brain(load_config())+ candidates: list[Any] = []+ for brain in frontier_brain_candidates(load_config()):+ candidates.append(brain)+ if len(candidates) >= MAX_PROVIDER_TRIES:+ break+ return candidatesexcept Exception as exc: # noqa: BLE001 - no brain is an answer, not an errorlogger.info("Agentic IDE recap: no brain reachable ({})", exc)- return None+ return []def _bounded_rows(@@ -737,12 +781,37 @@ async def summarize_with_model() -> SmartRecap | None:"""Ask a model what this pane has been doing. None when nothing can answer.- Raises only what the provider raises — the caller turns that into "keep the- previous sentence", which is the whole error handling this feature needs.+ Walks the resolver's candidate chain rather than trusting its first pick:+ the first brain in it is whatever the user configured, and the ordinary way+ that brain fails is at call time — a depleted key instantiates fine and+ 429s when asked to write. Each further try is a different provider FAMILY+ (AP-22), so the recap lands on whatever key the user actually has instead+ of dying with the depleted one. Only when every candidate has failed does+ this raise, and it raises the FIRST failure — the configured provider's,+ which is the one the user can act on."""- brain = await asyncio.to_thread(_resolve_brain)- if brain is None:+ brains = await asyncio.to_thread(_resolve_brains)+ if not brains:return None+ first_failure: Exception | None = None+ for brain in brains:+ try:+ return await _summarize_on(brain, term, rows, folder=folder)+ except Exception as exc: # noqa: BLE001 - the next family is the handling+ first_failure = first_failure or exc+ logger.info(+ "Agentic IDE recap: {} could not write it ({}) — crossing to the next provider",+ getattr(brain, "model", "") or getattr(brain, "name", "") or type(brain).__name__,+ type(exc).__name__,+ )+ assert first_failure is not None # noqa: S101 - the loop above ran at least once+ raise first_failure+++async def _summarize_on(+ brain: Any, term: Any, rows: Sequence[str], *, folder: str = ""+) -> SmartRecap:+ """One summary on one brain. Raises whatever the provider raises."""from jarvis.core.protocols import BrainMessage, BrainRequestrequest = BrainRequest(diff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.pyindex 25c19f24b3..65d5fbec96 100644--- a/jarvis/brain/resolver.py+++ b/jarvis/brain/resolver.py@@ -37,6 +37,8 @@ from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDERfrom jarvis.brain.provider_registry import BrainProviderRegistryif TYPE_CHECKING:+ from collections.abc import Iterator+from jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfigfrom jarvis.core.protocols import Brain@@ -149,6 +151,54 @@ def resolve_frontier_brain()+def frontier_brain_candidates(+ config: JarvisConfig,+ *,+ bus: EventBus | None = None,+) -> Iterator[Brain]:+ """Instantiable frontier brains along the fallback chain, one per family.++ ``resolve_frontier_brain`` answers "give me ONE brain" and crosses families+ only when a stage cannot be *instantiated*. That gate misses the ordinary+ depleted-key case: most providers construct their client happily without+ checking the balance and only fail at CALL time (429/402). A caller that+ wants the cross-family promise of AP-22 to hold at call time iterates this+ instead: try the first candidate, and when the request itself fails, move+ to the next FAMILY — a second model behind the same depleted key would+ just fail the same way, so each provider appears at most once.++ Lazy on purpose: a candidate is instantiated only when the caller reaches+ it, and the shared cache keeps repeated walks free. Yields nothing when no+ stage can be instantiated — the caller's "no provider" path, not an error.+ """+ _ensure_bus_subscription(bus)+ try:+ chain = list(_resolve_chain(config))+ except Exception: # noqa: BLE001 - a config problem must not kill the caller+ log.info("frontier_brain_candidates: chain could not be built", exc_info=True)+ return+ yielded: set[str] = set()+ for provider, model in chain:+ if provider in yielded:+ continue+ cache_key = (provider, model or "")+ brain = _cache.get(cache_key)+ if brain is None:+ try:+ brain = _get_registry().instantiate(+ provider, **({"model": model} if model else {}),+ )+ except Exception as exc: # noqa: BLE001+ log.info(+ "frontier_brain_candidates: %s/%s not instantiable (%s)",+ provider, model or "<default>", type(exc).__name__,+ )+ continue+ _cache[cache_key] = brain+ yielded.add(provider)+ yield brain++def _is_fast_tier(config: JarvisConfig, provider: str, model: str | None) -> bool:"""Whether ``(provider, model)`` is this install's latency-first tier.diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.pyindex 1175d37ad0..6d0d8bd71c 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -508,6 +508,13 @@ _AGENTS: dict[str, WorkspaceAgent] = {# only slow down behaviour that already works.needs_input_line_wait=False,instruction_filename="CLAUDE.md",+ # Its footer row ("<folder> 🌿 <branch> <model> (1M context)") carries+ # plenty of letters, so without these the deterministic recap of a busy+ # pane quoted the footer as its "activity". The branch glyph is the+ # stable marker; the tip prefix covers the rotating "Tip: Use /btw …"+ # hint rows. The key-hint half of the footer already matches the shared+ # "shift+tab" fragment.+ chrome_fragments=("🌿", "tip: use"),spoken_aliases=("claude", "cloude", "claud", "clode", "klaude", "kloude"),spoken_aliases_needing_suffix=("cloud", "clawed", "clod", "loud"),),diff --git a/tests/unit/agentic_ide/test_recap.py b/tests/unit/agentic_ide/test_recap.pyindex c0ea167b15..3d535ed261 100644--- a/tests/unit/agentic_ide/test_recap.py+++ b/tests/unit/agentic_ide/test_recap.py@@ -86,6 +86,39 @@ def test_tui_chrome_never_becomes_the_headline() -> None:assert summarize(term).headline == "Writing jarvis/core/config_writer.py"+def test_the_claude_code_footer_never_becomes_the_headline() -> None:+ """The folder/branch/model footer is redrawn on every frame — pure chrome.++ Observed live: a busy pane whose newest rows were all footer captioned+ itself "Personal Jarvis 🌿 main Opus 5 (1M context)" — three facts the pane+ header already shows elsewhere, and zero about the work.+ """+ term = _pane(status="live")+ term.transcript.feed("Traced the stale process to yesterday\r\n")+ term.transcript.feed("Tip: Use /btw to ask a quick side question\r\n")+ term.transcript.feed("Personal Jarvis 🌿 main Opus 5 (1M context)\r\n")++ assert summarize(term).headline == "Traced the stale process to yesterday"+++def test_a_hand_driven_busy_pane_does_not_claim_it_was_never_instructed() -> None:+ """"No instruction yet" on a pane that worked for hours reads as broken."""+ term = _pane(status="live", last_output_at=time.time())+ term.transcript.feed("Ran 42 tests, all green\r\n")++ detail = summarize(term).detail++ assert "No instruction has been sent" not in detail+ assert "driven directly in the terminal" in detail+++def test_a_live_pane_with_no_output_still_says_nothing_was_sent() -> None:+ """The idle wording stays for a pane that truly has nothing going on."""+ term = _pane(status="live")++ assert "No instruction has been sent" in summarize(term).detail++def test_the_input_line_never_becomes_the_headline() -> None:"""The prompt box is what the USER is typing, not what the agent is doing."""term = _pane(status="live")diff --git a/tests/unit/agentic_ide/test_recap_engine.py b/tests/unit/agentic_ide/test_recap_engine.pyindex befd9d085f..1ef3ee823d 100644--- a/tests/unit/agentic_ide/test_recap_engine.py+++ b/tests/unit/agentic_ide/test_recap_engine.py@@ -303,7 +303,7 @@ def test_cli_debris_is_rejected_as_a_model_headline(answer: str) -> None:def test_an_install_with_no_provider_keeps_the_deterministic_recap(monkeypatch) -> None:"""§3: one key, no key, a dead key — the pane header still says something."""- monkeypatch.setattr(recap_engine, "_resolve_brain", lambda: None)+ monkeypatch.setattr(recap_engine, "_resolve_brains", lambda: [])assert asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20))) is None@@ -328,7 +328,7 @@ def test_the_recap_request_disables_internal_reasoning(monkeypatch) -> None:)brain = Brain()- monkeypatch.setattr(recap_engine, "_resolve_brain", lambda: brain)+ monkeypatch.setattr(recap_engine, "_resolve_brains", lambda: [brain])answer = asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20)))@@ -361,7 +361,7 @@ def test_an_invalid_small_answer_retries_with_the_measured_larger_budget(monkeypyield SimpleNamespace(content=content)brain = Brain()- monkeypatch.setattr(recap_engine, "_resolve_brain", lambda: brain)+ monkeypatch.setattr(recap_engine, "_resolve_brains", lambda: [brain])answer = asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20)))@@ -372,6 +372,71 @@ def test_an_invalid_small_answer_retries_with_the_measured_larger_budget(monkeyp]+def test_a_depleted_provider_crosses_to_the_next_family(monkeypatch) -> None:+ """AP-22 at call time: a key that 429s must not take the recap down with it."""++ class Depleted:+ model = "gemini-depleted"++ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ raise RuntimeError("429 Too Many Requests: prepayment credits are depleted")+ yield # pragma: no cover - makes this an async generator++ class Working:+ model = "other-family"++ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ yield SimpleNamespace(+ content=(+ "HEADLINE: Pane recaps — cross-family fallback\n"+ "DETAIL: The goal is a recap that survives a depleted key. "+ "The second provider family wrote this one."+ )+ )++ monkeypatch.setattr(recap_engine, "_resolve_brains", lambda: [Depleted(), Working()])++ answer = asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20)))++ assert answer is not None+ assert answer.headline == "Pane recaps — cross-family fallback"+ assert answer.writer == "other-family"+++def test_when_every_family_fails_the_first_failure_is_reported(monkeypatch) -> None:+ """The configured provider's error is the one the user can act on."""++ def _dead(model: str, message: str): # noqa: ANN202+ class Dead:+ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ raise RuntimeError(message)+ yield # pragma: no cover - makes this an async generator++ Dead.model = model+ return Dead()++ monkeypatch.setattr(+ recap_engine,+ "_resolve_brains",+ lambda: [_dead("first", "429 quota exceeded"), _dead("second", "connection refused")],+ )++ with pytest.raises(RuntimeError, match="429 quota exceeded"):+ asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20)))+++def test_a_depleted_key_failure_reads_as_a_sentence_not_json() -> None:+ """The screenshot case: the card led with a wall of provider JSON."""+ note = recap_engine.describe_failure(+ RuntimeError(+ "429 Too Many Requests. {'message': '{\\n \"error\": {\\n \"code\": 429,"+ "\\n \"message\": \"Your prepayment credits are depleted.\"}}'}"+ )+ )++ assert note.startswith("Its provider is out of credits or rate-limited.")++def test_a_failing_provider_leaves_the_previous_sentence_in_place() -> None:"""A provider that raises costs the refresh, never the recap on screen."""diff --git a/tests/unit/brain/test_resolver_frontier_candidates.py b/tests/unit/brain/test_resolver_frontier_candidates.pynew file mode 100644index 0000000000..2d7dce173c--- /dev/null+++ b/tests/unit/brain/test_resolver_frontier_candidates.py@@ -0,0 +1,100 @@+"""The lazy frontier candidate walk that makes AP-22 hold at CALL time.++``resolve_frontier_brain`` crosses families only when a stage cannot be+INSTANTIATED — but the ordinary depleted-key failure happens later, at call+time, after the client constructed happily. ``frontier_brain_candidates`` is+the call-time half: a caller iterates it and moves to the next provider FAMILY+when a request itself fails. These tests pin the promises that make that walk+usable: one candidate per family, lazy instantiation, and no exceptions out of+a broken chain.+"""+from __future__ import annotations++import pytest++from jarvis.brain import resolver+++class _FakeRegistry:+ def __init__(self, fail_providers: set[str] | None = None) -> None:+ self.attempts: list[tuple[str, str]] = []+ self.fail_providers = fail_providers or set()++ def instantiate(self, provider: str, **kwargs: object) -> object:+ self.attempts.append((provider, str(kwargs.get("model", ""))))+ if provider in self.fail_providers:+ raise RuntimeError("no key")+ return object()++[email protected](autouse=True)+def _clean_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(resolver, "_cache", {})+++def test_each_provider_family_appears_at_most_once(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A second model behind the same depleted key would fail the same way."""+ monkeypatch.setattr(+ resolver,+ "_resolve_chain",+ lambda cfg: [+ ("gemini", "gemini-3.1-pro-preview"),+ ("gemini", "gemini-3.5-flash"),+ ("claude-api", "claude-opus-5"),+ ],+ )+ fake = _FakeRegistry()+ monkeypatch.setattr(resolver, "_get_registry", lambda: fake)++ candidates = list(resolver.frontier_brain_candidates(object()))++ assert len(candidates) == 2+ assert fake.attempts == [+ ("gemini", "gemini-3.1-pro-preview"),+ ("claude-api", "claude-opus-5"),+ ]+++def test_instantiation_is_lazy(monkeypatch: pytest.MonkeyPatch) -> None:+ """A caller that stops after the first candidate never pays for the rest."""+ monkeypatch.setattr(+ resolver,+ "_resolve_chain",+ lambda cfg: [("gemini", "gemini-3.1-pro-preview"), ("openai", "gpt-5.5-pro")],+ )+ fake = _FakeRegistry()+ monkeypatch.setattr(resolver, "_get_registry", lambda: fake)++ next(resolver.frontier_brain_candidates(object()))++ assert fake.attempts == [("gemini", "gemini-3.1-pro-preview")]+++def test_a_stage_that_cannot_instantiate_is_skipped(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ resolver,+ "_resolve_chain",+ lambda cfg: [("gemini", "gemini-3.1-pro-preview"), ("openai", "gpt-5.5-pro")],+ )+ fake = _FakeRegistry(fail_providers={"gemini"})+ monkeypatch.setattr(resolver, "_get_registry", lambda: fake)++ candidates = list(resolver.frontier_brain_candidates(object()))++ assert len(candidates) == 1+ assert fake.attempts[-1] == ("openai", "gpt-5.5-pro")+++def test_a_broken_chain_yields_nothing_rather_than_raising(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def explode(cfg: object) -> list[tuple[str, str]]:+ raise ValueError("config is nonsense")++ monkeypatch.setattr(resolver, "_resolve_chain", explode)++ assert list(resolver.frontier_brain_candidates(object())) == []