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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 18:19)
Ruben Lütke176188af2d9b
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 3e190ef374..c85d962c10 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -165,6 +165,7 @@ _MAIN_BRAIN_FALLBACK_PROVIDER_ORDER: tuple[str, ...] = ("claude-api","openai","openrouter",+ "nvidia",)# Human-readable display names for each brain provider id. Used to tell the@@ -1951,6 +1952,14 @@ class BrainManager:# reset). Prevents each voice turn from running through 8 sequential# "no API key" failures.self._dead_providers: set[str] = set()+ # Model-scoped twin of `_dead_providers`: a billing-style rejection+ # (account_blocked, e.g. HTTP 402) on ONE model must not dead-list a+ # provider that has other, untried models still in this turn's chain+ # (e.g. a paid model capped out while a free model on the same+ # provider is still funded). Populated/consulted only for+ # account_blocked; missing_key/bad_key stay provider-wide since a+ # dead credential blocks every model on that provider.+ self._dead_provider_models: set[tuple[str, str | None]] = set()# Populated by from_tier_config(). Tier fallbacks are runtime# priorities, not just healthcheck metadata.self._configured_fallbacks: list[tuple[str, str | None]] = []@@ -6307,10 +6316,22 @@ class BrainManager:if name in seen or name == self._active_name or name not in available:continueseen.add(name)+ # Skip providers dead-listed or rate-limited THIS session — the+ # chain walk (see the dead_providers/rate_tracker checks at the+ # top of the provider-chain loop below) already excludes them+ # from actually answering, so picking one here as the "lead"+ # left _router_lead_key pointing at an entry the chain would+ # never reach: _is_router_lead misfired for the real lead and+ # the toolless fall-through gate accepted a tool-incapable+ # provider's answer as final.+ if name in self._dead_providers:+ continuemodel = (self._deep_model(name) if level in ("deep", "code")else self._fast_model(name)) or self._fast_model(name)+ if not self._rate_tracker.is_available(name, model):+ continueif self._brain_can_call_tools(name, model):return (name, model)return Nonediff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex 45565ee5d4..a57f8768fd 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -71,6 +71,7 @@ def _build_browser_session(send_binary=send_binary,send_json=send_json,surface="browser",+ brain=getattr(state, "brain", None),)if rt is not None:return rtdiff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.pyindex 235fda12d3..ce56144a35 100644--- a/jarvis/realtime/factory.py+++ b/jarvis/realtime/factory.py@@ -85,6 +85,7 @@ def build_realtime_session(send_json: Any,half_duplex: bool = False,surface: str = "browser",+ brain: Any = None,):"""Build a transport-neutral realtime session wrapper.@@ -112,6 +113,7 @@ def build_realtime_session(bus=bus,half_duplex=half_duplex,surface=surface,+ brain=brain,)except Exception as exc: # noqa: BLE001 — unbuildable stack => classic pathlog.warning("Realtime session build failed: %s", exc)diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex ab6a4a2886..8ae7777c0b 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -61,6 +61,8 @@ class RealtimeVoiceSession:browser_sample_rate: int = 48_000,half_duplex: bool = False,surface: str = "browser",+ brain: Any = None,+ tool_bridge: Any = None,) -> None:self.session_id = session_idself._send_binary = send_binary@@ -83,6 +85,16 @@ class RealtimeVoiceSession:self._output_active = Falseself._language = self._resolve_lang(text="")+ if tool_bridge is None and brain is not None:+ try:+ from jarvis.realtime.tools import RealtimeToolBridge++ tool_bridge = RealtimeToolBridge.from_brain(+ brain, language=self._language+ )+ except Exception: # noqa: BLE001 — conversation still works without tools+ log.warning("Realtime tool bridge is unavailable", exc_info=True)+ self._tool_bridge = tool_bridgeself._gate = ScrubHoldGate(self._language)self._session: Any = Noneself._pump_task: asyncio.Task[None] | None = None@@ -97,6 +109,8 @@ class RealtimeVoiceSession:self._turn_index = 0self._last_user_text = ""self._output_transcript: list[str] = []+ self._executed_tool_names: set[str] = set()+ self._pending_tool_events: list[Any] = []def _resolve_lang(self, *, text: str) -> str:brain = getattr(self._config, "brain", None)@@ -167,6 +181,11 @@ class RealtimeVoiceSession:input_sample_rate=input_rate,output_sample_rate=output_rate,modalities=("audio",),+ tools=(+ self._tool_bridge.declarations+ if self._tool_bridge is not None+ else ()+ ),)try:session = await provider.open_session(session_config)@@ -242,8 +261,12 @@ class RealtimeVoiceSession:instructions=_session_instructions(new_language),language=new_language,)+ if self._tool_bridge is not None:+ self._tool_bridge.set_language(new_language)mark_phase(LatencyPhase.REALTIME_INPUT_COMMITTED)self._last_user_text = event.text+ if self._tool_bridge is not None and event.is_final:+ await self._tool_bridge.handle_user_transcript(event.text)if not self._turn_id:self._turn_id = str(uuid4())self._turn_index += 1@@ -257,6 +280,11 @@ class RealtimeVoiceSession:"is_final": bool(event.is_final),})+ if event.is_final and self._pending_tool_events:+ pending = self._pending_tool_events+ self._pending_tool_events = []+ for pending_event in pending:+ await self._handle_tool_call(pending_event)elif event.type == "output_transcript_delta" and event.text:mark_phase(LatencyPhase.REALTIME_FIRST_TRANSCRIPT)display = await self._gate.feed_transcript(event.text)@@ -293,7 +321,17 @@ class RealtimeVoiceSession:)elif event.type in {"speech_started", "interrupted"}:await self._barge_in()+ elif event.type == "tool_call":+ if not self._last_user_text:+ self._pending_tool_events.append(event)+ else:+ await self._handle_tool_call(event)elif event.type == "turn_complete":+ if self._pending_tool_events:+ pending = self._pending_tool_events+ self._pending_tool_events = []+ for pending_event in pending:+ await self._reject_untranscribed_tool_call(pending_event)self._cancel_release_task()for chunk in self._gate.release_available():await self._emit_audio(chunk)@@ -466,6 +504,7 @@ class RealtimeVoiceSession:tier="realtime",provider=self.active_provider,model=self._active_model,+ tool_calls=tuple(sorted(self._executed_tool_names)),))except Exception: # noqa: BLE001, S110@@ -473,6 +512,45 @@ class RealtimeVoiceSession:self._turn_id = ""self._last_user_text = ""self._output_transcript.clear()+ self._executed_tool_names.clear()++ async def _handle_tool_call(self, event: Any) -> None:+ if self._session is None:+ return+ call_id = str(getattr(event, "call_id", "") or "")+ wire_name = str(getattr(event, "tool_name", "") or "")+ arguments = getattr(event, "tool_args", None)+ if not isinstance(arguments, dict):+ arguments = {}+ if not call_id or not wire_name or self._tool_bridge is None:+ await self._session.send_tool_result(+ call_id,+ wire_name,+ {"success": False, "error": "Tool call is not available."},+ )+ return+ original_name, result = await self._tool_bridge.execute(+ wire_name=wire_name,+ arguments=arguments,+ )+ if result.get("success"):+ self._executed_tool_names.add(original_name)+ await self._session.send_tool_result(call_id, wire_name, result)++ async def _reject_untranscribed_tool_call(self, event: Any) -> None:+ if self._session is None:+ return+ await self._session.send_tool_result(+ str(getattr(event, "call_id", "") or ""),+ str(getattr(event, "tool_name", "") or ""),+ {+ "success": False,+ "error": (+ "The input transcript was unavailable, so the action was not "+ "executed. Ask the user to repeat the request."+ ),+ },+ )async def _emit_audio(self, chunk: Any) -> None:pcm = bytes(getattr(chunk, "pcm", b"") or b"")@@ -525,6 +603,11 @@ class RealtimeVoiceSession:await self._session.close()except Exception: # noqa: BLE001, S110 — best-effort teardownpass+ if self._tool_bridge is not None:+ try:+ await self._tool_bridge.close()+ except Exception: # noqa: BLE001, S110 — teardown is best-effort+ passif self._surface == "browser" and self._bus is not None:try:from jarvis.core.events import VoiceSessionEndeddiff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pynew file mode 100644index 0000000000..d7f8199401--- /dev/null+++ b/jarvis/realtime/tools.py@@ -0,0 +1,265 @@+"""Provider-neutral realtime tool declarations and safe execution bridge."""++from __future__ import annotations++import hashlib+import json+import re+from dataclasses import dataclass+from typing import Any+from uuid import UUID, uuid4++from jarvis.brain.tool_use_loop import (+ _is_instructional_question,+ _is_meta_debug_intent,+ _is_self_identification,+ _is_side_effect_tool,+ _is_stt_hallucinated,+ _should_block_action_as_research,+)+from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL+from jarvis.voice.echo_confirmation import classify_response+from jarvis.voice.tool_confirmation import format_tool_confirmation++_VALID_WIRE_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")+_MAX_DESCRIPTION_CHARS = 4_000+_MAX_ARGUMENT_CHARS = 32_000+_MAX_RESULT_CHARS = 8_000+++def _wire_name(name: str) -> str:+ """Return a deterministic identifier accepted by both provider families."""+ if _VALID_WIRE_NAME.fullmatch(name):+ return name+ normalized = re.sub(r"[^A-Za-z0-9_]", "_", name).strip("_") or "tool"+ if not normalized[0].isalpha() and normalized[0] != "_":+ normalized = f"tool_{normalized}"+ digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:10]+ return f"{normalized[:52]}_{digest}"+++def _json_safe(value: Any) -> Any:+ return json.loads(json.dumps(value, ensure_ascii=False, default=str))+++def _bounded_result(success: bool, output: Any, error: str | None) -> dict[str, Any]:+ payload = {+ "success": bool(success),+ "output": _json_safe(output),+ "error": str(error) if error else None,+ }+ serialized = json.dumps(payload, ensure_ascii=False, default=str)+ if len(serialized) <= _MAX_RESULT_CHARS:+ return payload+ return {+ "success": bool(success),+ "output": serialized[:_MAX_RESULT_CHARS],+ "error": (+ f"Tool output was truncated from {len(serialized)} characters "+ f"to {_MAX_RESULT_CHARS}."+ ),+ "truncated": True,+ }+++@dataclass(slots=True)+class _PendingConfirmation:+ trace_id: UUID+ tool_name: str+ confirmed: bool = False+++class RealtimeToolBridge:+ """Expose the live router tools and execute only through ``ToolExecutor``."""++ def __init__(self, *, tools: dict[str, Any], executor: Any, language: str) -> None:+ self._tools = dict(tools)+ self._executor = executor+ self._language = language+ self._wire_to_name: dict[str, str] = {}+ self._declarations: tuple[dict[str, Any], ...] = self._build_declarations()+ self._pending: _PendingConfirmation | None = None+ self._vetoed_tool = ""+ self._last_user_text = ""++ @classmethod+ def from_brain(cls, brain: Any, *, language: str) -> RealtimeToolBridge | None:+ tools = getattr(brain, "_tools", None)+ executor = getattr(brain, "_tool_executor_ref", None)+ if not isinstance(tools, dict) or not tools or executor is None:+ return None+ return cls(tools=tools, executor=executor, language=language)++ def _build_declarations(self) -> tuple[dict[str, Any], ...]:+ declarations: list[dict[str, Any]] = []+ for name, tool in sorted(self._tools.items()):+ schema = getattr(tool, "schema", None)+ if not isinstance(schema, dict):+ continue+ wire = _wire_name(str(name))+ if wire in self._wire_to_name:+ continue+ self._wire_to_name[wire] = str(name)+ declarations.append(+ {+ "name": wire,+ "description": str(getattr(tool, "description", ""))[+ :_MAX_DESCRIPTION_CHARS+ ],+ "parameters": schema,+ }+ )+ return tuple(declarations)++ @property+ def declarations(self) -> tuple[dict[str, Any], ...]:+ return self._declarations++ def set_language(self, language: str) -> None:+ self._language = language++ async def handle_user_transcript(self, text: str) -> None:+ self._last_user_text = text+ self._vetoed_tool = ""+ pending = self._pending+ if pending is None:+ return+ verdict = classify_response(text, language=self._language)+ if verdict == "confirm":+ pending.confirmed = True+ elif verdict == "veto":+ await self._executor.cancel_pending(pending.trace_id)+ self._vetoed_tool = pending.tool_name+ self._pending = None++ async def execute(+ self,+ *,+ wire_name: str,+ arguments: dict[str, Any],+ ) -> tuple[str, dict[str, Any]]:+ name = self._wire_to_name.get(wire_name, "")+ tool = self._tools.get(name)+ if tool is None:+ await self._publish_denied(wire_name, "unknown realtime tool")+ return wire_name, {+ "success": False,+ "error": "Tool is not available in this session.",+ }+ if self._vetoed_tool == name:+ return wire_name, {+ "success": False,+ "error": "The user declined this action. Do not ask again in this turn.",+ }+ validation_error = self._validate_arguments(tool, arguments)+ if validation_error:+ await self._publish_denied(name, validation_error)+ return name, {"success": False, "error": validation_error}++ guard_error = await self._guard(tool, name, arguments)+ if guard_error:+ return name, {"success": False, "error": guard_error}++ pending = self._pending+ if pending is not None and pending.tool_name == name:+ if not pending.confirmed:+ return name, {+ "success": False,+ "confirmation_required": True,+ "message": format_tool_confirmation(+ name, language=self._language+ ),+ }+ result = await self._executor.execute_confirmed(+ pending.trace_id,+ user_utterance=self._last_user_text,+ config_snapshot={"output_language": self._language},+ )+ self._pending = None+ return name, _bounded_result(+ bool(getattr(result, "success", False)),+ getattr(result, "output", None),+ getattr(result, "error", None),+ )++ trace_id = uuid4()+ result = await self._executor.execute(+ tool,+ arguments,+ user_utterance=self._last_user_text,+ config_snapshot={+ "output_language": self._language,+ "voice_confirm": True,+ },+ trace_id=trace_id,+ rationale="Realtime model requested an available Jarvis tool.",+ )+ if (+ getattr(result, "error", None) == VOICE_CONFIRM_SENTINEL+ and isinstance(getattr(result, "output", None), dict)+ ):+ self._pending = _PendingConfirmation(trace_id=trace_id, tool_name=name)+ return name, {+ "success": False,+ "confirmation_required": True,+ "message": format_tool_confirmation(name, language=self._language),+ "instruction": (+ "Ask the user this question. Call the same function again only "+ "after a clear affirmative answer."+ ),+ }+ return name, _bounded_result(+ bool(getattr(result, "success", False)),+ getattr(result, "output", None),+ getattr(result, "error", None),+ )++ def _validate_arguments(self, tool: Any, arguments: Any) -> str:+ if not isinstance(arguments, dict):+ return "Tool arguments must be a JSON object."+ try:+ size = len(json.dumps(arguments, ensure_ascii=False, default=str))+ except Exception: # noqa: BLE001+ return "Tool arguments are not JSON serializable."+ if size > _MAX_ARGUMENT_CHARS:+ return f"Tool arguments exceed the {_MAX_ARGUMENT_CHARS}-character limit."+ schema = getattr(tool, "schema", None) or {}+ required = schema.get("required", ()) if isinstance(schema, dict) else ()+ missing = [key for key in required if key not in arguments]+ if missing:+ return f"Missing required tool arguments: {', '.join(map(str, missing))}."+ return ""++ async def _guard(self, tool: Any, name: str, arguments: dict[str, Any]) -> str:+ user_text = self._last_user_text+ blocked, reason = _is_stt_hallucinated(name, arguments)+ if blocked:+ message = f"Suspected speech-recognition argument error: {reason}"+ elif _is_instructional_question(user_text) and _is_side_effect_tool(tool):+ message = "The user asked for instructions; the side-effect tool was not run."+ elif _is_self_identification(user_text) and _is_side_effect_tool(tool):+ message = "The user was introducing themselves; the side-effect tool was not run."+ elif name == "spawn_worker" and _is_meta_debug_intent(user_text):+ message = "A meta/debug request must be answered directly, not delegated."+ elif _should_block_action_as_research(tool, name, user_text, None, ""):+ message = "This sounds like research, not an action on a connected system."+ else:+ return ""+ await self._publish_denied(name, message)+ return message++ async def _publish_denied(self, name: str, reason: str) -> None:+ publisher = getattr(self._executor, "publish_guard_denied", None)+ if callable(publisher):+ try:+ await publisher(name, reason, trace_id=uuid4())+ except Exception: # noqa: BLE001, S110 — observability cannot break safety+ pass++ async def close(self) -> None:+ if self._pending is not None:+ await self._executor.cancel_pending(self._pending.trace_id)+ self._pending = None+++__all__ = ["RealtimeToolBridge"]diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 11ea180a89..9c3e40ef25 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -5074,6 +5074,7 @@ class SpeechPipeline:send_json=_send_json,half_duplex=True,surface="desktop",+ brain=getattr(self, "_brain", None),)if session is None:return Nonediff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.pyindex af0f8f4cb6..2a1d2bfb8e 100644--- a/jarvis/ui/jarvisbar/overlay.py+++ b/jarvis/ui/jarvisbar/overlay.py@@ -97,13 +97,17 @@ FRAME_STALL_THRESHOLD_NS = 2_000_000_000 # 2 s of silence ⇒ the loop is dead# occasional slow render (measured up to ~30ms in "think"+hovered mode)# from compounding into an even longer visible gap.#-# Idle-static skip: once the resting pill's eased size has stopped changing-# (ease() with factor 0.5 converges to sub-pixel precision within a handful-# of ticks; 30 is a generous margin) AND the state is idle/not-hovered/-# not-muted (draws nothing — see renderer.render), every further tick would-# repaint the exact same pixels. Skipped ticks still stamp the heartbeat and-# re-arm the loop, so the watchdog/self-healing contract is untouched — only-# the render()/PhotoImage()/itemconfig() work is skipped.+# Idle-static skip: EVERY branch renderer.render() can reach while the coarse+# mode is "idle" is time-independent (the empty resting pill, the hovered+# idle pill's static mic glyph, the muted idle pill's static mic glyph — the+# equalizer bars and the close-X both require an active/listen/speak/think+# mode, never reached while idle). So once the resting pill's eased size has+# stopped changing (ease() with factor 0.5 converges to sub-pixel precision+# within a handful of ticks; 30 is a generous margin) for a given+# (hover, mute) combination, every further tick would repaint the exact same+# pixels regardless of hover/mute. Skipped ticks still stamp the heartbeat+# and re-arm the loop, so the watchdog/self-healing contract is untouched —+# only the render()/PhotoImage()/itemconfig() work is skipped._IDLE_SETTLE_TICKS = 30# Adaptive pacing: the nominal target stays 16ms (~60fps aspirational — the@@ -561,13 +565,21 @@ class JarvisBarOverlay:playback_active=playing,)- # Idle-static skip (see _IDLE_SETTLE_TICKS docstring above): once the- # resting pill has been idle/not-hovered/not-muted for enough- # consecutive ticks that its eased size has fully settled, every- # further tick would repaint the exact same pixels — skip the- # render/PhotoImage/itemconfig work entirely. Any change in mode,- # hover, or mute resets the counter, so a real transition always- # renders immediately.+ # Idle-static skip (see _IDLE_SETTLE_TICKS docstring above): every+ # branch renderer.render() can reach while ``effective_mode ==+ # "idle"`` is time-INDEPENDENT — the empty resting pill, the+ # hovered idle pill (only draws the static mic glyph; the close-X+ # and equalizer bars require an active/listen/speak mode, never+ # reached here), and the muted idle pill (same static mic glyph)+ # all draw nothing that depends on ``t``. The only thing that+ # still moves per tick is the eased pill size/color, which+ # converges (ease() factor 0.5) well within _IDLE_SETTLE_TICKS+ # ticks of any (hover, mute) combination changing. So once idle+ # has been static for that long, EVERY further tick — hovered or+ # muted or neither — would repaint byte-identical pixels; skip+ # the render/PhotoImage/itemconfig work entirely. Any change in+ # mode, hover, or mute resets the counter, so a real transition+ # (including a hover/mute flip) always renders immediately.tick_key = (effective_mode, self._hovered, self._muted)if tick_key != self._static_tick_key:self._static_tick_key = tick_key@@ -576,8 +588,6 @@ class JarvisBarOverlay:self._static_tick_count += 1is_settled_idle = (effective_mode == "idle"- and not self._hovered- and not self._mutedand self._static_tick_count >= _IDLE_SETTLE_TICKS)diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.section-health.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.section-health.test.tsxindex b8647a4283..24e45a5575 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.section-health.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.section-health.test.tsx@@ -47,8 +47,8 @@ afterEach(() => {describe("Sidebar — API-Keys alert dot", () => {it("shows a red alert dot on API Keys when a section reports error", () => {mockHealth = {- brain: { status: "error", reason: "rate_limited", detail: "OpenRouter: rate limited" },- tts: { status: "ok", reason: "ok", detail: "" },+ brain: { status: "error", reason: "rate_limited", detail: "OpenRouter: rate limited", subject_id: "openrouter" },+ tts: { status: "ok", reason: "ok", detail: "", subject_id: "gemini-flash-tts" },};render(<Sidebar />);const dot = screen.getByTestId("nav-alert-apikeys");@@ -58,9 +58,9 @@ describe("Sidebar — API-Keys alert dot", () => {it("stays calm (no dot) when nothing is broken", () => {mockHealth = {- brain: { status: "needs_setup", reason: "not_configured", detail: "" },- tts: { status: "ok", reason: "ok", detail: "" },- stt: { status: "unknown", reason: "unknown", detail: "" },+ brain: { status: "needs_setup", reason: "not_configured", detail: "", subject_id: "openrouter" },+ tts: { status: "ok", reason: "ok", detail: "", subject_id: "gemini-flash-tts" },+ stt: { status: "unknown", reason: "unknown", detail: "", subject_id: "groq-api" },};render(<Sidebar />);expect(screen.queryByTestId("nav-alert-apikeys")).toBeNull();diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.section-health.test.tsx b/jarvis/ui/web/frontend/src/hooks/useProviders.section-health.test.tsxnew file mode 100644index 0000000000..9dbeeec44f--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.section-health.test.tsx@@ -0,0 +1,170 @@+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ sectionHealthForSubject,+ sectionHealthFromProviderTest,+ type ProviderTestResult,+ type SectionHealth,+ type SectionHealthResponse,+ useSectionHealth,+} from "./useProviders";++function jsonResponse(body: unknown): Response {+ return {+ ok: true,+ status: 200,+ json: async () => body,+ } as Response;+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++function responseFor(health: SectionHealth): SectionHealthResponse {+ return {+ sections: { brain: health },+ checked_at: 1,+ cached: false,+ };+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("provider-bound section health", () => {+ it.each([+ "gemini",+ "openrouter",+ "openrouter-tts",+ "groq-api",+ "openai-realtime",+ "gemini-live",+ "codex",+ "telephony",+ ])("accepts %s only for that exact subject", (subjectId) => {+ const health: SectionHealth = {+ status: "error",+ reason: "timeout",+ detail: `${subjectId}: timeout`,+ subject_id: subjectId,+ };++ expect(sectionHealthForSubject(health, subjectId)).toBe(health);+ expect(sectionHealthForSubject(health, `${subjectId}-replacement`)).toBeUndefined();+ });++ it.each([+ ["ok", "ok"],+ ["not_configured", "needs_setup"],+ ["bad_key", "error"],+ ["no_credits", "error"],+ ["rate_limited", "error"],+ ["model_unavailable", "error"],+ ["unreachable", "error"],+ ["error", "error"],+ ] as const)("maps a manual %s result to %s", (providerStatus, sectionStatus) => {+ const result: ProviderTestResult = {+ provider: "openrouter",+ status: providerStatus,+ detail: "probe result",+ latency_ms: 10,+ integration_ok: providerStatus !== "unreachable" && providerStatus !== "error",+ };++ expect(sectionHealthFromProviderTest(result, "OpenRouter")).toMatchObject({+ status: sectionStatus,+ reason: providerStatus,+ subject_id: "openrouter",+ });+ });++ it("keeps a fresh OpenRouter test when an older NVIDIA request finishes later", async () => {+ const oldRequest = deferred<Response>();+ const fetchMock = vi+ .fn()+ .mockImplementationOnce(() => oldRequest.promise)+ .mockImplementation(() => new Promise<Response>(() => undefined));+ vi.stubGlobal("fetch", fetchMock);+ const { result } = renderHook(() => useSectionHealth());+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));++ act(() => {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-tested", {+ detail: {+ section: "brain",+ provider: "openrouter",+ provider_label: "OpenRouter",+ active: true,+ result: {+ provider: "openrouter",+ status: "ok",+ detail: "working",+ latency_ms: 25,+ integration_ok: true,+ },+ },+ }),+ );+ });+ expect(result.current.health.brain).toMatchObject({+ status: "ok",+ subject_id: "openrouter",+ });++ await act(async () => {+ oldRequest.resolve(+ jsonResponse(+ responseFor({+ status: "error",+ reason: "timeout",+ detail: "NVIDIA NIM: timeout after 60.0s",+ subject_id: "nvidia",+ }),+ ),+ );+ await Promise.resolve();+ });++ expect(result.current.health.brain).toMatchObject({+ status: "ok",+ subject_id: "openrouter",+ });+ });++ it("clears the old result immediately while a provider switch is pending", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ jsonResponse(+ responseFor({+ status: "error",+ reason: "timeout",+ detail: "NVIDIA NIM: timeout after 60.0s",+ subject_id: "nvidia",+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const { result } = renderHook(() => useSectionHealth());+ await waitFor(() => expect(result.current.health.brain?.subject_id).toBe("nvidia"));++ act(() => {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", {+ detail: { section: "brain", provider: "openrouter" },+ }),+ );+ });++ expect(result.current.health.brain).toBeUndefined();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex a623f952ed..3eb1f1decd 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -299,17 +299,18 @@ export function useSectionHealth() {const detail = (event as CustomEvent<ProviderHealthEventDetail>).detail;const section = detail?.section ?? SECTION_HEALTH_EVENT_SECTIONS[event.type];+ const testResult = detail?.result;if (event.type === "jarvis:provider-tested" &&detail?.active &&- detail.result &&+ testResult &§ion) {setHealth((previous) => ({...previous,[section]: sectionHealthFromProviderTest(- detail.result as ProviderTestResult,- detail.provider_label ?? detail.result.provider,+ testResult,+ detail.provider_label ?? testResult.provider,),}));} else if (event.type !== "jarvis:provider-tested") {diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.pyindex 5b3720ca6f..c70e4d59c0 100644--- a/tests/integration/test_provider_routes.py+++ b/tests/integration/test_provider_routes.py@@ -180,8 +180,9 @@ def test_section_health_returns_all_tabs(assert sec["status"] in validassert body["cached"] is Falseassert body["sections"]["brain"]["subject_id"] == "openai"+ computer_use_cfg = getattr(server_with_brain.cfg.brain, "computer_use", None)expected_cu = (- server_with_brain.cfg.brain.computer_use.provider+ getattr(computer_use_cfg, "provider", None)or server_with_brain.cfg.brain.primary)assert body["sections"]["computer-use"]["subject_id"] == expected_cudiff --git a/tests/unit/ui/jarvisbar/test_frame_pacing.py b/tests/unit/ui/jarvisbar/test_frame_pacing.pyindex 145827cb55..a87111e642 100644--- a/tests/unit/ui/jarvisbar/test_frame_pacing.py+++ b/tests/unit/ui/jarvisbar/test_frame_pacing.py@@ -4,11 +4,15 @@ A 41s GIF capture of the bar frame-diffed to only ~5 visual updates/second onaverage, in a burst-then-freeze pattern. Measured root causes (see theconstants' docstrings in ``overlay.py``):-1. The idle pill draws nothing beyond its at-rest background once its eased- size has settled, so re-rendering + re-blitting it every tick was pure- waste — a real per-tick Windows DWM compositing cost paid for a+1. Every branch ``renderer.render()`` can reach while the coarse mode is+ "idle" is time-independent (empty resting pill / hovered idle pill's+ static mic glyph / muted idle pill's static mic glyph — the equalizer+ bars and the close-X both require an active/listen/speak/think mode). So+ once its eased size has settled, re-rendering + re-blitting it every tick+ was pure waste — a real per-tick Windows DWM compositing cost paid for abyte-identical image. ``_schedule_frame`` now skips the render/PhotoImage/- itemconfig work once idle has visibly settled (``_IDLE_SETTLE_TICKS``).+ itemconfig work once idle has visibly settled (``_IDLE_SETTLE_TICKS``),+ regardless of hover/mute.2. The re-arm delay is now adaptive (derived from actual tick cost via``TARGET_FRAME_MS``/``MIN_FRAME_DELAY_MS``) instead of a blind constant, soan unusually slow render can't compound into an even longer visible gap.@@ -21,9 +25,9 @@ from __future__ import annotationsimport pytestfrom jarvis.ui.jarvisbar.overlay import (+ _IDLE_SETTLE_TICKS,MIN_FRAME_DELAY_MS,TARGET_FRAME_MS,- _IDLE_SETTLE_TICKS,JarvisBarOverlay,)@@ -73,7 +77,9 @@ class _CountingRenderer:return "sentinel-image"-def _bare_bar(renderer_obj: object, *, mode: str = "idle") -> tuple[JarvisBarOverlay, _FakeRoot, _FakeCanvas]:+def _bare_bar(+ renderer_obj: object, *, mode: str = "idle"+) -> tuple[JarvisBarOverlay, _FakeRoot, _FakeCanvas]:bar = JarvisBarOverlay.__new__(JarvisBarOverlay)bar._running = Truebar._mode = mode@@ -157,19 +163,47 @@ def test_mode_change_resets_the_idle_settle_counter_and_renders_immediately():)-def test_hover_prevents_the_idle_skip():- """A hovered idle pill shows controls (mic glyph) and must keep rendering- even though the coarse mode is 'idle' — only a truly at-rest, uninteracted- pill may be skipped."""+def test_hovered_idle_pill_also_settles_and_skips():+ """A hovered idle pill only ever draws the static mic glyph (the close-X+ and equalizer bars require an active/listen/speak mode, unreachable while+ ``effective_mode == "idle"``) — so it is just as time-independent as the+ empty resting pill once its (larger, OPEN-sized) eased pill has settled,+ and must also stop repainting."""renderer_obj = _CountingRenderer()- bar, _root, _canvas = _bare_bar(renderer_obj, mode="idle")+ bar, _root, canvas = _bare_bar(renderer_obj, mode="idle")bar._hovered = True+ for _ in range(_IDLE_SETTLE_TICKS):+ bar._schedule_frame()+ calls_before = renderer_obj.calls+ itemconfig_before = canvas.itemconfig_calls++ for _ in range(10):+ bar._schedule_frame()++ assert renderer_obj.calls == calls_before, (+ "a settled hovered-idle pill kept calling render() — the static mic "+ "glyph never changes once the pill size has settled"+ )+ assert canvas.itemconfig_calls == itemconfig_before+++def test_hover_flip_while_idle_forces_an_immediate_render():+ """A hover state CHANGE (mouse entering/leaving a settled idle pill) must+ always render on the very next tick — the skip must never delay a real+ interaction cue (showing/hiding the mic glyph) from appearing."""+ renderer_obj = _CountingRenderer()+ bar, _root, _canvas = _bare_bar(renderer_obj, mode="idle")+for _ in range(_IDLE_SETTLE_TICKS + 5):bar._schedule_frame()+ calls_while_settled = renderer_obj.calls- assert renderer_obj.calls == _IDLE_SETTLE_TICKS + 5, (- "a hovered idle pill was skipped despite showing live controls"+ bar._hovered = True+ bar._schedule_frame()++ assert renderer_obj.calls == calls_while_settled + 1, (+ "a hover flip on a settled idle pill did not render on the next tick")