The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(setup): a provider configured after boot unblocks the dashboard chat without a restart
teknium15ae7ec8623d2
diff --git a/hermes_cli/free_tier_bootstrap.py b/hermes_cli/free_tier_bootstrap.pyindex 073a56c71c2..0274ca9f299 100644--- a/hermes_cli/free_tier_bootstrap.py+++ b/hermes_cli/free_tier_bootstrap.py@@ -16,7 +16,7 @@ from __future__ import annotationsimport loggingimport threadingimport time-from dataclasses import asdict, dataclass, field+from dataclasses import asdict, dataclass, field, replacefrom typing import Any, Dict, Optionallogger = logging.getLogger("hermes_cli.auth")@@ -59,6 +59,10 @@ _lock = threading.Lock()_record: Optional[SetupRecord] = None_done = threading.Event()_started = False+# ``(mtime_ns, size)`` of the files the inventory reads, taken by the inventory that built the+# current record; ``reconcile_record`` re-inventories only when they moved.+_inventory_stamp: Optional[tuple] = None+_INVENTORY_FILES = ("config.yaml", ".env", "auth.json")def current_record() -> Optional[SetupRecord]:@@ -68,31 +72,77 @@ def current_record() -> Optional[SetupRecord]:def wait_for_record(timeout: float = SETUP_READY_WAIT_SECONDS) -> Optional[SetupRecord]:"""Block up to ``timeout`` seconds for a bootstrap that is IN FLIGHT, then return whatever it- produced. Returns None at once when no bootstrap ever started in this process (a bare- ``tui_gateway`` under test, an old serve without the boot hook): the caller falls back to its- live probe instead of paying the wait for nothing."""+ produced, reconciled with any provider configured since (:func:`reconcile_record`). Returns+ None at once when no bootstrap ever started in this process (a bare ``tui_gateway`` under+ test, an old serve without the boot hook): the caller falls back to its live probe instead of+ paying the wait for nothing."""if not _started:return None_done.wait(timeout)- return _record+ return reconcile_record()+++def reconcile_record() -> Optional[SetupRecord]:+ """Let a provider configured AFTER boot count: a record that says ``provider_configured:+ false`` is re-inventoried once ``config.yaml`` / ``.env`` / ``auth.json`` moved since the+ inventory that built it, and replaced (+ ``setup.ready``) when something now carries+ inference. The mint verdict (identity, failure block) is kept as is: only the boot bootstrap+ and its retries mint. A record that already says ``True`` is never re-probed, so the answer+ only moves false -> true here. Every write path that assigns the main model (the Models page,+ a picker key save) calls this for the immediate broadcast; ``setup.status`` calls it for+ writes this process never saw (``hermes setup`` / ``hermes model`` from a shell, a hand edit)."""+ global _record+ record = _record+ if record is None or record.provider_configured or _inventory_stamp == _config_stamp():+ return record+ if not _inventory_other_providers():+ return _record+ refreshed = replace(record, provider_configured=True, other_providers=True,+ inference_provider=_resolve_inference(), finished_at=time.time())+ with _lock:+ if _record is not record: # a retry replaced it meanwhile; its inventory is newer+ return _record+ _record = refreshed+ _broadcast(refreshed)+ return refresheddef reset_for_tests() -> None:- global _record, _started+ global _record, _started, _inventory_stampwith _lock:_record = None_started = False+ _inventory_stamp = None_done.clear()+def _config_stamp() -> tuple:+ from hermes_cli.config import get_hermes_home+ home = get_hermes_home()+ stamp = []+ for name in _INVENTORY_FILES:+ try:+ st = (home / name).stat()+ stamp.append((st.st_mtime_ns, st.st_size))+ except OSError:+ stamp.append(None)+ return tuple(stamp)++def _inventory_other_providers() -> bool:"""Is anything usable configured BESIDES the free tier? Asks the resolver ladder itself (thething that picks the provider for a turn) with the free-tier rung hidden: an explicit key, aconfig pin, a sign-in or a host credential answers; nothing else falls through to``no_provider_configured``. Not ``_has_any_provider_configured``: that first-run guard alsocounts host credentials (gh auth, Claude Code) and a config pin, and it does not hide the- free-tier rung."""+ free-tier rung.++ Stamps the config files BEFORE reading them, so a write that lands during the inventory is+ seen by the next :func:`reconcile_record`.+ """+ global _inventory_stampfrom hermes_cli.auth import resolve_provider+ _inventory_stamp = _config_stamp()try:return resolve_provider("auto", skip_free_tier=True) != "nous"except Exception as exc:diff --git a/hermes_cli/web_server_config.py b/hermes_cli/web_server_config.pyindex 53fa363e066..b5fd93f4417 100644--- a/hermes_cli/web_server_config.py+++ b/hermes_cli/web_server_config.py@@ -671,25 +671,10 @@ def _prepare_main_assignment(cfg: dict, provider: str, model: str, base_url: strreturn base_url, _validated_main_model_selection(cfg, provider, model, base_url, api_key)-def _refresh_setup_readiness() -> None:- """Re-run the free-tier bootstrap inventory after a model assignment landed on disk.-- A serve process whose boot-time mint failed keeps its record at- ``provider_configured: false`` for the whole process lifetime, so every- ``setup.status`` keeps the chat gated long after the user configured a- provider elsewhere. The re-inventory never mints when an identity already- exists; on success it broadcasts ``setup.ready`` to every connected client.- """- try:- from hermes_cli.free_tier_bootstrap import retry_bootstrap_mint- retry_bootstrap_mint(force=True, announce=True)- except Exception:- _log.debug("setup readiness refresh after model assignment failed", exc_info=True)--def _apply_main_assignment_sync(cfg: dict, provider: str, model: str, base_url: str, api_key: str,prepared: "Optional[tuple[str, ModelSwitchResult]]" = None) -> dict:from hermes_cli.config import save_config+ from hermes_cli.free_tier_bootstrap import reconcile_recordbase_url, result = prepared or _prepare_main_assignment(cfg, provider, model, base_url, api_key)provider, model = result.target_provider, result.new_modelprovider_entry = _provider_entry(cfg, provider)@@ -702,7 +687,8 @@ def _apply_main_assignment_sync(cfg: dict, provider: str, model: str, base_url:save_config(cfg)if new_provider in {"custom", "local"} and base_url:_register_custom_endpoint(base_url, api_key, model)- _refresh_setup_readiness()+ # The serve process's boot record may still say "nothing configured"; the chat gates on it.+ reconcile_record()return {"ok": True,diff --git a/tests/hermes_cli/test_resolve_provider_custom_endpoint.py b/tests/hermes_cli/test_resolve_provider_custom_endpoint.pyindex d986f4dc956..2c9c03b3599 100644--- a/tests/hermes_cli/test_resolve_provider_custom_endpoint.py+++ b/tests/hermes_cli/test_resolve_provider_custom_endpoint.py@@ -89,3 +89,30 @@ def test_auto_provider_with_loopback_base_url_resolves_without_recursing(isolatemonkeypatch.setattr(runtime_provider, "_resolves_to_custom", unexpected_provider_resolution)assert resolve_provider("auto") == "custom"+++def test_a_provider_configured_after_boot_flips_the_stale_setup_record(isolated_home, monkeypatch):+ """A serve process whose boot inventory found nothing keeps that record for its lifetime;+ ``setup.status`` reads it (``wait_for_record``), so the dashboard chat stayed on "Setup+ Required" after the user configured a provider — from the Models page, a picker key, or+ ``hermes setup`` in another process. A ``False`` record is reconciled with the config files+ on read: it flips (+ one ``setup.ready``) once something carries inference, and a blank+ machine stays ``False`` with no broadcast."""+ from hermes_cli import free_tier_bootstrap as fb++ broadcasts = []+ monkeypatch.setattr(fb, "_broadcast", broadcasts.append)+ boot = fb.run_bootstrap(announce=False)+ assert boot.provider_configured is False+ assert fb.wait_for_record(timeout=0) is boot and broadcasts == [], "blank machine: nothing to reconcile"++ (isolated_home / "config.yaml").write_text(+ "model:\n default: qwen3\n provider: custom\n base_url: http://127.0.0.1:8000/v1\n api_key: dummy\n",+ encoding="utf-8",+ )+ fresh = fb.wait_for_record(timeout=0)+ assert fresh.provider_configured is True and fresh.other_providers is True+ assert fresh.inference_provider == "custom"+ assert fresh.has_identity is boot.has_identity and fresh.failure == boot.failure, "the mint verdict is kept"+ assert broadcasts == [fresh]+ assert fb.wait_for_record(timeout=0) is fresh and broadcasts == [fresh], "settled: no re-inventory, no re-announce"diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 1e3ff1fcbdb..148909e5877 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -1506,41 +1506,34 @@ class TestWebServerEndpoints:assert data["model"] == "moonshotai/kimi-k2.6"- def test_model_set_refreshes_a_stale_setup_record(self, monkeypatch):- """POST /api/model/set landed a provider on disk; the serve process's- boot record must follow, or the web chat stays gated on "need setup"- until a restart (setup.status answers from the record)."""+ def test_model_set_flips_a_stale_setup_record(self, monkeypatch):+ """POST /api/model/set landed a provider on disk; the serve process's boot record+ (``provider_configured: false`` since a failed boot-time mint) must follow at once, with+ the ``setup.ready`` broadcast, or the web chat stays gated on "need setup" until a restart+ (setup.status answers from the record)."""from hermes_cli import free_tier_bootstrap as fbfb.reset_for_tests()- monkeypatch.setattr(- "hermes_cli.model_cost_guard.expensive_model_warning",- lambda *_args, **_kwargs: None,- )- from hermes_cli.config import load_config, save_config- cfg = load_config()- cfg["model"] = {"provider": "openrouter", "default": "openai/gpt-5.5"}- save_config(cfg)- stale = fb.SetupRecord(- provider_configured=False, inference_provider="", free_tier=False,- has_identity=False, other_providers=False)+ monkeypatch.setattr("hermes_cli.model_cost_guard.expensive_model_warning", lambda *_a, **_k: None)+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)+ broadcasts = []+ monkeypatch.setattr(fb, "_broadcast", broadcasts.append)with fb._lock:- fb._record = stale+ fb._record = fb.SetupRecord(provider_configured=False, inference_provider="", free_tier=False,+ has_identity=False, other_providers=False)fb._started = Truefb._done.set()- refreshed = []- monkeypatch.setattr(- fb, "retry_bootstrap_mint", lambda **kw: refreshed.append(kw) or stale- )try:resp = self.client.post("/api/model/set",- json={"scope": "main", "provider": "openrouter",- "model": "moonshotai/kimi-k2.6"},+ json={"scope": "main", "provider": "custom", "model": "local-model",+ "base_url": "http://127.0.0.1:8081/v1", "api_key": "sk-local"},)- assert resp.status_code == 200- assert resp.json()["ok"] is True- assert refreshed and refreshed[0].get("force") is True+ assert resp.status_code == 200 and resp.json()["ok"] is True+ record = fb.current_record()+ assert record.provider_configured is True and record.other_providers is True+ assert record.inference_provider == "custom"+ assert broadcasts == [record]finally:fb.reset_for_tests()diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 9896bd35095..fea556633a4 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -16968,84 +16968,6 @@ def test_model_save_key_uses_credential_lifecycle_and_picker_context(monkeypatch)-def test_model_save_key_refreshes_a_stale_setup_record(monkeypatch):- """A key saved from the gated picker must move the boot record too, or the- chat stays "need setup" (setup.status answers from the record) until the- serve process restarts."""- from hermes_cli import free_tier_bootstrap as fb-- fb.reset_for_tests()- stale = fb.SetupRecord(- provider_configured=False, inference_provider="", free_tier=False,- has_identity=False, other_providers=False)- with fb._lock:- fb._record = stale- fb._started = True- fb._done.set()- retried = []- monkeypatch.setattr(- fb, "retry_bootstrap_mint", lambda **kw: retried.append(kw) or stale- )- monkeypatch.setattr(- "hermes_cli.auth.PROVIDER_REGISTRY",- {"test-provider": types.SimpleNamespace(- name="Test Provider", auth_type="api_key",- api_key_env_vars=("TEST_STALE_RECORD_KEY",))})- monkeypatch.setattr("hermes_cli.config.is_managed", lambda: False)- monkeypatch.setattr(- "hermes_cli.credential_lifecycle.save_provider_env_credential", Mock())- monkeypatch.setattr(server, "_model_picker_context", Mock(return_value=object()))- monkeypatch.setattr(- "hermes_cli.inventory.build_models_payload",- Mock(return_value={"providers": [{"slug": "test-provider", "models": [], "total_models": 0}]}))-- try:- resp = server._methods["model.save_key"](- 104, {"slug": "test-provider", "api_key": "k-1"})-- assert "result" in resp, resp- assert retried and retried[0].get("force") is True- finally:- fb.reset_for_tests()---def test_model_save_key_leaves_a_profile_scoped_record_alone(monkeypatch):- """The record belongs to the launch profile; a profile-scoped save must not- rewrite it with another home's inventory."""- from hermes_cli import free_tier_bootstrap as fb-- fb.reset_for_tests()- with fb._lock:- fb._record = fb.SetupRecord(- provider_configured=False, inference_provider="", free_tier=False,- has_identity=False, other_providers=False)- fb._started = True- fb._done.set()- retried = []- monkeypatch.setattr(fb, "retry_bootstrap_mint", lambda **kw: retried.append(kw))- monkeypatch.setattr(- "hermes_cli.auth.PROVIDER_REGISTRY",- {"test-provider": types.SimpleNamespace(- name="Test Provider", auth_type="api_key",- api_key_env_vars=("TEST_PROFILE_SCOPE_KEY",))})- monkeypatch.setattr("hermes_cli.config.is_managed", lambda: False)- monkeypatch.setattr(- "hermes_cli.credential_lifecycle.save_provider_env_credential", Mock())- monkeypatch.setattr(server, "_model_picker_context", Mock(return_value=object()))- monkeypatch.setattr(- "hermes_cli.inventory.build_models_payload",- Mock(return_value={"providers": [{"slug": "test-provider", "models": [], "total_models": 0}]}))-- try:- resp = server._methods["model.save_key"](- 105, {"slug": "test-provider", "api_key": "k-2", "profile": "other"})-- assert "result" in resp, resp- assert retried == []- finally:- fb.reset_for_tests()--# ---------------------------------------------------------------------------# prompt.submit — auto-title# ---------------------------------------------------------------------------diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.pyindex 822b01c8c0f..a917d69844c 100644--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@ -360,11 +360,11 @@ def _(rid, params: dict) -> dict:from hermes_cli.credential_lifecycle import save_provider_env_credential # also rotates stale config.yaml mirrorssave_provider_env_credential(env_var, api_key)os.environ[env_var] = api_key # so the refreshed inventory sees it- # The record may still say "nothing configured" from a failed boot-time mint; a- # fresh key must move setup.status (and the setup.ready listeners) with it.- from hermes_cli import free_tier_bootstrap- if free_tier_bootstrap.current_record() is not None and not params.get("profile"):- free_tier_bootstrap.retry_bootstrap_mint(force=True)+ # The launch profile's boot record may still say "nothing configured"; the gated picker's+ # own chat waits on setup.status, so the fresh key must move the record (+ setup.ready).+ if not params.get("profile"):+ from hermes_cli.free_tier_bootstrap import reconcile_record+ reconcile_record()# Shared inventory builder (lock-step with model.options / dashboard); picker_hints carries `authenticated`.from hermes_cli.inventory import build_models_payloadpayload = build_models_payload(_model_picker_context(_session_agent(params)), picker_hints=True, max_models=50)diff --git a/tui_gateway/methods_config.py b/tui_gateway/methods_config.pyindex c0ed5086590..5dd1df090af 100644--- a/tui_gateway/methods_config.py+++ b/tui_gateway/methods_config.py@@ -271,7 +271,10 @@ def _(rid, params: dict) -> dict:For the launch profile the answer is the boot bootstrap's record (``free_tier_bootstrap``):the call blocks up to ``SETUP_READY_WAIT_SECONDS`` for it, so a client's first poll lands after- the free-tier identity exists (or has been refused) rather than racing the mint. If the record+ the free-tier identity exists (or has been refused) rather than racing the mint. A record that+ says ``False`` is reconciled with the config files first (``reconcile_record``): a provider+ added after boot — the Models page, a picker key, ``hermes setup`` from a shell — flips it+ without a restart. If the recordis still missing after the wait, or a named profile is asked about, today's live probe answers.The record's fields ride along additively (``ready``, ``free_tier``, ``other_providers``)."""try:diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.pyindex 4e89aa0806f..583112df83d 100644--- a/tui_gateway/methods_config_set.py+++ b/tui_gateway/methods_config_set.py@@ -147,8 +147,11 @@ def _set_model(rid, params, key, value, session):if parse_model_switch_args(str(value)).is_once:result = _apply_model_switch("", {"agent": None}, value, confirm_expensive_model=confirmed)else:- return _err(rid, 4001, "config.set model requires a live session; "- "use Settings -> Models to change the profile default")+ # One string for every client: the Ink TUI (dashboard /chat, `hermes --tui`) has no+ # Settings; the dashboard has a Models page; only the Desktop has Settings -> Models.+ return _err(rid, 4001, "config.set model requires a live session; to change the "+ "profile default run /setup, or use the Models page (dashboard) / "+ "Settings -> Models (Desktop)")return _kv(rid, key, result["value"], warning=result["warning"],confirm_required=result.get("confirm_required", False),confirm_message=result.get("confirm_message", ""), scope=result.get("scope", "session"))diff --git a/ui-tui/src/content/setup.ts b/ui-tui/src/content/setup.tsindex 49dd9aa247d..24a25284f3e 100644--- a/ui-tui/src/content/setup.ts+++ b/ui-tui/src/content/setup.ts@@ -8,10 +8,13 @@ export const buildSetupRequiredSections = (): PanelSection[] => [},{rows: [- ['/model', 'configure provider + model in-place'],- ['/setup', 'run full first-time setup wizard in-place'],+ ['/setup', 'run the first-time setup wizard in-place (adds a provider)'],+ ['/model', 'pick a model (needs a session — add a provider first)'],['Ctrl+C', 'exit and run `hermes setup` manually']],title: 'Actions'+ },+ {+ text: 'In the dashboard the Models page sets the profile default; on Desktop it is Settings -> Models.'}]