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-06-30 13:53)
Ruben Lütke2de6a483c597
diff --git a/jarvis/mcp/client.py b/jarvis/mcp/client.pyindex fc6b2c1c80..675e1ddfce 100644--- a/jarvis/mcp/client.py+++ b/jarvis/mcp/client.py@@ -12,7 +12,9 @@ be held for the entire lifetime of the client."""from __future__ import annotations+import asyncioimport logging+import osimport reimport timefrom contextlib import AsyncExitStack@@ -29,6 +31,34 @@ log = logging.getLogger(__name__)_CB_THRESHOLD = 3_CB_COOLDOWN_NS = 60_000_000_000 # 60 seconds++def _read_call_timeout_s() -> float:+ """Per-call timeout (seconds), ENV-overridable with a safe fallback.++ Default 20 s. Rationale: a hung MCP server must NOT block the whole voice+ turn (~35 s hangs were observed), but the ceiling must not guillotine+ legitimately slower tools — a remote http MCP doing real network I/O+ (search, a DB query, a web fetch) can take well over 5-10 s. 20 s sits+ comfortably above normal tool latency yet still trips long before a voice+ turn feels dead, and a repeatedly-slow server tips into the circuit+ breaker (3 strikes) and drops off the surface on its own. Tunable per host+ via ``JARVIS_MCP_CALL_TIMEOUT_S`` (a headless VPS with a slow uvx cold+ start can raise it) without code or config edits.+ """+ raw = os.environ.get("JARVIS_MCP_CALL_TIMEOUT_S")+ if raw:+ try:+ val = float(raw)+ if val > 0:+ return val+ except ValueError:+ log.warning("JARVIS_MCP_CALL_TIMEOUT_S=%r is not a number; using 20s", raw)+ return 20.0+++# Module-level so a test can monkeypatch it and call_tool re-reads it each call.+_CALL_TIMEOUT_S = _read_call_timeout_s()+# Matches ``$NAME`` secret placeholders inside http header values, e.g.# ``"Bearer $ZAPIER_TOKEN"`` → the ``ZAPIER_TOKEN`` group._SECRET_TOKEN_RE = re.compile(r"\$([A-Z_][A-Z0-9_]*)")@@ -145,7 +175,26 @@ class MCPClient:raise RuntimeError(f"{self.spec.name}: MCPClient not started")try:- result = await self._session.call_tool(name, args)+ # Per-call timeout: the MCP SDK has no built-in ceiling, so a server+ # that hangs on a tool call would block the whole turn forever. We+ # bound it here and RAISE on expiry; the raise falls into the+ # ``except Exception`` below, which counts the failure — so a+ # repeatedly-hung server trips the circuit breaker and drops from the+ # surface instead of hanging every future turn. We re-read the module+ # global each call so the ENV override / a test monkeypatch applies.+ timeout_s = _CALL_TIMEOUT_S+ try:+ result = await asyncio.wait_for(+ self._session.call_tool(name, args),+ timeout=timeout_s,+ )+ except TimeoutError as exc:+ # Clean, honest message so the brain's tool loop surfaces it and+ # the voice layer can speak its timeout phrase — not a bare crash.+ raise RuntimeError(+ f"{self.spec.name} tool {name!r} timed out after "+ f"{timeout_s:.0f}s (server not responding)"+ ) from exc# MCP-SDK quirk: server-side tool exceptions do NOT propagate as# Python exceptions; instead they arrive as a CallToolResult with# isError=True. The circuit breaker counts this as a failure.diff --git a/jarvis/mcp/registry.py b/jarvis/mcp/registry.pyindex 897bb45290..60298a3c4a 100644--- a/jarvis/mcp/registry.py+++ b/jarvis/mcp/registry.py@@ -18,6 +18,12 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)+# Per-server start ceiling (seconds). A server that hangs on initialize /+# list_tools must not hang its start task forever — mirrors the 60 s guard in+# ``bootstrap.verify_server``. On expiry we log per-server and move on; the+# parallel start of the other servers is never aborted.+_START_TIMEOUT_S = 60.0+# ----------------------------------------------------------------------# Spec@@ -164,10 +170,20 @@ class MCPRegistry:env_overrides = _env_from_mcp_json(spec.name)client = MCPClient(spec, env_overrides=env_overrides)try:- await client.start()+ # Per-server start timeout: a server hanging on initialize /+ # list_tools must not block this task forever. asyncio.wait_for+ # cancels the hung start on expiry and raises TimeoutError, which+ # the ``except`` below records per server — the gather over the+ # other servers keeps running, so one hung server never stalls+ # the parallel boot.+ await asyncio.wait_for(client.start(), timeout=_START_TIMEOUT_S)self._clients[spec.name] = clientself._errors.pop(spec.name, None)log.info("MCP-Server %s gestartet", spec.name)+ except TimeoutError:+ error_msg = f"start timeout ({_START_TIMEOUT_S:.0f}s)"+ self._errors[spec.name] = error_msg+ log.error("MCP-Server %s Startfehler: %s", spec.name, error_msg)except Exception as e: # noqa: BLE001error_msg = f"{type(e).__name__}: {e}"self._errors[spec.name] = error_msgdiff --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.tsxnew file mode 100644index 0000000000..b8647a4283--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.section-health.test.tsx@@ -0,0 +1,74 @@+/**+ * Sidebar API-Keys alert dot.+ *+ * The API-Keys tab dots already say "this section is broken" once you are on the+ * page. The sidebar drills that one level up: a red dot on the "API Keys" nav row+ * makes a set-up-but-failing provider visible from anywhere in the app. Only a+ * hard "error" lights it — the amber "needs_setup" state stays off the bar so a+ * fresh install isn't permanently flagged.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";++import type { SectionHealth } from "@/hooks/useProviders";++let mockHealth: Record<string, SectionHealth> = {};++vi.mock("@/hooks/useVoiceReadiness", () => ({+ useVoiceReadiness: () => ({+ connected: true,+ voiceWarming: false,+ bootWarming: false,+ warming: false,+ }),+}));++vi.mock("@/hooks/useProviders", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/hooks/useProviders")>();+ return {+ ...actual,+ useSectionHealth: () => ({ health: mockHealth, reload: vi.fn() }),+ };+});++import { Sidebar } from "@/components/layout/Sidebar";+import { useEventStore } from "@/store/events";++beforeEach(() => {+ mockHealth = {};+ useEventStore.setState({ activeSection: "chats" });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++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: "" },+ };+ render(<Sidebar />);+ const dot = screen.getByTestId("nav-alert-apikeys");+ expect(dot).toBeTruthy();+ expect(dot.className).toMatch(/bg-destructive/);+ });++ 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: "" },+ };+ render(<Sidebar />);+ expect(screen.queryByTestId("nav-alert-apikeys")).toBeNull();+ });++ it("stays calm when health hasn't loaded yet (empty map)", () => {+ mockHealth = {};+ render(<Sidebar />);+ expect(screen.queryByTestId("nav-alert-apikeys")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 3dbc896e4d..369ec498a1 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -287,12 +287,19 @@ function NavRow({label,active,badge,+ alert = false,+ alertTitle,onClick,}: {item: NavItem;label: string;active: boolean;badge?: number;+ /** Draw a red status dot on the row — a section this row fronts has a provider+ * that is set up but failing, so the problem is visible app-wide. */+ alert?: boolean;+ /** Plain-language hover text for the alert dot. */+ alertTitle?: string;onClick: () => void;}) {const Icon = item.icon;@@ -301,6 +308,7 @@ function NavRow({<buttontype="button"onClick={onClick}+ title={alert ? alertTitle : undefined}className={cn("group relative flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm transition-all","hover:bg-background/60",@@ -316,6 +324,14 @@ function NavRow({)}/><span className="flex-1 text-left">{label}</span>+ {alert && (+ <span+ data-testid={`nav-alert-${item.id}`}+ role="status"+ aria-label={alertTitle}+ className="h-2 w-2 shrink-0 rounded-full bg-destructive ring-2 ring-background"+ />+ )}{badge !== undefined && badge > 0 && (<span className="rounded-full bg-primary/20 px-1.5 py-0.5 text-[10px] font-semibold text-primary">{badge}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex f344f9cdf4..462efd6ba6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -165,7 +165,8 @@"sidebar": {"wake_hint": "Sag dein Wake-Word…","brain_label": "Brain",- "brain_tooltip": "Brain-Provider wechseln"+ "brain_tooltip": "Brain-Provider wechseln",+ "apikeys_alert": "Ein Anbieter ist eingerichtet, funktioniert aber nicht — zum Beheben API Keys öffnen"},"chats_view": {"title": "Chat",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 637d50dde9..940c028b6f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -165,7 +165,8 @@"sidebar": {"wake_hint": "Say your wake word…","brain_label": "Brain",- "brain_tooltip": "Switch brain provider"+ "brain_tooltip": "Switch brain provider",+ "apikeys_alert": "A provider is set up but not working — open API Keys to fix it"},"chats_view": {"title": "Chat",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 0f1ea2c8fc..d6f22abc10 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -165,7 +165,8 @@"sidebar": {"wake_hint": "Di tu palabra de activación…","brain_label": "Cerebro",- "brain_tooltip": "Cambiar proveedor de IA"+ "brain_tooltip": "Cambiar proveedor de IA",+ "apikeys_alert": "Un proveedor está configurado pero no funciona — abre API Keys para solucionarlo"},"chats_view": {"title": "Chat",diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsxindex 69942507a7..707318a027 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx@@ -70,6 +70,56 @@ afterEach(() => {vi.restoreAllMocks();});+// A single active, configured brain provider whose live check is failing — the+// shape the card-level indicator must drill the tab's red dot down onto.+const BROKEN_BRAIN_PROVIDER = {+ id: "openrouter",+ label: "OpenRouter",+ tier: "brain",+ auth_mode: "api_key",+ secret_keys: ["OPENROUTER_API_KEY"],+ secrets_set: { OPENROUTER_API_KEY: true },+ dashboard_url: null,+ login_cli: null,+ install_hint: null,+ credential_path_hint: null,+ configured: true,+ active: true,+ brain_switchable: true,+ cli_installed: null,+ credential_help: null,+ signup_url: null,+ billing: "api",+ alt_credential: null,+};++const SECTION_HEALTH_BRAIN_ERROR = {+ sections: {+ brain: { status: "error", reason: "rate_limited", detail: "OpenRouter: rate limited" },+ tts: { status: "ok", reason: "ok", detail: "Gemini Flash: ok" },+ stt: { status: "ok", reason: "ok", detail: "faster-whisper: local" },+ subagents: { status: "unknown", reason: "unknown", detail: "" },+ advanced: { status: "unknown", reason: "unknown", detail: "" },+ },+ checked_at: 0,+ cached: false,+};++// Routes for a fully-rendered brain card: the active card mounts the model + CU+// pickers, which fetch their own catalogs on mount.+function cardRoutes() {+ return baseRoutes({+ "/api/providers/section-health": () => ({ body: SECTION_HEALTH_BRAIN_ERROR }),+ "/api/providers/openrouter/models": () => ({+ body: { provider: "openrouter", current_model: "", models: [], source: "static", fetched_at: 0, selects: "model" },+ }),+ "/api/providers/openrouter/cu-model": () => ({+ body: { provider: "openrouter", cu_model: "", effective_model: "auto", uses_main: true },+ }),+ "/api/providers": () => ({ body: { providers: [BROKEN_BRAIN_PROVIDER] } }),+ });+}+describe("ApiKeysView — section-health tab indicators", () => {it("marks a not-set-up tab amber ('Setup needed')", async () => {installFetchMock(baseRoutes());@@ -96,4 +146,35 @@ describe("ApiKeysView — section-health tab indicators", () => {const ttsTab = screen.getByRole("tab", { name: /^Voice Output$/i });expect(ttsTab.getAttribute("title")).toBeNull();});++ it("drills the error onto the exact failing card with the cause in plain text", async () => {+ installFetchMock(cardRoutes());+ render(<ApiKeysView />);+ // The active OpenRouter card surfaces an inline error banner naming the cause,+ // so the user sees WHICH provider broke and WHY — not just the tab's red dot.+ const banner = await waitFor(() =>+ screen.getByTestId("provider-health-error-openrouter"),+ );+ expect(banner.textContent).toMatch(/Not working/i);+ expect(banner.textContent).toMatch(/rate limited/i);+ });++ it("does not mark a card red when its provider is healthy", async () => {+ installFetchMock(+ baseRoutes({+ "/api/providers/section-health": () => ({ body: SECTION_HEALTH }),+ "/api/providers/openrouter/models": () => ({+ body: { provider: "openrouter", current_model: "", models: [], source: "static", fetched_at: 0, selects: "model" },+ }),+ "/api/providers/openrouter/cu-model": () => ({+ body: { provider: "openrouter", cu_model: "", effective_model: "auto", uses_main: true },+ }),+ // brain is "needs_setup" in SECTION_HEALTH, never "error" → no card banner.+ "/api/providers": () => ({ body: { providers: [BROKEN_BRAIN_PROVIDER] } }),+ }),+ );+ render(<ApiKeysView />);+ await waitFor(() => screen.getByRole("tab", { name: /Brain/i }));+ expect(screen.queryByTestId("provider-health-error-openrouter")).toBeNull();+ });});diff --git a/tests/integration/mcp/test_mcp_client_timeout.py b/tests/integration/mcp/test_mcp_client_timeout.pynew file mode 100644index 0000000000..c11954b3d7--- /dev/null+++ b/tests/integration/mcp/test_mcp_client_timeout.py@@ -0,0 +1,151 @@+"""Per-call and per-start timeout guards for the MCP layer.++A user MCP tool call can hang and block the whole voice turn because there is+no per-call timeout in the chain (tool_use_loop -> tool_executor -> adapter ->+``MCPClient.call_tool``). The circuit breaker only counted COMPLETED failures,+so a true HANG never tripped it. These tests pin two guards:++1. ``MCPClient.call_tool`` wraps the SDK call in a per-call timeout that RAISES+ on expiry; the raise lands in the existing breaker-counting ``except`` so a+ repeatedly-hung server auto-opens the circuit breaker after the threshold.+2. ``MCPRegistry`` starts each server under a per-start timeout (mirroring+ ``bootstrap.verify_server``); a server hanging on ``initialize``/``list_tools``+ is given up on without hanging the start task forever or killing siblings.++We inject fakes whose ``call_tool``/``start`` await forever, then shrink the+timeout constants via monkeypatch so the tests stay fast and deterministic+(no subprocess, no real network).+"""+from __future__ import annotations++import asyncio++import pytest++import jarvis.mcp.client as client_mod+import jarvis.mcp.registry as registry_mod+from jarvis.mcp.client import MCPClient+from jarvis.mcp.registry import MCPRegistry, MCPServerSpec+++def _spec(name: str = "hang-mcp") -> MCPServerSpec:+ return MCPServerSpec(+ name=name,+ display="Hang MCP",+ description="test-only",+ install_command=["python", "-m", "noop"],+ )+++class _HangingSession:+ """Stand-in MCP ClientSession whose call_tool never returns."""++ def __init__(self) -> None:+ self.calls = 0++ async def call_tool(self, name: str, args: dict) -> object: # noqa: ANN401+ self.calls += 1+ await asyncio.sleep(3600) # effectively forever -> simulates a hang+ raise AssertionError("unreachable") # pragma: no cover+++# ----------------------------------------------------------------------+# 1. Per-call timeout+# ----------------------------------------------------------------------++async def test_hung_call_tool_raises_after_timeout_and_counts_failure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Shrink the per-call timeout so the hang is cut almost immediately.+ monkeypatch.setattr(client_mod, "_CALL_TIMEOUT_S", 0.05, raising=False)++ client = MCPClient(_spec())+ client._session = _HangingSession() # inject without a real transport++ with pytest.raises(RuntimeError) as excinfo:+ await client.call_tool("slow_tool", {"x": 1})++ # The error must be honest/clean (mentions a timeout), not a bare crash.+ assert "timeout" in str(excinfo.value).lower() or "timed out" in str(+ excinfo.value+ ).lower()+ # A hang must be COUNTED as a failure so the breaker can eventually open.+ assert client._circuit_breaker_failures == 1+++async def test_repeated_hangs_open_the_circuit_breaker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(client_mod, "_CALL_TIMEOUT_S", 0.05, raising=False)++ client = MCPClient(_spec())+ session = _HangingSession()+ client._session = session++ # Threshold consecutive hangs must trip the breaker.+ for _ in range(client_mod._CB_THRESHOLD):+ with pytest.raises(RuntimeError):+ await client.call_tool("slow_tool", {})++ assert client.is_healthy is False+ # Once open, further calls are rejected WITHOUT even touching the session+ # (no new hang, no extra wait).+ calls_before = session.calls+ with pytest.raises(RuntimeError, match="circuit-breaker"):+ await client.call_tool("slow_tool", {})+ assert session.calls == calls_before+++# ----------------------------------------------------------------------+# 2. Per-start timeout (registry)+# ----------------------------------------------------------------------++class _FakeClient:+ """Registry-level stand-in: ``hang`` blocks forever in start(), ``ok`` is fine."""++ instances: list[_FakeClient] = []++ def __init__(self, spec: MCPServerSpec, env_overrides=None) -> None: # noqa: ANN001+ self.spec = spec+ self.started = False+ self.stopped = False+ _FakeClient.instances.append(self)++ async def start(self) -> None:+ if self.spec.name == "hang":+ await asyncio.sleep(3600) # hang on initialize/list_tools+ self.started = True++ async def stop(self) -> None:+ self.stopped = True+++async def test_start_one_gives_up_after_timeout_without_killing_siblings(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _FakeClient.instances.clear()+ # Shrink the per-start timeout; patch the client class the local import picks up.+ monkeypatch.setattr(registry_mod, "_START_TIMEOUT_S", 0.05, raising=False)+ monkeypatch.setattr(client_mod, "MCPClient", _FakeClient)+ # Avoid touching mcp.json on disk.+ monkeypatch.setattr(registry_mod, "_env_from_mcp_json", lambda _name: None)++ reg = MCPRegistry()+ reg.register_spec(_spec("hang"))+ reg.register_spec(_spec("ok"))++ # Must RETURN promptly even though "hang" blocks forever.+ await asyncio.wait_for(reg.start_enabled(["hang", "ok"]), timeout=5)++ active = reg.active_clients()+ # The healthy sibling came up...+ assert "ok" in active+ assert active["ok"].started is True+ # ...while the hung server was given up on and recorded as an error.+ assert "hang" not in active+ err = reg.last_error("hang")+ assert err is not None+ assert "timeout" in err.lower() or "timed out" in err.lower()