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-03 16:42)

Ruben Lütkeaae3be57a9cb
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 8840199645..42e37c3f32 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -3116,6 +3116,29 @@ class BrainManager:
provider, was_dead, len(keys_to_drop),
)
+ def _active_has_usable_credential(self) -> bool:
+ """Whether the currently active brain provider has a usable credential.
+
+ True iff an API key is present in any of the active provider's secret
+ slots, or a keyless provider is rescued by a connected OAuth login
+ (mirrors the pre-boot key check in ``from_tier_config`` so the two stay
+ consistent). Used by the ``SecretConfigured`` handler to decide whether a
+ fresh-install ``brain.primary`` default — which the downloader has no key
+ for — should yield to the provider the user just configured.
+ """
+ from jarvis.core import config as _cfg_mod
+ from jarvis.core.config import PROVIDER_SECRET_CANDIDATES
+
+ active = self._active_name
+ specs = PROVIDER_SECRET_CANDIDATES.get(active)
+ if specs:
+ try:
+ if _cfg_mod.get_secret_any(specs):
+ return True
+ except Exception: # noqa: BLE001 — an unreadable keyring counts as "no key"
+ pass
+ return _keyless_provider_is_rescued_by_oauth(active)
+
def apply_provider_model(self, provider: str, model: str) -> bool:
"""Live-apply a model override for a brain provider (no restart).
@@ -7657,6 +7680,38 @@ class BrainManager:
if not provider:
return
self.reactivate_provider(provider)
+ # Fresh-install heal (open-source AP-22/AP-23): on a first run there
+ # is no jarvis.toml, so brain.primary is the packaged code-default
+ # (e.g. claude-api) that the downloader has NO key for. Setting a key
+ # for a DIFFERENT provider used to leave that dead default active, so
+ # the brain kept reporting "not configured" even though a usable key
+ # was now present — the #1 fresh-laptop symptom. If the currently
+ # active provider has no usable credential, promote the provider the
+ # user just keyed to active and persist it. This is NOT the autonomous
+ # self-switch the USER-ONLY / provider_lock mandate forbids: it fires
+ # only in direct response to the user's OWN key-set action (the same
+ # path as a manual "Set as active" click, via config_writer — never
+ # the locked self-mod writer), and it never overrides a provider the
+ # user deliberately selected (one that already has a working key or
+ # OAuth login is left untouched).
+ if provider == self._active_name:
+ return # reactivate_provider already re-armed the active one
+ if self._active_has_usable_credential():
+ return
+ previous_active = self._active_name
+ try:
+ await self.switch(provider, persist=True)
+ log.info(
+ "Fresh-install heal: active brain %r had no usable "
+ "credential; promoted just-keyed provider %r to active and "
+ "persisted brain.primary.",
+ previous_active, provider,
+ )
+ except Exception: # noqa: BLE001 — a subscriber must never kill the bus (AP-18)
+ log.warning(
+ "auto-activate on key-set failed for provider %r",
+ provider, exc_info=True,
+ )
target_bus.subscribe(SecretConfigured, _on_secret_configured)
diff --git a/tests/unit/brain/test_key_set_auto_activates_brain.py b/tests/unit/brain/test_key_set_auto_activates_brain.py
new file mode 100644
index 0000000000..6c5713363f
--- /dev/null
+++ b/tests/unit/brain/test_key_set_auto_activates_brain.py
@@ -0,0 +1,130 @@
+"""Setting an API key must promote that provider to the active brain when the
+current active provider is dead — the #1 fresh-install symptom.
+
+Forensic: a downloader has no ``jarvis.toml`` (it is gitignored), so ``brain.primary``
+is the packaged code-default (e.g. ``claude-api``) they have NO key for. They open
+API Keys, paste their ONE key (say OpenRouter), and nothing happens — the dead
+default stays active and the brain keeps reporting "not configured". The fix: on a
+``SecretConfigured(set)`` for a brain provider, if the active provider has no usable
+credential, switch to and persist the just-keyed provider.
+
+This must NOT become an autonomous self-switch (the USER-ONLY / provider_lock
+mandate): it fires only in direct response to the user's own key-set action and
+never overrides a provider the user deliberately selected (one that already has a
+usable key/login).
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import load_config
+from jarvis.core.events import SecretConfigured
+
+
+def _cfg(*, primary: str):
+ cfg = load_config()
+ cfg.brain.primary = primary
+ cfg.brain.router.provider = primary
+ cfg.brain.router.fallback_provider = primary
+ return cfg
+
+
+def _manager(primary: str) -> tuple[BrainManager, EventBus]:
+ bus = EventBus()
+ mgr = BrainManager.from_tier_config("router", _cfg(primary=primary), bus)
+ mgr.attach_to_bus(bus)
+ return mgr, bus
+
+
+async def test_key_set_promotes_when_active_provider_is_dead(monkeypatch) -> None:
+ # Fresh install: active provider (claude-api default) has no usable credential.
+ mgr, bus = _manager("claude-api")
+ assert mgr.active_provider == "claude-api"
+ monkeypatch.setattr(mgr, "_active_has_usable_credential", lambda: False)
+ # Don't touch the real jarvis.toml — persist through a stubbed writer.
+ persisted: list[str] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_primary",
+ lambda name: persisted.append(name),
+ )
+
+ # User pastes their ONLY key — OpenRouter.
+ await bus.publish(SecretConfigured(key="openrouter_api_key", action="set"))
+
+ assert mgr.active_provider == "openrouter"
+ assert persisted == ["openrouter"] # survives a restart
+
+
+async def test_key_set_does_not_override_a_working_active_provider(monkeypatch) -> None:
+ # The user has a deliberately-chosen, working active provider. Adding a
+ # SECOND key for a different provider must NOT hijack their choice.
+ mgr, bus = _manager("claude-api")
+ monkeypatch.setattr(mgr, "_active_has_usable_credential", lambda: True)
+ switched: list[str] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_primary",
+ lambda name: switched.append(name),
+ )
+
+ await bus.publish(SecretConfigured(key="gemini_api_key", action="set"))
+
+ assert mgr.active_provider == "claude-api"
+ assert switched == []
+
+
+async def test_key_set_for_a_non_brain_slot_is_ignored(monkeypatch) -> None:
+ # An STT/TTS key (groq) is not a brain provider — it must never move the brain.
+ mgr, bus = _manager("claude-api")
+ monkeypatch.setattr(mgr, "_active_has_usable_credential", lambda: False)
+ switched: list[str] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_primary",
+ lambda name: switched.append(name),
+ )
+
+ await bus.publish(SecretConfigured(key="groq_api_key", action="set"))
+
+ assert mgr.active_provider == "claude-api"
+ assert switched == []
+
+
+async def test_delete_action_never_switches(monkeypatch) -> None:
+ mgr, bus = _manager("claude-api")
+ monkeypatch.setattr(mgr, "_active_has_usable_credential", lambda: False)
+ monkeypatch.setattr("jarvis.core.config_writer.set_brain_primary", lambda name: None)
+
+ await bus.publish(SecretConfigured(key="openrouter_api_key", action="delete"))
+
+ assert mgr.active_provider == "claude-api"
+
+
+def test_active_has_usable_credential_reflects_key_presence(monkeypatch) -> None:
+ # The helper is what decides "dead default vs. deliberate choice" — lock its
+ # two branches without depending on which keys the test host actually has.
+ mgr, _bus = _manager("claude-api")
+
+ monkeypatch.setattr("jarvis.core.config.get_secret_any", lambda specs: None)
+ monkeypatch.setattr(
+ "jarvis.brain.manager._keyless_provider_is_rescued_by_oauth", lambda name: False
+ )
+ assert mgr._active_has_usable_credential() is False
+
+ monkeypatch.setattr("jarvis.core.config.get_secret_any", lambda specs: "sk-present")
+ assert mgr._active_has_usable_credential() is True
+
+
+def test_active_has_usable_credential_true_via_oauth(monkeypatch) -> None:
+ # A keyless provider rescued by a connected OAuth login counts as usable —
+ # it must not be overridden even with no API key in any slot.
+ mgr, _bus = _manager("claude-api")
+ monkeypatch.setattr("jarvis.core.config.get_secret_any", lambda specs: None)
+ monkeypatch.setattr(
+ "jarvis.brain.manager._keyless_provider_is_rescued_by_oauth", lambda name: True
+ )
+ assert mgr._active_has_usable_credential() is True