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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 19:00)

Ruben Lütke0ce36bd5aeeb
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index a46060cdb0..43c6c272a5 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -1081,6 +1081,18 @@ class ModelCatalog:
client = await self._client()
async with client:
resp = await client.get(url, headers=headers, params=params)
+ # ``bearer_opt`` endpoints are public. A stale/revoked optional key
+ # must not hide the live model roster from the picker: retry once
+ # anonymously on an authentication/permission rejection. Inference
+ # still uses and validates the credential normally; this fallback is
+ # scoped only to public catalog discovery.
+ if auth == "bearer_opt" and headers and resp.status_code in (401, 403):
+ log.info(
+ "Optional credential rejected by the public %s model catalog; "
+ "retrying anonymously.",
+ provider,
+ )
+ resp = await client.get(url, params=params)
resp.raise_for_status()
return parse_models_response(provider, resp.json())
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index ea12ad7772..bae444031e 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2592,6 +2592,53 @@ def _ensure_keyring_backend() -> None:
pass
+def _try_restore_platform_keyring_backend() -> bool:
+ """Restore a recovered OS keyring before an explicit credential save.
+
+ A transient OS-keyring read/write failure switches this process to the
+ portable file backend. Without a recovery attempt, every later in-app save
+ keeps writing only that file while an older OS-keyring value survives and
+ shadows it after the next restart. Explicit user saves are the safe recovery
+ boundary: re-detect the platform backend, capability-probe it with a
+ non-existent slot, and retain the file backend when the platform store is
+ still unavailable (the normal headless-host path).
+
+ This never runs on boot or a normal read, so a locked Secret Service cannot
+ add startup latency or prompts. Returns ``True`` when the platform backend
+ is active, including when no fallback swap had occurred.
+ """
+ global _FILE_BACKEND_ACTIVE
+ if not _FILE_BACKEND_ACTIVE:
+ return True
+
+ keyring_mod = None
+ previous_backend = None
+ try:
+ import keyring as keyring_mod
+ from keyring.core import init_backend
+
+ previous_backend = keyring_mod.get_keyring()
+ init_backend()
+ candidate = keyring_mod.get_keyring()
+ # Capability probe, never an isinstance check against third-party
+ # internals. A real backend returns None for this absent slot; fail or
+ # locked backends raise and are rejected below.
+ candidate.get_password(KEYRING_SERVICE, "__jarvis_backend_probe__")
+ except Exception: # noqa: BLE001 -- unavailable OS keyring is expected headlessly
+ if keyring_mod is not None and previous_backend is not None:
+ try:
+ keyring_mod.set_keyring(previous_backend)
+ except Exception: # noqa: BLE001, S110 -- keep best-effort fallback active
+ pass
+ return False
+
+ _FILE_BACKEND_ACTIVE = False
+ logging.getLogger(__name__).info(
+ "OS credential store recovered; future credential saves use the platform keyring."
+ )
+ return True
+
+
def get_secret(key: str, env_fallback: str | None = None) -> str | None:
"""Retrieve a secret value from every portable credential source.
@@ -2737,6 +2784,11 @@ def set_secret(key: str, value: str) -> bool:
so the headless file fallback is what makes a fresh VPS user able to save a key.
"""
_ensure_keyring_backend()
+ # A prior transient failure may have swapped this process to the file
+ # backend. Re-detect the OS backend on the user's explicit save so the new
+ # value cannot be shadowed by a stale platform entry after restart.
+ if _FILE_BACKEND_ACTIVE:
+ _try_restore_platform_keyring_backend()
try:
import keyring
diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.py
index ef8c682998..8ac97a593e 100644
--- a/jarvis/plugins/stt/openrouter_stt.py
+++ b/jarvis/plugins/stt/openrouter_stt.py
@@ -120,6 +120,7 @@ class OpenRouterSTT:
# ``resolve_provider_endpoint`` so construction stays cheap and never
# triggers a config load on the boot critical path (AP-26).
self._api_key = api_key or None
+ self._api_key_is_explicit = bool(api_key)
self._model = model or DEFAULT_MODEL
self._base_url = base_url or None
self._language = language if language and language != "auto" else None
@@ -214,18 +215,19 @@ class OpenRouterSTT:
return self._client
def _ensure_endpoint(self) -> str:
- """Resolve (and cache) the credential + transcription URL.
+ """Resolve the current credential + transcription URL.
Lazy so construction never loads config; keeps the boot path clean and
- lets the STT factory build the instance before the key is probed. Raises
- a clear English error when no OpenRouter credential is configured, so the
- factory / pipeline can fall back to the local floor (AP-22).
+ lets the STT factory build the instance before the key is probed. A
+ config-resolved key is refreshed at each transcription boundary so one
+ replacement in the API-Keys view applies to brain, TTS, and STT without
+ rebuilding this instance. Explicitly injected credentials remain pinned
+ (team proxy / embedding contract). Raises a clear English error when no
+ OpenRouter credential is configured, so the factory / pipeline can fall
+ back to the local floor (AP-22).
"""
- if self._endpoint_url is not None and self._api_key:
- return self._endpoint_url
-
- base = self._base_url
- if not self._api_key or not base:
+ base = self._base_url or DEFAULT_BASE_URL
+ if not self._api_key_is_explicit:
# Import here (not at module top) to keep the plugin ``jarvis.*``-free
# at import time; the entry-point loader tolerates a lazy internal use.
from jarvis.core import config as _cfg
@@ -233,10 +235,8 @@ class OpenRouterSTT:
ep = _cfg.resolve_provider_endpoint(
"openrouter", vendor_default_base_url=DEFAULT_BASE_URL
)
- if not self._api_key:
- self._api_key = ep.credential or None
- if not base:
- base = ep.base_url or DEFAULT_BASE_URL
+ self._api_key = ep.credential or None
+ base = ep.base_url or DEFAULT_BASE_URL
if not self._api_key:
raise RuntimeError(
diff --git a/jarvis/plugins/tts/openrouter_tts.py b/jarvis/plugins/tts/openrouter_tts.py
index e7f6efc294..b90651c7ee 100644
--- a/jarvis/plugins/tts/openrouter_tts.py
+++ b/jarvis/plugins/tts/openrouter_tts.py
@@ -98,6 +98,11 @@ class OpenRouterTTS:
self._language = language or "auto"
self._speed = speed
self._client: Any = None # httpx.AsyncClient, lazy
+ # Credential/base URL used by the internally-created client. ``None``
+ # while a test or embedding injects its own client, which remains fully
+ # caller-owned and is never replaced here.
+ self._resolved_credential: str | None = None
+ self._resolved_base_url: str | None = None
# Overridden by _ensure_client with the resolved endpoint; a default here
# lets a directly-injected client (tests / warm reuse) synthesise without
# re-resolving the key.
@@ -107,13 +112,18 @@ class OpenRouterTTS:
# Auth + client
# ------------------------------------------------------------------
- def _ensure_client(self) -> None:
- """Build the shared httpx client, resolving the ONE OpenRouter key.
+ async def _ensure_client(self) -> None:
+ """Build or refresh the client from the ONE shared OpenRouter key.
Raises :class:`OpenRouterTTSError` when no credential is configured — the
- same clear, fail-closed signal the factory / FallbackTTS expects.
+ same clear, fail-closed signal the factory / FallbackTTS expects. The
+ endpoint is resolved on every synthesis boundary so replacing the shared
+ brain/TTS/STT credential takes effect without rebuilding the speech
+ pipeline. An unchanged credential reuses the existing keep-alive pool.
"""
- if self._client is not None:
+ # A directly injected client (tests / embedding) has no resolved
+ # credential marker and stays caller-owned.
+ if self._client is not None and self._resolved_credential is None:
return
ep = cfg.resolve_provider_endpoint(
"openrouter", vendor_default_base_url=BASE_URL
@@ -126,7 +136,16 @@ class OpenRouterTTS:
)
import httpx
- self._base_url = (ep.base_url or BASE_URL).rstrip("/")
+ resolved_base_url = (ep.base_url or BASE_URL).rstrip("/")
+ if (
+ self._client is not None
+ and self._resolved_credential == ep.credential
+ and self._resolved_base_url == resolved_base_url
+ ):
+ return
+
+ old_client = self._client
+ self._base_url = resolved_base_url
self._client = httpx.AsyncClient(
timeout=_HTTP_TIMEOUT_S,
headers={
@@ -137,6 +156,13 @@ class OpenRouterTTS:
"X-Title": "Personal Jarvis",
},
)
+ self._resolved_credential = ep.credential
+ self._resolved_base_url = resolved_base_url
+ if old_client is not None:
+ try:
+ await old_client.aclose()
+ except Exception as exc: # noqa: BLE001 -- replacement already succeeded
+ log.debug("Closing the superseded OpenRouter TTS client failed: %s", exc)
async def aclose(self) -> None:
"""Close the HTTP client. Idempotent."""
@@ -145,6 +171,8 @@ class OpenRouterTTS:
await self._client.aclose()
finally:
self._client = None
+ self._resolved_credential = None
+ self._resolved_base_url = None
# ------------------------------------------------------------------
# Voice resolution
@@ -229,7 +257,7 @@ class OpenRouterTTS:
return
# No key / build failure → raise before any chunk (FallbackTTS crosses).
- self._ensure_client()
+ await self._ensure_client()
resolved_voice = self._resolve_voice(voice, language_code)
payload: dict[str, Any] = {
diff --git a/tests/unit/core/test_keyring_backend_recovery.py b/tests/unit/core/test_keyring_backend_recovery.py
new file mode 100644
index 0000000000..8ce5674c3e
--- /dev/null
+++ b/tests/unit/core/test_keyring_backend_recovery.py
@@ -0,0 +1,97 @@
+"""Regression coverage for recovering from a transient keyring fallback.
+
+An in-app save must not remain trapped in the local file backend after the OS
+credential store becomes usable again. Otherwise an older platform credential
+shadows the newly saved value on the next process start.
+"""
+from __future__ import annotations
+
+import keyring
+import keyring.backend
+import pytest
+
+import jarvis.core.config as cfg
+
+
+class _MemoryBackend(keyring.backend.KeyringBackend):
+ priority = 1.0
+
+ def __init__(self) -> None:
+ self.values: dict[tuple[str, str], str] = {}
+
+ def get_password(self, service: str, username: str) -> str | None:
+ return self.values.get((service, username))
+
+ def set_password(self, service: str, username: str, password: str) -> None:
+ self.values[(service, username)] = password
+
+ def delete_password(self, service: str, username: str) -> None:
+ self.values.pop((service, username), None)
+
+
+class _UnavailableBackend(_MemoryBackend):
+ def get_password(self, service: str, username: str) -> str | None:
+ raise RuntimeError("credential service unavailable")
+
+
+def _restore_keyring_backend():
+ original = keyring.get_keyring()
+ try:
+ yield
+ finally:
+ keyring.set_keyring(original)
+
+
+def test_explicit_save_restores_platform_backend_and_removes_stale_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+ _restore_keyring_backend,
+) -> None:
+ file_backend = _MemoryBackend()
+ platform_backend = _MemoryBackend()
+ keyring.set_keyring(file_backend)
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)
+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)
+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)
+
+ store = cfg._FileCredStore()
+ store.set(cfg.KEYRING_SERVICE, "openrouter_api_key", "new-file-value")
+
+ def _restore_platform() -> None:
+ keyring.set_keyring(platform_backend)
+
+ monkeypatch.setattr(keyring.core, "init_backend", _restore_platform)
+
+ assert cfg.set_secret("openrouter_api_key", "new-file-value") is True
+ assert (
+ platform_backend.get_password(cfg.KEYRING_SERVICE, "openrouter_api_key")
+ == "new-file-value"
+ )
+ assert store.get(cfg.KEYRING_SERVICE, "openrouter_api_key") is None
+ assert cfg._FILE_BACKEND_ACTIVE is False
+
+
+def test_explicit_save_keeps_file_backend_when_platform_store_is_still_unusable(
+ monkeypatch: pytest.MonkeyPatch,
+ _restore_keyring_backend,
+) -> None:
+ file_backend = _MemoryBackend()
+ unavailable = _UnavailableBackend()
+ keyring.set_keyring(file_backend)
+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)
+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)
+
+ def _restore_unavailable_platform() -> None:
+ keyring.set_keyring(unavailable)
+
+ monkeypatch.setattr(keyring.core, "init_backend", _restore_unavailable_platform)
+
+ assert cfg.set_secret("openrouter_api_key", "headless-value") is True
+ assert (
+ file_backend.get_password(cfg.KEYRING_SERVICE, "openrouter_api_key")
+ == "headless-value"
+ )
+ assert keyring.get_keyring() is file_backend
+ assert cfg._FILE_BACKEND_ACTIVE is True