The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: move the free-tier tests onto the welcome-trial rules
alt-glitcha8cf3a2cdc94
diff --git a/tests/agent/test_bedrock_integration.py b/tests/agent/test_bedrock_integration.pyindex 07af3bf9db8..33e253c99f9 100644--- a/tests/agent/test_bedrock_integration.py+++ b/tests/agent/test_bedrock_integration.py@@ -92,9 +92,6 @@ class TestResolveProvider:monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAIOSFODNN7EXAMPLE")monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")- # The Nous free tier counts as a configured provider and sits above the Bedrock chain- # (NS-829); this test's contract is the chain itself, so switch the free tier off.- monkeypatch.setattr("hermes_cli.anon_auth.guest_enabled", lambda: False)# Mock the auth store to have no active providerwith patch("hermes_cli.auth._load_auth_store", return_value={}):result = resolve_provider("auto")diff --git a/tests/agent/test_credential_pool_connectors_guest.py b/tests/agent/test_credential_pool_connectors_guest.pyindex d62b4644569..c54fcf7a3dc 100644--- a/tests/agent/test_credential_pool_connectors_guest.py+++ b/tests/agent/test_credential_pool_connectors_guest.py@@ -1,24 +1,24 @@-"""A guest kept for connectors only never serves inference through the credential pool.+"""A guest that does not carry inference here never serves inference through the credential pool.-A guest that carried inference in a build with the free-tier launch gate leaves a ``device_code``-row in ``credential_pool.nous``. In a process without the gate (plain CLI, gateway) the pool must+A guest that claimed the welcome trial on the desktop's local backend leaves a ``device_code`` row+in ``credential_pool.nous``. In a process that is not that backend (plain CLI, gateway) the pool mustdrop that row instead of handing its welcome-host token to the runtime."""from hermes_cli import anon_auth-from tests.hermes_cli.anon_portal import install_portal+from tests.hermes_cli.anon_portal import claimed_trial, install_portal-def test_guest_pool_row_is_dropped_when_the_free_tier_is_off(monkeypatch, tmp_path):+def test_guest_pool_row_is_dropped_outside_the_desktop_backend(monkeypatch, tmp_path):from agent.credential_pool import load_poolfrom hermes_cli.auth_nous import resolve_nous_runtime_credentialsinstall_portal(monkeypatch, tmp_path)- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))- resolve_nous_runtime_credentials() # the guest now carries an inference token+ claimed_trial(monkeypatch)+ resolve_nous_runtime_credentials() # the claimed guest now carries an inference tokenassert any(e.source == "device_code" for e in load_pool("nous").entries())- monkeypatch.delenv("HERMES_GUEST_ONBOARDING")+ monkeypatch.delenv("HERMES_DESKTOP")assert not any(e.source == "device_code" for e in load_pool("nous").entries())assert anon_auth.has_guest()diff --git a/tests/gateway/test_first_contact_dm.py b/tests/gateway/test_first_contact_dm.pyindex ebeaabba43c..cd5ba55edae 100644--- a/tests/gateway/test_first_contact_dm.py+++ b/tests/gateway/test_first_contact_dm.py@@ -21,11 +21,9 @@ def _runner(tmp_path, monkeypatch):@pytest.mark.asyncio[email protected]("guest", ["1", "0"])-async def test_first_dm_gets_the_profile_build_offer_once(tmp_path, monkeypatch, guest):+async def test_first_dm_gets_the_profile_build_offer_once(tmp_path, monkeypatch):from agent.onboarding import PROFILE_BUILD_FLAG, profile_build_directive- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", guest)(tmp_path / "config.yaml").write_text("model: test\n", encoding="utf-8")runner = _runner(tmp_path, monkeypatch)source = SessionSource(platform=Platform.TELEGRAM, chat_id="dm", user_id="u", chat_type="dm")diff --git a/tests/gateway/test_free_tier_gateway_boot.py b/tests/gateway/test_free_tier_gateway_boot.pydeleted file mode 100644index bc1852b039a..00000000000--- a/tests/gateway/test_free_tier_gateway_boot.py+++ /dev/null@@ -1,40 +0,0 @@-"""The messaging gateway is a boot owner of the Nous free tier.--Rung 5 made every demand-time site a read (provider resolution, ``/login``, the connector token), so a-process that never runs the bootstrap can never have an identity. `cmd_chat` and `hermes serve` run it;-this file pins that `hermes gateway run` does too, and does it BEFORE any adapter connects, so a fast-first DM cannot arrive with nothing to resolve.-"""--import pytest--from gateway.config import GatewayConfig, Platform, PlatformConfig-from gateway.run import GatewayRunner-from gateway import run_startup--async def test_gateway_boot_runs_the_free_tier_bootstrap_before_any_adapter_connects(monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- order: list[str] = []-- def fake_bootstrap() -> None:- order.append("bootstrap")-- async def fake_prefilter(self):- order.append("prefilter-platforms")- # No pending connects: startup exits cleanly at the no-connections check, which is exactly the- # path the cold cell drives. Shape mirrors the real return.- return (False, 0, [], [])-- monkeypatch.setattr(GatewayRunner, "_start_free_tier_bootstrap", staticmethod(fake_bootstrap))- monkeypatch.setattr(run_startup.GatewayStartupMixin, "_start_prefilter_platforms", fake_prefilter)-- config = GatewayConfig(- platforms={Platform.TELEGRAM: PlatformConfig(enabled=False)},- sessions_dir=tmp_path / "sessions",- )- runner = GatewayRunner(config)- ok = await runner.start()-- assert ok is True- assert order[:2] == ["bootstrap", "prefilter-platforms"], orderdiff --git a/tests/gateway/test_free_tier_startup_notice.py b/tests/gateway/test_free_tier_startup_notice.pydeleted file mode 100644index aed88011611..00000000000--- a/tests/gateway/test_free_tier_startup_notice.py+++ /dev/null@@ -1,100 +0,0 @@-"""Home-channel startup notice names the free tier only when a guest carries the gateway's inference."""--import base64-import json-import time--import pytest-from unittest.mock import AsyncMock--import gateway.run as gateway_run-from gateway.config import HomeChannel, Platform-from gateway.platforms.base import SendResult-from hermes_cli import anon_auth-from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store-from tests.gateway.restart_test_helpers import make_restart_runner----def _jwt(**claims) -> str:- def seg(obj):- return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()- payload = {"sub": "nas_user:1", "client_id": "nas-anonymous", "account_tier": "anonymous",- "scope": "inference:invoke", "exp": int(time.time()) + 900, **claims}- return f"{seg({'alg': 'RS256'})}.{seg(payload)}.sig"---def _seed_nous(state: dict) -> None:- with _auth_store_lock():- store = _load_auth_store()- store.setdefault("providers", {})["nous"] = state- store["active_provider"] = "nous"- _save_auth_store(store)---def _guest_state() -> dict:- return {"auth_method": anon_auth.ANON_AUTH_METHOD, "account_tier": "anonymous", "anon_token": "anon_0001",- "client_id": "nas-anonymous", "access_token": _jwt(), "expires_at": "2999-01-01T00:00:00+00:00",- "inference_base_url": "https://welcome-api.nousresearch.com/v1"}---def _account_state() -> dict:- return {"auth_method": "oauth", "access_token": _jwt(client_id="hermes-cli", account_tier="pro"),- "refresh_token": "rt", "expires_at": "2999-01-01T00:00:00+00:00"}---def nous_runner(tmp_path, monkeypatch):- monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")- # Provider precedence gates the line and is answered from persisted state only (no network at boot).- for var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NOUS_API_KEY"):- monkeypatch.delenv(var, raising=False)- runner, adapter = make_restart_runner()- runner.config.platforms[Platform.TELEGRAM].home_channel = HomeChannel(- platform=Platform.TELEGRAM, chat_id="home-1", name="Home")- adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="home"))- return runner, adapter---async def _startup_message(runner, adapter) -> str:- delivered = await runner._send_home_channel_startup_notifications()- assert delivered == {("telegram", "home-1", None)}- adapter.send.assert_called_once()- return adapter.send.call_args.args[1]---async def test_guest_inference_adds_exactly_one_free_tier_line(nous_runner):- runner, adapter = nous_runner- _seed_nous(_guest_state())- assert anon_auth.has_free_tier_account()-- message = await _startup_message(runner, adapter)-- lines = message.splitlines()- assert len(lines) == 2 and "free tier" in lines[1].lower()- assert "guest" not in message.lower() and "anonymous" not in message.lower()---async def test_signed_in_account_keeps_the_plain_online_notice(nous_runner):- runner, adapter = nous_runner- _seed_nous(_account_state())- assert not anon_auth.has_free_tier_account()-- message = await _startup_message(runner, adapter)-- assert "free tier" not in message.lower()---async def test_non_nous_provider_never_mentions_the_free_tier(nous_runner, monkeypatch):- runner, adapter = nous_runner- _seed_nous(_guest_state()) # identity exists for connectors, but inference is elsewhere- monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test") # an explicit key wins provider precedence-- message = await _startup_message(runner, adapter)-- assert "free tier" not in message.lower()diff --git a/tests/gateway/test_planned_restart_notice_multiplex.py b/tests/gateway/test_planned_restart_notice_multiplex.pyindex 00805ada192..121b5f6d2e9 100644--- a/tests/gateway/test_planned_restart_notice_multiplex.py+++ b/tests/gateway/test_planned_restart_notice_multiplex.py@@ -50,7 +50,6 @@ def multiplex_runner(tmp_path, monkeypatch):runner.adapters = {}runner._profile_configs = {"coder": _home_config(Platform.TELEGRAM, "coder-home")}runner._profile_adapters = {"coder": {}}- runner._free_tier_startup_line = Mock(return_value=None)runner._planned_restart_notice_lock = Nonemarker = tmp_path / ".restart_pending.json"marker.write_text("{}", encoding="utf-8")@@ -146,7 +145,6 @@ async def test_profiles_sharing_one_home_chat_get_one_notice(tmp_path, monkeypatrunner.adapters = {Platform.TELEGRAM: launch}runner._profile_configs = {"coder": _home_config(Platform.TELEGRAM, "-100999")}runner._profile_adapters = {"coder": {Platform.TELEGRAM: coder}}- runner._free_tier_startup_line = Mock(return_value=None)runner._planned_restart_notice_lock = Nonemarker = tmp_path / ".restart_pending.json"marker.write_text("{}", encoding="utf-8")diff --git a/tests/gateway/test_restart_notice_replay.py b/tests/gateway/test_restart_notice_replay.pyindex a3cfab1a671..ef173d82433 100644--- a/tests/gateway/test_restart_notice_replay.py+++ b/tests/gateway/test_restart_notice_replay.py@@ -53,10 +53,9 @@ def boot_notice(tmp_path, monkeypatch):runner._redeliver_failed_obligations_for_platform = AsyncMock()runner._schedule_resume_pending_sessions = Mock()monkeypatch.setattr("gateway.channel_directory.build_channel_directory", AsyncMock())- # Unrelated conversation recovery and optional account-status text are isolated.+ # Unrelated conversation recovery is isolated.runner._claim_pending_obligations = AsyncMock(return_value=[])runner._redeliver_claimed_obligations = AsyncMock(return_value=0)- runner._free_tier_startup_line = Mock(return_value=None)marker = tmp_path / ".restart_pending.json"marker.write_text("{}", encoding="utf-8")return runner, markerdiff --git a/tests/gateway/test_startup_warmup_profile_scope.py b/tests/gateway/test_startup_warmup_profile_scope.pyindex 0cb491c0dff..a336ce2784c 100644--- a/tests/gateway/test_startup_warmup_profile_scope.py+++ b/tests/gateway/test_startup_warmup_profile_scope.py@@ -88,13 +88,3 @@ def test_single_profile_warmup_keeps_environ_semantics(tmp_path, monkeypatch):assert seen["scope_installed"] is Falseassert seen["portal_override"] == PORTAL--def test_multiplex_free_tier_bootstrap_runs_inside_the_launch_profile_scope(multiplex_home, monkeypatch):- """The free-tier bootstrap mints the Portal identity at boot through the same override; it is the- sibling unscoped executor hop and gets the same binding."""- seen: dict = {}- runner = _Runner(multiplex=True)- runner._start_free_tier_bootstrap = _probe(seen)- asyncio.run(runner._run_free_tier_bootstrap())- assert seen["scope_installed"] is True- assert seen["portal_override"] == PORTALdiff --git a/tests/gateway/test_status_free_tier_line.py b/tests/gateway/test_status_free_tier_line.pydeleted file mode 100644index 9c2d78caa4a..00000000000--- a/tests/gateway/test_status_free_tier_line.py+++ /dev/null@@ -1,105 +0,0 @@-"""The in-chat /status line identifies an active Nous free-tier route."""--import base64-import json-import time-from datetime import datetime--import pytest--from gateway.config import Platform-from gateway.session import SessionEntry, build_session_key-from hermes_cli import anon_auth-from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store-from tests.gateway.test_status_command import _make_event, _make_runner, _make_source--def _runner():- source = _make_source()- entry = SessionEntry(- session_key=build_session_key(source),- session_id="sess-free-tier-status",- created_at=datetime.now(),- updated_at=datetime.now(),- platform=Platform.TELEGRAM,- chat_type="dm",- )- return _make_runner(entry)--def _jwt(**claims) -> str:- def segment(value):- return base64.urlsafe_b64encode(json.dumps(value).encode()).rstrip(b"=").decode()-- payload = {- "sub": "nas_user:status",- "client_id": "nas-anonymous",- "account_tier": "anonymous",- "scope": "inference:invoke",- "exp": int(time.time()) + 900,- **claims,- }- return f"{segment({'alg': 'RS256'})}.{segment(payload)}.sig"--def _seed_nous(state: dict) -> None:- with _auth_store_lock():- store = _load_auth_store()- store.setdefault("providers", {})["nous"] = state- store["active_provider"] = "nous"- _save_auth_store(store)--def _free_tier_state() -> dict:- return {- "auth_method": anon_auth.ANON_AUTH_METHOD,- "account_tier": "anonymous",- "anon_token": "anon_status",- "access_token": _jwt(),- "expires_at": "2999-01-01T00:00:00+00:00",- "inference_base_url": "https://welcome-api.nousresearch.com/v1",- }--def _account_state() -> dict:- return {- "auth_method": "oauth_device_code",- "access_token": _jwt(client_id="hermes-cli", account_tier="standard"),- "refresh_token": "refresh-status",- "expires_at": "2999-01-01T00:00:00+00:00",- }-[email protected](autouse=True)-def isolated_auth_store(tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")--async def test_status_names_the_free_tier_and_the_slash_command_when_the_free_tier_carries_inference(-):- runner = _runner()- _seed_nous(_free_tier_state())-- result = await runner._handle_message(_make_event("/status"))-- assert anon_auth.FREE_TIER_STATUS_LINE in result--async def test_status_omits_the_line_for_a_real_account():- runner = _runner()- _seed_nous(_account_state())-- result = await runner._handle_message(_make_event("/status"))-- assert anon_auth.FREE_TIER_STATUS_LINE not in result--async def test_a_status_gate_failure_never_breaks_status(monkeypatch):- runner = _runner()- _seed_nous(_free_tier_state())- monkeypatch.setattr(anon_auth, "free_tier_route", lambda: False)- expected = await runner._handle_message(_make_event("/status"))-- def broken_store():- raise RuntimeError("broken store")-- monkeypatch.setattr(anon_auth, "free_tier_route", broken_store)-- result = await runner._handle_message(_make_event("/status"))-- assert result == expecteddiff --git a/tests/hermes_cli/test_anon_auth_core.py b/tests/hermes_cli/test_anon_auth_core.pyindex 49cc33c0032..94a260223c2 100644--- a/tests/hermes_cli/test_anon_auth_core.py+++ b/tests/hermes_cli/test_anon_auth_core.py@@ -16,7 +16,7 @@ import pytestfrom hermes_cli import anon_authfrom hermes_cli.auth import _load_auth_store, resolve_provider-from tests.hermes_cli.anon_portal import PORTAL, WELCOME, install_portal, make_jwt as _jwt+from tests.hermes_cli.anon_portal import PORTAL, WELCOME, claimed_trial, install_portal, make_jwt as _jwt@pytest.fixture@@ -39,13 +39,17 @@ def _shared_store(tmp_path) -> dict:class TestIdentityLifecycle:- def test_fresh_install_mints_once_and_resolves_without_claiming_active_provider(self, portal, tmp_path):+ def test_connector_guest_mints_once_and_never_carries_inference(self, portal, tmp_path):+ """``ensure_portal_identity(explicit=True)`` (the connector creator) mints one guest, shared+ through the store, but without the welcome-trial claim it never answers the resolver."""state = anon_auth.ensure_portal_identity(explicit=True)assert anon_auth.is_guest_state(state)assert "refresh_token" not in state+ assert not state.get(anon_auth.WELCOME_CLAIM_FLAG)store = _load_auth_store()assert "active_provider" not in store- assert resolve_provider("auto") == "nous"+ with pytest.raises(anon_auth.AuthError):+ resolve_provider("auto")assert anon_auth.is_guest_state(store["providers"]["nous"])assert _shared_store(tmp_path).get("anon_token") == state["anon_token"]assert portal.minted == 1@@ -84,29 +88,22 @@ class TestIdentityLifecycle:with pytest.raises(anon_auth.AuthError):resolve_provider("auto")- def test_launch_gate_off_means_no_free_tier_at_all(self, portal, monkeypatch):- """Without ``HERMES_GUEST_ONBOARDING=1`` the free tier does not exist: no mint, no portal- traffic, ``nous.guest``'s default is never consulted, and an identity already on disk is- not treated as enabled. The env var is the only lever; ``0``/``true``/anything but ``1`` is off."""- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)- for raw in ("", "0", "true", "yes", "new"):- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", raw)- assert anon_auth.guest_enabled() is False- assert anon_auth.ensure_portal_identity(explicit=True) is None- assert portal.calls == []+ def test_a_claimed_trial_carries_inference_only_on_the_local_desktop_backend(self, portal, monkeypatch):+ claimed_trial(monkeypatch)+ assert resolve_provider("auto") == "nous"+ monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN") # a CLI shell beside the desktop+ assert anon_auth.free_inference_active() is Falsewith pytest.raises(anon_auth.AuthError):resolve_provider("auto")- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")- assert anon_auth.guest_enabled() is Trueclass TestExplicitProvision:- """``ensure_portal_identity(explicit=True)`` is the one creator (the boot bootstrap and the desktop- retry call it). It mints once; every later caller adopts that identity through the shared store,- so two boots never create two identities. ``nous.guest: false`` still wins."""+ """``ensure_portal_identity(explicit=True)`` is the creator under both the welcome-trial claim and+ the connectors path. It mints once; every later caller adopts that identity through the shared+ store, so two callers never create two identities. ``nous.guest: false`` still wins."""def test_provision_mints_once_then_everything_adopts(self, portal, monkeypatch, tmp_path):- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ assert anon_auth.is_guest_state(claimed_trial(monkeypatch))assert portal.minted == 1token = _load_auth_store()["providers"]["nous"]["anon_token"]# A second provision is idempotent, and the runtime now serves nous/welcome on the welcome host.@@ -123,15 +120,6 @@ class TestExplicitProvision:assert adopted and adopted["anon_token"] == tokenassert portal.minted == 1- def test_retired_identity_is_replaced(self, portal, monkeypatch):- anon_auth.ensure_portal_identity(explicit=True)- first = _load_auth_store()["providers"]["nous"]["anon_token"]- portal.dead_tokens.add(first)- from hermes_cli.auth_nous import resolve_nous_runtime_credentials- assert resolve_nous_runtime_credentials(force_refresh=True)["api_key"] # replaced, not refused- assert _load_auth_store()["providers"]["nous"]["anon_token"] != first- assert portal.minted == 2-def test_guest_off_beats_an_explicit_provision(self, portal, monkeypatch):_write_config(monkeypatch, guest=False)assert anon_auth.ensure_portal_identity(explicit=True) is None@@ -147,8 +135,8 @@ class TestExplicitProvision:])def test_preview_full_connectors_rides_the_create_call(self, portal, monkeypatch, raw, body):"""The cohort reaches the account service on the one call that creates the account, as a- real boolean. "1" turns it on, as it does HERMES_GUEST_ONBOARDING, so one bundle command reads- the same for both; an unrecognised value leaves the body empty (the service default)."""+ real boolean. "1" and "true" turn it on, "0" and "false" off; an unrecognised value leaves the+ body empty (the service default)."""if raw is None:monkeypatch.delenv(anon_auth.PREVIEW_FULL_CONNECTORS_ENV, raising=False)else:@@ -159,13 +147,13 @@ class TestExplicitProvision:class TestResolverIsUnchanged:def test_guest_is_last_resort_and_explicit_key_wins(self, portal, monkeypatch):- anon_auth.ensure_portal_identity(explicit=True)+ claimed_trial(monkeypatch)assert resolve_provider("auto") == "nous"monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")assert resolve_provider("auto") == "openrouter"- def test_runtime_routes_to_welcome_host(self, portal):- anon_auth.ensure_portal_identity(explicit=True)+ def test_runtime_routes_to_welcome_host(self, portal, monkeypatch):+ claimed_trial(monkeypatch)from hermes_cli.runtime_provider import resolve_runtime_providerruntime = resolve_runtime_provider()assert runtime["provider"] == "nous"@@ -176,18 +164,18 @@ class TestResolverIsUnchanged:class TestRouteFallback:"""A guest never falls back to the paid host: the gateway cross-refuses an anonymous JWT there."""- def test_exchange_without_inference_url_routes_to_welcome_literal(self, portal):+ def test_exchange_without_inference_url_routes_to_welcome_literal(self, portal, monkeypatch):portal.inference_base_url = None- anon_auth.ensure_portal_identity(explicit=True)+ claimed_trial(monkeypatch)from hermes_cli.runtime_provider import resolve_runtime_providerruntime = resolve_runtime_provider()assert runtime["base_url"].rstrip("/") == WELCOMEstate = _load_auth_store()["providers"]["nous"]assert state["inference_base_url"].rstrip("/") == WELCOME- def test_disallowed_inference_host_heals_to_welcome_literal(self, portal):+ def test_disallowed_inference_host_heals_to_welcome_literal(self, portal, monkeypatch):portal.inference_base_url = "https://welcome-api.staging-nousresearch.com/v1"- anon_auth.ensure_portal_identity(explicit=True)+ claimed_trial(monkeypatch)from hermes_cli.runtime_provider import resolve_runtime_providerruntime = resolve_runtime_provider()assert runtime["base_url"].rstrip("/") == WELCOME@@ -207,8 +195,8 @@ class TestRouteFallback:class TestTokenAcquisitionSeam:- def test_expired_guest_jwt_reexchanges_and_never_hits_oauth_token(self, portal):- anon_auth.ensure_portal_identity(explicit=True)+ def test_expired_guest_jwt_reexchanges_and_never_hits_oauth_token(self, portal, monkeypatch):+ claimed_trial(monkeypatch)from hermes_cli.auth import _auth_store_lock, _save_auth_storewith _auth_store_lock():store = _load_auth_store()@@ -224,15 +212,16 @@ class TestTokenAcquisitionSeam:assert creds["base_url"].rstrip("/") == WELCOMEassert "quarantine" not in json.dumps(_load_auth_store())- def test_dead_credential_is_replaced_by_a_fresh_identity(self, portal):- first = anon_auth.ensure_portal_identity(explicit=True)+ def test_dead_credential_is_retired_and_never_replaced(self, portal, monkeypatch):+ """The trial is claimed once per machine: a guest NAS no longer knows is cleared and the+ error surfaces; inference never mints a replacement."""+ first = claimed_trial(monkeypatch)portal.dead_tokens.add(first["anon_token"])from hermes_cli.auth_nous import resolve_nous_runtime_credentials- creds = resolve_nous_runtime_credentials(force_refresh=True)- assert creds["api_key"]- state = _load_auth_store()["providers"]["nous"]- assert state["anon_token"] != first["anon_token"]- assert portal.minted == 2+ with pytest.raises(anon_auth.AnonCredentialDead):+ resolve_nous_runtime_credentials(force_refresh=True)+ assert "nous" not in _load_auth_store().get("providers", {})+ assert portal.minted == 1def test_tool_gateway_token_path_reexchanges(self, portal):anon_auth.ensure_portal_identity(explicit=True)@@ -328,33 +317,41 @@ class TestRotationNeverRewritesTheConversationModel:assert ok is True and agent.model == anon_auth.GUEST_MODEL-class TestBootstrapIsTheOneCreator:- """``free_tier_bootstrap.run_bootstrap`` is the only place an identity is created. Every other- site is a read. One mint per process; the record says who carries inference."""+class TestBootstrapNeverCreates:+ """``free_tier_bootstrap.run_bootstrap`` only records who carries inference: it never mints.+ The welcome-trial claim and the connectors path are the creators; every other site is a read."""def _fresh(self):from hermes_cli import free_tier_bootstrap as fbfb.reset_for_tests()return fb- def test_bootstrap_mints_once_records_and_a_second_run_is_free(self, portal):+ def test_bootstrap_on_a_fresh_machine_mints_nothing(self, portal, monkeypatch):+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)+ from tests.hermes_cli.anon_portal import as_local_desktop_backend+ as_local_desktop_backend(monkeypatch) # the trial is claimable here; boot still never claims it+ record = self._fresh().run_bootstrap(announce=False)+ assert record.has_identity is False and record.free_tier_account is False+ assert portal.calls == [], "boot never reaches the portal"++ def test_bootstrap_records_a_claimed_trial_and_a_second_run_is_free(self, portal, monkeypatch):+ claimed_trial(monkeypatch)fb = self._fresh()- record = fb.run_bootstrap()+ record = fb.run_bootstrap(announce=False)assert record.free_tier_account and record.has_identity and record.provider_configuredassert record.inference_provider == "nous" and record.other_providers is False- assert portal.minted == 1- again = fb.run_bootstrap()- assert again is record and portal.minted == 1, "a second boot in the same process adopts, never mints"+ again = fb.run_bootstrap(announce=False)+ assert again is record and portal.minted == 1assert fb.wait_for_record(timeout=0) is record- def test_own_key_keeps_inference_and_the_identity_stays_off_active_provider(self, portal, monkeypatch):+ def test_own_key_keeps_inference_and_a_connector_guest_stays_off_active_provider(self, portal, monkeypatch):+ anon_auth.ensure_portal_identity(explicit=True)monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-own-key")- fb = self._fresh()- record = fb.run_bootstrap()+ record = self._fresh().run_bootstrap(announce=False)assert record.other_providers is True and record.has_identity is True- assert record.free_tier_account is True, "the identity exists for connectors"- assert record.inference_provider != "nous"- assert _load_auth_store().get("active_provider") != "nous", "a mint beside an own key must not hijack inference"+ assert record.free_tier_account is False, "a connector guest does not carry inference"+ assert record.inference_provider == "openrouter"+ assert _load_auth_store().get("active_provider") != "nous"assert portal.minted == 1def test_reads_never_mint(self, portal, monkeypatch):@@ -372,18 +369,6 @@ class TestBootstrapIsTheOneCreator:with pytest.raises(ValueError):anon_auth.ensure_portal_identity(explicit=False)- def test_bootstrap_with_the_gate_closed_records_the_refusal_and_stops(self, portal, monkeypatch):- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)- portal.gate_closed = True- fb = self._fresh()- record = fb.run_bootstrap()- assert record.has_identity is False and record.free_tier_account is False and record.error- assert [p for _, p in portal.calls].count("/api/anonymous/create") == 1- # The explicit retry (desktop free_tier.provision) is also memoised for the process.- assert anon_auth.ensure_portal_identity(explicit=True) is None- assert [p for _, p in portal.calls].count("/api/anonymous/create") == 1--class TestIdentityOfRecordIsTheSharedStore:def test_stale_profile_guest_adopts_a_newer_shared_account(self, portal, tmp_path):anon_auth.ensure_portal_identity(explicit=True)@@ -398,8 +383,8 @@ class TestIdentityOfRecordIsTheSharedStore:assert _load_auth_store()["providers"]["nous"]["refresh_token"] == "rt-sibling"assert _shared_store(tmp_path)["refresh_token"] == "rt-sibling", "the profile must never overwrite the shared account"- def test_mint_persists_before_any_exchange_and_first_use_exchanges_once(self, portal):- first = anon_auth.ensure_portal_identity(explicit=True)+ def test_mint_persists_before_any_exchange_and_first_use_exchanges_once(self, portal, monkeypatch):+ first = claimed_trial(monkeypatch)assert anon_auth.is_guest_state(first) and "access_token" not in firstassert [p for _, p in portal.calls] == ["/api/anonymous/create"], "mint alone; exchange is lazy"from hermes_cli.auth_nous import resolve_nous_runtime_credentials@@ -443,10 +428,8 @@ class TestIdentityOfRecordIsTheSharedStore:class TestConnectorTokenPath:def test_opt_out_hides_the_free_tier_from_connectors_including_cached_tokens(self, portal, monkeypatch):anon_auth.ensure_portal_identity(explicit=True)- from hermes_cli.auth_nous import resolve_nous_runtime_credentials- resolve_nous_runtime_credentials() # now a cached, valid JWT existsfrom tools import managed_tool_gateway as mtg- assert mtg.read_nous_access_token()+ assert mtg.read_nous_access_token() # now a cached, valid JWT exists_write_config(monkeypatch, guest=False)assert mtg.peek_nous_access_token() is Noneassert mtg.read_nous_access_token() is Nonediff --git a/tests/hermes_cli/test_anon_challenge.py b/tests/hermes_cli/test_anon_challenge.pyindex 6cf2d050f67..750d569dcae 100644--- a/tests/hermes_cli/test_anon_challenge.py+++ b/tests/hermes_cli/test_anon_challenge.py@@ -11,7 +11,7 @@ import pytestfrom hermes_cli import anon_auth, anon_challenge-from tests.hermes_cli.anon_portal import PORTAL, install_portal+from tests.hermes_cli.anon_portal import PORTAL, claimed_trial, install_portal@pytest.fixture@@ -32,15 +32,24 @@ def _desktop_backend(monkeypatch):monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", "spawn-token")-def _resolve():+def _resolve(monkeypatch):+ """A free-model call: only a guest that claimed the welcome trial on the desktop's local backend+ mints an inference token."""from hermes_cli.auth_nous import resolve_nous_runtime_credentials- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ claimed_trial(monkeypatch)return resolve_nous_runtime_credentials()+def _connectors_token():+ """A connectors / managed-tool token read: the one exchange a terminal guest makes."""+ from hermes_cli.auth import resolve_nous_access_token+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ return resolve_nous_access_token()++class TestWhatTheClientSends:def test_the_exchange_reports_surface_version_and_the_browser_capability(self, nas):- _resolve()+ _connectors_token()sent = nas.token_requests[-1]assert sent["body"]["client"]["capabilities"] == ["browser-v1"]assert sent["body"]["client"]["surface"] == "cli"@@ -56,7 +65,7 @@ class TestRequiredChallenge:assert anon_challenge.record_host_outcome(challenge.url, challenge.attempt, "error")monkeypatch.setattr(anon_challenge, "present", failed)with pytest.raises(anon_auth.AuthError, match="couldn't finish"):- _resolve()+ _resolve(monkeypatch)assert [p for _, p in nas.calls].count("/api/anonymous/token") == 2assert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") == 1# A window that crashed is not a reason to let a boot burst of callers each re-mint and@@ -66,7 +75,7 @@ class TestRequiredChallenge:resolve_nous_runtime_credentials()assert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") == 1- def test_a_poll_the_service_refuses_ends_the_wait_instead_of_running_out_the_clock(self, nas, presented):+ def test_a_poll_the_service_refuses_ends_the_wait_instead_of_running_out_the_clock(self, nas, presented, monkeypatch):"""404 ``unknown_token`` / 400 on the status poll: the credential is gone (or the surface isoff), so no amount of waiting clears it. The wait ends and the re-mint says what happened."""nas.challenge_required = True@@ -81,7 +90,7 @@ class TestRequiredChallenge:return original(request)nas.handler = refuse_once_pending_is_spentwith pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIREDassert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") == 2@@ -90,7 +99,7 @@ class TestRequiredChallenge:not under a fresh default context that would fail every read and run out the clock."""from hermes_cli import auth_nousfrom hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ claimed_trial(monkeypatch)with _auth_store_lock():store = _load_auth_store()store["providers"]["nous"]["tls"] = {"insecure": True}@@ -117,13 +126,13 @@ class TestRequiredChallenge:nas.challenge_required = Falsereturn responsenas.handler = cleared_after_status- assert _resolve()["api_key"]+ assert _resolve(monkeypatch)["api_key"]assert [p for _, p in nas.calls].count("/api/anonymous/token") == 2assert anon_challenge.pending_challenge() is None- def test_a_challenge_is_presented_polled_and_the_exchange_retried(self, nas, presented):+ def test_a_challenge_is_presented_polled_and_the_exchange_retried(self, nas, presented, monkeypatch):nas.challenge_required = Truenas.challenge_statuses = ["pending", "pending", "needs_interaction"]- creds = _resolve()+ creds = _resolve(monkeypatch)assert creds["api_key"]assert [c.url for c in presented] == [nas.challenge_url]assert presented[0].required and presented[0].message == "A quick check first."@@ -143,7 +152,7 @@ class TestRequiredChallenge:with _nous_shared_store_lock(timeout_seconds=0.5):passmonkeypatch.setattr(anon_challenge, "present", present)- assert _resolve()["api_key"]+ assert _resolve(monkeypatch)["api_key"]def test_a_challenge_that_never_clears_is_a_retryable_error_not_a_hang(self, nas, presented, monkeypatch):nas.challenge_required = True@@ -151,7 +160,7 @@ class TestRequiredChallenge:monkeypatch.setattr(anon_challenge, "CHALLENGE_WAIT_SECONDS", 0.05)monkeypatch.setattr(anon_challenge, "_sleep", lambda _seconds: __import__("time").sleep(0.02))with pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIRED and exc.value.retryable is Trueassert "browser" in str(exc.value)# The callers queued behind it fail fast instead of each parking for a full wait.@@ -160,7 +169,7 @@ class TestRequiredChallenge:resolve_nous_runtime_credentials()assert len(presented) == 1- def test_a_second_challenge_after_the_retry_is_not_looped_on(self, nas, presented):+ def test_a_second_challenge_after_the_retry_is_not_looped_on(self, nas, presented, monkeypatch):nas.challenge_required = Truenas.challenge_statuses = ["failed"] # the page ruled; the ticket left the waiting states@@ -172,7 +181,7 @@ class TestRequiredChallenge:return responsenas.handler = still_challengedwith pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIREDassert [p for _, p in nas.calls].count("/api/anonymous/token") == 2@@ -188,10 +197,10 @@ class TestRequiredChallenge:class TestWhoWaits:- def test_a_background_caller_announces_and_returns_at_once(self, nas, presented):+ def test_a_background_caller_announces_and_returns_at_once(self, nas, presented, monkeypatch):"""A keepalive tick or a status paint has nobody waiting on it: no poll, no parked thread."""from hermes_cli.auth_nous import resolve_nous_runtime_credentials- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ claimed_trial(monkeypatch)nas.challenge_required = Truenas.challenge_never_clears = Truewith anon_challenge.background_caller():@@ -203,16 +212,17 @@ class TestWhoWaits:assert anon_challenge.pending_challenge()["url"] == nas.challenge_urldef test_the_messaging_gateway_never_waits_on_a_challenge(self, nas, presented, monkeypatch):- """Nobody sits at a gateway's console, and its token reads can run on the event loop."""+ """Nobody sits at a gateway's console, and its token reads can run on the event loop. (A+ gateway never carries the free model, so its only challenged exchange is a managed-tool+ token against a NAS from before the connectors purpose.)"""from gateway import status- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))monkeypatch.setattr(status, "owns_gateway_runtime_lock", lambda: True)monkeypatch.setattr(anon_challenge, "CHALLENGE_WAIT_SECONDS", 0.05)+ nas.honours_purpose = Falsenas.challenge_required = Truenas.challenge_never_clears = True- from hermes_cli.auth_nous import resolve_nous_runtime_credentialswith pytest.raises(anon_auth.AuthError) as exc:- resolve_nous_runtime_credentials()+ _connectors_token()assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIRED and exc.value.retryable is Trueassert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]@@ -234,12 +244,12 @@ class TestWhoWaits:_compute_nous_auth_status()assert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]- def test_a_poll_error_is_a_blip_not_a_verdict(self, nas, presented):+ def test_a_poll_error_is_a_blip_not_a_verdict(self, nas, presented, monkeypatch):nas.challenge_required = Truenas.challenge_status_errors = [429] # the "is it already settled?" readnas.challenge_statuses = ["pending"]nas.challenge_status_errors += [500]- assert _resolve()["api_key"]+ assert _resolve(monkeypatch)["api_key"]assert len(presented) == 1 # the 429 did not skip presentingdef test_an_inherited_desktop_flag_is_not_the_desktop_surface(self, nas, monkeypatch, capsys):@@ -250,7 +260,7 @@ class TestWhoWaits:monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)monkeypatch.setenv("SSH_TTY", "/dev/pts/0")monkeypatch.setattr(webbrowser, "open", lambda _url: False)- _resolve()+ _connectors_token()assert nas.token_requests[-1]["body"]["client"]["surface"] == "cli"anon_challenge.present(anon_challenge.BrowserChallenge(f"{PORTAL}/challenge?code=t", True, 600, 2, "m"))assert f"{PORTAL}/challenge?code=t" in capsys.readouterr().err@@ -277,11 +287,11 @@ class TestOtherEndpointsAreUnchanged:class TestWhatIsNeverOpened:- def test_a_challenge_url_off_the_portal_origin_is_refused(self, nas, presented):+ def test_a_challenge_url_off_the_portal_origin_is_refused(self, nas, presented, monkeypatch):nas.challenge_required = Truenas.challenge_url = "https://evil.example/challenge?code=x"with pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED and exc.value.retryable is Falseassert presented == []@@ -292,27 +302,27 @@ class TestWhatIsNeverOpened:payload = {"challenges": [{"type": "browser", "url": url}]}assert anon_challenge.parse_browser_challenge(payload, PORTAL) is None- def test_an_unknown_challenge_type_falls_back_to_sign_in(self, nas, presented):+ def test_an_unknown_challenge_type_falls_back_to_sign_in(self, nas, presented, monkeypatch):nas.token_response = httpx.Response(428, json={"error": "challenge_required", "message": "Attest your device.","challenges": [{"type": "attestation-v9", "url": f"{PORTAL}/x"}]})with pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIREDassert "Sign in" in str(exc.value) and "Attest" not in str(exc.value)- def test_an_unknown_428_is_a_sign_in_not_the_proof_of_work_sentence(self, nas):+ def test_an_unknown_428_is_a_sign_in_not_the_proof_of_work_sentence(self, nas, monkeypatch):nas.token_response = httpx.Response(428, json={"error": "something_new"})with pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIREDassert "proof of work" not in str(exc.value)@pytest.mark.parametrize("error", ["signin_required", "access_denied"])- def test_a_refusal_uses_the_services_own_words(self, nas, error):+ def test_a_refusal_uses_the_services_own_words(self, nas, error, monkeypatch):nas.token_response = httpx.Response(403, json={"error": error, "message": "Not from here, sorry."})with pytest.raises(anon_auth.AuthError) as exc:- _resolve()+ _resolve(monkeypatch)assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED and str(exc.value) == "Not from here, sorry."def test_network_numbers_are_kept_finite_and_sane(self):@@ -335,16 +345,16 @@ class TestOptionalChallenge:def test_a_terminal_never_opens_anything_for_an_optional_challenge(self, nas, presented, monkeypatch):announced = []monkeypatch.setattr(anon_challenge, "_announce", announced.append)+ nas.honours_purpose = False # an inference-scoped grant: the one that carries the offernas.optional_challenge = True- assert _resolve()["api_key"]+ assert _connectors_token()assert presented == [] and announced == []def test_the_desktop_backend_announces_it_and_waits_on_nothing(self, nas, presented, monkeypatch):announced = []monkeypatch.setattr(anon_challenge, "_announce", announced.append)- _desktop_backend(monkeypatch)nas.optional_challenge = True- assert _resolve()["api_key"]+ assert _resolve(monkeypatch)["api_key"]assert [c.required for c in announced] == [False]assert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]assert anon_challenge.pending_challenge()["url"] == nas.challenge_urldiff --git a/tests/hermes_cli/test_anon_connectors_token.py b/tests/hermes_cli/test_anon_connectors_token.pyindex b0411d63c44..efc0be1a84d 100644--- a/tests/hermes_cli/test_anon_connectors_token.py+++ b/tests/hermes_cli/test_anon_connectors_token.py@@ -20,16 +20,25 @@ from hermes_cli import anon_auth, anon_challengefrom hermes_cli import auth as auth_modfrom hermes_cli.auth_nous import resolve_nous_runtime_credentials-from tests.hermes_cli.anon_portal import WELCOME, install_portal, make_jwt+from tests.hermes_cli.anon_portal import WELCOME, claimed_trial, install_portal, make_jwt@pytest.fixturedef nas(monkeypatch, tmp_path):+ """A connectors-only guest: the free model is not active for it."""fake = install_portal(monkeypatch, tmp_path)assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))return fake+def trial(monkeypatch, tmp_path):+ """A guest that claimed the welcome trial on the desktop's local backend: the free model is live."""+ fake = install_portal(monkeypatch, tmp_path)+ claimed_trial(monkeypatch)+ return fake++@pytest.fixturedef presented(monkeypatch):seen: list[anon_challenge.BrowserChallenge] = []@@ -110,8 +119,9 @@ class TestConnectorsCallers:assert auth_mod.resolve_nous_access_token() == tokenassert len(nas.token_requests) == 1- def test_account_reads_use_the_connectors_token(self, nas, presented):+ def test_account_reads_use_the_connectors_token(self, trial, presented):from hermes_cli.nous_account import get_nous_portal_account_info, reset_nous_portal_account_info_cache+ nas = trialnas.challenge_required = Trueauth_mod.resolve_nous_access_token()reset_nous_portal_account_info_cache()@@ -129,7 +139,8 @@ class TestConnectorsCallers:class TestInferenceCallers:- def test_still_work_the_challenge_and_never_take_the_connectors_token(self, nas, presented):+ def test_still_work_the_challenge_and_never_take_the_connectors_token(self, trial, presented):+ nas = trialconnectors = auth_mod.resolve_nous_access_token()nas.challenge_required = Truenas.challenge_statuses = ["pending"]@@ -138,15 +149,17 @@ class TestInferenceCallers:assert [c.url for c in presented] == [nas.challenge_url]assert _purposes(nas) == ["connectors", "inference", "inference"]- def test_a_held_inference_token_satisfies_connectors_callers(self, nas, monkeypatch):+ def test_a_held_inference_token_satisfies_connectors_callers(self, trial, monkeypatch):+ nas = trialcreds = resolve_nous_runtime_credentials()_forget_memo(monkeypatch)assert auth_mod.resolve_nous_access_token() == creds["api_key"]assert len(nas.token_requests) == 1- def test_a_connectors_mint_leaves_a_pending_inference_challenge_alone(self, nas, presented):+ def test_a_connectors_mint_leaves_a_pending_inference_challenge_alone(self, trial, presented):"""The connectors grant says nothing about the inference check: the desktop's hidden windowmust keep the ticket it was handed."""+ nas = trialnas.challenge_required = Truenas.challenge_never_clears = Truewith anon_challenge.background_caller(), pytest.raises(anon_auth.AuthError):@@ -155,8 +168,9 @@ class TestInferenceCallers:auth_mod.resolve_nous_access_token()assert anon_challenge.pending_challenge()["url"] == nas.challenge_url- def test_a_connectors_caller_never_queues_behind_an_inference_challenge(self, nas, monkeypatch):+ def test_a_connectors_caller_never_queues_behind_an_inference_challenge(self, trial, monkeypatch):"""The wait runs outside the auth locks and its work lock is the inference mint's alone."""+ nas = trialnas.challenge_required = Truenas.challenge_statuses = ["pending"]during_wait: list[str] = []@@ -171,7 +185,8 @@ class TestInferenceCallers:assert [_scope(t) for t in during_wait] == ["connectors:invoke"]def test_an_inference_give_up_cooldown_does_not_fail_connectors_callers_fast(- self, nas, presented, monkeypatch):+ self, trial, presented, monkeypatch):+ nas = trialnas.challenge_required = Truenas.challenge_never_clears = Truemonkeypatch.setattr(anon_challenge, "CHALLENGE_WAIT_SECONDS", 0)@@ -184,6 +199,14 @@ class TestInferenceCallers:class TestNoInferenceIntent:"""Paths that are not a free-model call never mint inference in the foreground or on a timer."""+ def test_a_connectors_only_guest_never_mints_inference(self, nas, presented):+ """Without a claimed trial the free model is not this guest's: the inference path refuses+ before any exchange, and the identity stays for connectors."""+ with pytest.raises(anon_auth.AuthError):+ resolve_nous_runtime_credentials()+ assert nas.token_requests == [] and presented == []+ assert anon_auth.is_guest_state(anon_auth.current_nous_state())+def test_the_keepalive_never_mints_for_a_guest(self, nas):from hermes_cli.nous_auth_keepalive import refresh_nous_auth_keepalive_onceauth_mod.resolve_nous_access_token()@@ -201,7 +224,8 @@ class TestNoInferenceIntent:class TestOlderNas:"""A NAS from before #1516 drops the unknown ``purpose`` key and mints today's token."""- def test_an_inference_token_for_a_connectors_mint_fills_the_inference_slot(self, nas, monkeypatch):+ def test_an_inference_token_for_a_connectors_mint_fills_the_inference_slot(self, trial, monkeypatch):+ nas = trialnas.honours_purpose = Falsetoken = auth_mod.resolve_nous_access_token()assert _scope(token) == "inference:invoke"@@ -219,7 +243,8 @@ class TestOlderNas:class TestPersistedState:- def test_state_written_by_current_releases_loads_unchanged(self, nas):+ def test_state_written_by_current_releases_loads_unchanged(self, trial):+ nas = trialfrom tools.managed_tool_gateway import peek_nous_access_tokentoken = _persist_guest_tokens(inference=900)["inference"]assert peek_nous_access_token() == tokendiff --git a/tests/hermes_cli/test_anon_desktop_signin.py b/tests/hermes_cli/test_anon_desktop_signin.pyindex 45d366a8c41..e7c6c4a5888 100644--- a/tests/hermes_cli/test_anon_desktop_signin.py+++ b/tests/hermes_cli/test_anon_desktop_signin.py@@ -16,6 +16,7 @@ from fastapi.testclient import TestClientfrom hermes_cli import anon_authfrom hermes_cli.auth import _load_auth_storefrom hermes_cli.web_server import _SESSION_TOKEN, app+from tests.hermes_cli.anon_portal import as_local_desktop_backend, claimed_trialfrom tests.hermes_cli.test_anon_upgrade import (EMAIL, FREE_PICK, INFERENCE, PORTAL, WELCOME, _model_config, _write_model_config, free_account, portal)@@ -73,8 +74,8 @@ def test_a_transfer_the_user_declined_is_reported_with_its_reason_and_keeps_the_assert _load_auth_store()["providers"]["nous"]["anon_token"] == guest["anon_token"]-def test_status_routes_report_the_free_tier(portal):- anon_auth.ensure_portal_identity(explicit=True)+def test_status_routes_report_the_free_tier(portal, monkeypatch):+ claimed_trial(monkeypatch)portal_status = client.get("/api/portal", headers=HEADERS).json()assert portal_status["free_tier"] is Trueassert portal_status["account_tier"] == "anonymous"@@ -83,6 +84,15 @@ def test_status_routes_report_the_free_tier(portal):assert nous["status"]["free_tier"] is True+def test_a_connector_only_guest_is_not_reported_as_the_free_tier(portal, monkeypatch):+ as_local_desktop_backend(monkeypatch)+ anon_auth.ensure_portal_identity(explicit=True)+ assert client.get("/api/portal", headers=HEADERS).json()["free_tier"] is False+ providers = client.get("/api/providers/oauth", headers=HEADERS).json()["providers"]+ nous = next(p for p in providers if p["id"] == "nous")+ assert not nous["status"].get("free_tier")++def test_a_sign_in_cancelled_while_waiting_never_persists_the_account(portal, free_account, monkeypatch):"""The poller is blocked on the transfer when the user cancels; when the wait returns completed,nothing may reach the auth store."""diff --git a/tests/hermes_cli/test_anon_failure_modes.py b/tests/hermes_cli/test_anon_failure_modes.pyindex 8c98937b26e..923cfa13a18 100644--- a/tests/hermes_cli/test_anon_failure_modes.py+++ b/tests/hermes_cli/test_anon_failure_modes.py@@ -15,7 +15,7 @@ import pytestfrom hermes_cli import anon_auth, anon_sign_in, free_tier_bootstrapfrom hermes_cli.auth import _load_auth_store-from tests.hermes_cli.anon_portal import PORTAL, WELCOME, install_portal+from tests.hermes_cli.anon_portal import PORTAL, WELCOME, as_local_desktop_backend, claimed_trial, install_portal@pytest.fixture@@ -29,10 +29,10 @@ def _mint_error(nas) -> anon_auth.AuthError:return exc.value-def _exchange_error(nas) -> anon_auth.AuthError:- """Mint (the credential is persisted before any exchange), then exchange it at first use."""+def _exchange_error(nas, monkeypatch) -> anon_auth.AuthError:+ """Claim the trial (the credential is persisted before any exchange), then exchange it at first use."""from hermes_cli.auth_nous import resolve_nous_runtime_credentials- assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ assert anon_auth.is_guest_state(claimed_trial(monkeypatch))with pytest.raises(anon_auth.AuthError) as exc:resolve_nous_runtime_credentials()return exc.value@@ -70,9 +70,9 @@ class TestNasRefusalCodes:assert "about a minute" in str(err)assert anon_auth.last_mint_failure()["retry_after"] == 42- def test_proof_of_work_is_deferred_with_the_agreed_sentence(self, nas):+ def test_proof_of_work_is_deferred_with_the_agreed_sentence(self, nas, monkeypatch):nas.token_response = httpx.Response(428, json={"error": "pow_required", "pow": {"bits": 31}})- err = _exchange_error(nas)+ err = _exchange_error(nas, monkeypatch)assert err.code == anon_auth.ANON_POW_REQUIRED and err.retryable is Falseassert "proof of work" in str(err)# The credential from ``create`` is kept, so a later NAS without PoW exchanges it instead@@ -80,9 +80,9 @@ class TestNasRefusalCodes:assert anon_auth.is_guest_state(_load_auth_store()["providers"]["nous"])assert nas.creates() == 1- def test_locked_account_is_dead_and_never_replaced(self, nas):+ def test_locked_account_is_dead_and_never_replaced(self, nas, monkeypatch):nas.token_response = httpx.Response(403, json={"error": "account_locked"})- err = _exchange_error(nas)+ err = _exchange_error(nas, monkeypatch)assert isinstance(err, anon_auth.AnonCredentialDead)assert err.code == anon_auth.ANON_ACCOUNT_LOCKED# Retired, and NOT replaced by a fresh identity: the way forward is a sign-in.@@ -104,26 +104,6 @@ class TestNasRefusalCodes:assert "nous" not in _load_auth_store().get("providers", {})assert nas.creates() == 1- def test_unknown_token_is_replaced_once_at_first_use(self, nas):- from hermes_cli.auth_nous import resolve_nous_runtime_credentials- first = anon_auth.ensure_portal_identity(explicit=True)- original = nas.handler-- def _first_only(request):- # Only the FIRST credential is dead; its replacement exchanges normally.- if request.url.path == "/api/anonymous/token" and json.loads(request.content)["token"] == first["anon_token"]:- nas.calls.append((request.method, request.url.path))- return httpx.Response(404, json={"error": "unknown_token"})- return original(request)- nas.handler = _first_only # type: ignore[method-assign]- try:- creds = resolve_nous_runtime_credentials()- finally:- nas.handler = original # type: ignore[method-assign]- assert creds["base_url"].startswith(WELCOME)- assert nas.creates() == 2- assert _load_auth_store()["providers"]["nous"]["anon_token"] != first["anon_token"]-def test_a_5xx_or_non_json_body_is_a_retryable_server_error(self, nas):nas.create_response = httpx.Response(500, text="<html>oops</html>")err = _mint_error(nas)@@ -190,13 +170,23 @@ class TestMintCooldown:assert anon_auth.ensure_portal_identity(explicit=True) is None # and still terminal-# --- The boot record and its retries -------------------------------------------------------------+# --- The boot record ----------------------------------------------------------------------------+++def _failed_claim(nas, monkeypatch) -> anon_auth.AuthError:+ """The desktop's welcome-trial claim, refused by the service (boot itself never mints)."""+ from hermes_cli import welcome_trial+ as_local_desktop_backend(monkeypatch)+ with pytest.raises(anon_auth.AuthError) as exc:+ welcome_trial.claim_desktop_free_tier()+ return exc.valueclass TestBootstrapRecord:- def test_the_record_carries_the_code_and_the_wait(self, nas):+ def test_the_record_carries_the_failed_claims_code_and_wait(self, nas, monkeypatch):nas.create_response = httpx.Response(429, json={"error": "temporarily_unavailable"}, headers={"Retry-After": "30"})+ _failed_claim(nas, monkeypatch)record = free_tier_bootstrap.run_bootstrap(announce=False)assert record.has_identity is False and record.free_tier_account is Falseassert record.failure["error_code"] == anon_auth.ANON_RATE_LIMITED@@ -204,80 +194,31 @@ class TestBootstrapRecord:assert record.failure_fields() == {"error": record.error, "error_code": anon_auth.ANON_RATE_LIMITED, "retryable": True,"retry_after": record.failure["retry_after"]}+ assert nas.creates() == 1, "the boot record never retries the mint"- def test_a_clean_boot_carries_no_failure_block(self, nas):+ def test_a_claimed_trial_carries_no_failure_block(self, nas, monkeypatch):+ claimed_trial(monkeypatch)record = free_tier_bootstrap.run_bootstrap(announce=False)assert record.free_tier_account is True and record.failure_fields() == {}- def test_the_background_loop_retries_a_transient_failure_until_it_settles(self, nas, monkeypatch):- nas.raise_transport = httpx.ConnectTimeout("no route")- slept = []-- def _sleep(seconds):- slept.append(seconds)- # The cooldown passes while we "slept".- failure = anon_auth._mint_failure_for_profile()- monkeypatch.setattr(anon_auth.time, "monotonic", lambda f=failure: f.not_before + 1)- if len(slept) == 2:- nas.raise_transport = None # the network comes back on the second wait- monkeypatch.setattr(free_tier_bootstrap, "_sleep", _sleep)- free_tier_bootstrap._bootstrap_then_retry()- record = free_tier_bootstrap.current_record()- assert record.has_identity is True and record.free_tier_account is True- assert slept == [int(w) for w in anon_auth._MINT_RETRY_LADDER[:2]]- assert nas.creates() == 3-- def test_the_background_loop_never_retries_a_terminal_code(self, nas, monkeypatch):- nas.create_response = httpx.Response(404, json={"error": "not_found"})- monkeypatch.setattr(free_tier_bootstrap, "_sleep", lambda s: pytest.fail("must not sleep"))- free_tier_bootstrap._bootstrap_then_retry()- assert free_tier_bootstrap.current_record().failure["error_code"] == anon_auth.ANON_GATE_CLOSED- assert nas.creates() == 1-- def test_the_background_loop_is_bounded(self, nas, monkeypatch):- nas.raise_transport = httpx.ConnectTimeout("no route")-- def _sleep(seconds):- failure = anon_auth._mint_failure_for_profile()- monkeypatch.setattr(anon_auth.time, "monotonic", lambda f=failure: f.not_before + 1)- monkeypatch.setattr(free_tier_bootstrap, "_sleep", _sleep)- free_tier_bootstrap._bootstrap_then_retry()- assert nas.creates() == 1 + free_tier_bootstrap.BOOTSTRAP_RETRY_ATTEMPTS- assert free_tier_bootstrap.current_record().failure["error_code"] == anon_auth.ANON_UNREACHABLE-- def test_a_retry_re_inventories_so_a_provider_connected_meanwhile_keeps_inference(self, nas, monkeypatch):+ def test_a_refresh_re_inventories_so_a_provider_connected_meanwhile_keeps_inference(self, nas, monkeypatch):nas.raise_transport = httpx.ConnectTimeout("no route")+ _failed_claim(nas, monkeypatch)free_tier_bootstrap.run_bootstrap(announce=False)# The user connected their own provider during the cooldown.monkeypatch.setattr(free_tier_bootstrap, "_inventory_other_providers", lambda: True)- nas.raise_transport = None- record = free_tier_bootstrap.retry_bootstrap_mint(force=True, announce=False)- assert record.has_identity is True and record.other_providers is True+ record = free_tier_bootstrap.refresh_record(announce=False)+ assert record.other_providers is True and record.provider_configured is Trueassert _load_auth_store().get("active_provider") != "nous"- def test_a_late_failed_build_never_overwrites_a_success_that_landed_meanwhile(self, nas, monkeypatch):- """The background loop and the user's click can race: the loop's build (no identity, still- in cooldown) must not replace the record the click just wrote."""- nas.raise_transport = httpx.ConnectTimeout("no route")- free_tier_bootstrap.run_bootstrap(announce=False)- real_build = free_tier_bootstrap._build_record-- def slow_build(**kw):- stale = real_build(**kw) # no identity: still inside the cooldown- monkeypatch.setattr(free_tier_bootstrap, "_build_record", real_build)- nas.raise_transport = None # ...meanwhile the click's forced mint succeeds- free_tier_bootstrap.retry_bootstrap_mint(force=True, announce=False)- return stale- monkeypatch.setattr(free_tier_bootstrap, "_build_record", slow_build)- record = free_tier_bootstrap.retry_bootstrap_mint(force=False, announce=False)- assert record.has_identity is True- assert free_tier_bootstrap.current_record().has_identity is True-- def test_the_desktop_retry_refreshes_the_boot_record(self, nas):+ def test_the_desktop_retry_refreshes_the_boot_record(self, nas, monkeypatch):+ from hermes_cli import welcome_trialnas.raise_transport = httpx.ConnectTimeout("no route")+ _failed_claim(nas, monkeypatch)free_tier_bootstrap.run_bootstrap(announce=False)nas.raise_transport = None- record = free_tier_bootstrap.retry_bootstrap_mint(force=True, announce=False)+ assert welcome_trial.claim_desktop_free_tier(force=True) is not None # the user's retry+ record = free_tier_bootstrap.refresh_record(announce=False)assert record.free_tier_account is True and record.failure_fields() == {}assert free_tier_bootstrap.current_record() is recorddiff --git a/tests/hermes_cli/test_anon_first_notice.py b/tests/hermes_cli/test_anon_first_notice.pyindex d5b091b02f3..543ccdfdaaf 100644--- a/tests/hermes_cli/test_anon_first_notice.py+++ b/tests/hermes_cli/test_anon_first_notice.py@@ -1,4 +1,4 @@-"""CLI one-time notice: an explicit-provider install learns once that the Nous free tier exists."""+"""The one-time free-tier notice flag: pending once for a guest that carries the trial, then never again."""import base64import json@@ -8,7 +8,7 @@ import pytestfrom hermes_cli import anon_authfrom hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store-from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin+from tests.hermes_cli.anon_portal import as_local_desktop_backend, claimed_trial, install_portaldef _jwt(**claims) -> str:@@ -19,74 +19,36 @@ def _jwt(**claims) -> str:return f"{seg({'alg': 'RS256'})}.{seg(payload)}.sig"-def _seed_guest() -> None:- with _auth_store_lock():- store = _load_auth_store()- store.setdefault("providers", {})["nous"] = {- "auth_method": anon_auth.ANON_AUTH_METHOD, "account_tier": "anonymous", "anon_token": "anon_0001",- "client_id": "nas-anonymous", "access_token": _jwt(), "expires_at": "2999-01-01T00:00:00+00:00",- "inference_base_url": "https://welcome-api.nousresearch.com/v1"}- _save_auth_store(store)---class _RecordingConsole:- def __init__(self):- self.lines: list[str] = []-- def print(self, *args, **kwargs):- self.lines.append(" ".join(str(a) for a in args))---class _NoticeCLI(CLIAgentSetupMixin):- """Only what the notice path touches: the console seam."""+def portal(monkeypatch, tmp_path):+ return install_portal(monkeypatch, tmp_path)- def __init__(self):- self.console = _RecordingConsole()- self._app = None- def _console_print(self, *args, **kwargs):- self.console.print(*args, **kwargs)+def test_a_claimed_trial_has_the_notice_pending_once_and_the_flag_persists(portal, monkeypatch):+ claimed_trial(monkeypatch)+ assert anon_auth.guest_notice_pending()+ assert anon_auth.mark_guest_notice_shown() is True[email protected](autouse=True)-def _isolated_store(tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")---def test_notice_prints_once_after_identity_appears_and_persists_the_flag():- cli = _NoticeCLI()+ assert _load_auth_store()["providers"]["nous"][anon_auth.GUEST_NOTICE_FLAG] is True+ assert not anon_auth.guest_notice_pending()- # Background mint has not landed yet: nothing to say.- cli._maybe_print_free_tier_available_notice()- assert cli.console.lines == []- _seed_guest()- cli._maybe_print_free_tier_available_notice()- assert len(cli.console.lines) == 1- text = cli.console.lines[0]- assert anon_auth.FREE_TIER_AVAILABLE_NOTICE in text- assert "guest" not in text.lower() and "anonymous" not in text.lower()+def test_a_connector_only_guest_has_no_notice_pending(portal, monkeypatch):+ as_local_desktop_backend(monkeypatch)+ anon_auth.ensure_portal_identity(explicit=True)- # Same process, and a fresh process reading the store: never again.- cli._maybe_print_free_tier_available_notice()- _NoticeCLI()._maybe_print_free_tier_available_notice()- assert len(cli.console.lines) == 1- assert _load_auth_store()["providers"]["nous"][anon_auth.GUEST_NOTICE_FLAG] is True- assert not anon_auth.guest_notice_pending()+ assert anon_auth.has_guest() and not anon_auth.guest_notice_pending()-def test_signed_in_account_is_never_told_about_the_free_tier():+def test_signed_in_account_is_never_told_about_the_free_tier(portal):with _auth_store_lock():store = _load_auth_store()store.setdefault("providers", {})["nous"] = {"auth_method": "oauth", "access_token": _jwt(client_id="hermes-cli", account_tier="pro"),"refresh_token": "rt", "expires_at": "2999-01-01T00:00:00+00:00"}_save_auth_store(store)- cli = _NoticeCLI()- cli._maybe_print_free_tier_available_notice()-- assert cli.console.lines == []+ assert not anon_auth.guest_notice_pending()assert anon_auth.mark_guest_notice_shown() is Falseassert anon_auth.GUEST_NOTICE_FLAG not in _load_auth_store()["providers"]["nous"]diff --git a/tests/hermes_cli/test_anon_picker.py b/tests/hermes_cli/test_anon_picker.pyindex 4004f9b3b16..4df818aeb2b 100644--- a/tests/hermes_cli/test_anon_picker.py+++ b/tests/hermes_cli/test_anon_picker.py@@ -1,6 +1,6 @@"""Model pickers under a Nous free-tier identity.-A guest identity carrying inference shows one row, "Nous · free tier", with the single model+A guest carrying the welcome trial shows one row, "Nous · free tier", with the single model``nous/welcome``; the same guest with ``nous.guest: false`` shows no Nous row at all. The rule livesin one helper (``_free_tier_nous_row``) and this file exercises it through the real row buildersagainst a temp ``HERMES_HOME`` with the network catalog fetch stubbed.@@ -13,7 +13,9 @@ from pathlib import Pathimport pytest+from hermes_cli.anon_auth import WELCOME_CLAIM_FLAGfrom hermes_cli.auth import _save_auth_store+from tests.hermes_cli.anon_portal import as_local_desktop_backendGUEST_STATE = {"auth_method": "anonymous",@@ -22,14 +24,16 @@ GUEST_STATE = {"access_token": "aaa.bbb.ccc","expires_at": "2030-01-01T00:00:00+00:00","inference_base_url": "https://welcome-api.nousresearch.com/v1",+ WELCOME_CLAIM_FLAG: True,}@pytest.fixturedef guest_home(monkeypatch, tmp_path):- """Seed a guest identity as the only Nous state and keep every row builder offline."""+ """Seed a guest that claimed the welcome trial, read on the desktop's local backend, as the only+ Nous state, and keep every row builder offline."""monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")+ as_local_desktop_backend(monkeypatch)for var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NOUS_API_KEY", "LM_API_KEY", "LM_BASE_URL"):monkeypatch.delenv(var, raising=False)_save_auth_store({"active_provider": "nous", "providers": {"nous": dict(GUEST_STATE)}})@@ -84,7 +88,7 @@ def test_guest_identity_shows_free_tier_row_with_only_welcome_model(guest_home,def test_guest_identity_with_guest_off_hides_the_nous_row(guest_home, monkeypatch):_write_config(monkeypatch, guest_home, "nous:\n guest: false\n")from hermes_cli import anon_auth- assert anon_auth.has_guest() and not anon_auth.guest_enabled()+ assert anon_auth.has_guest() and not anon_auth.free_inference_active()from hermes_cli.model_switch_providers import list_picker_providersassert _nous_rows(list_picker_providers("nous", "", None, None, 50, "nous/welcome")) == []diff --git a/tests/hermes_cli/test_anon_sign_in_flow.py b/tests/hermes_cli/test_anon_sign_in_flow.pyindex ca5d5250735..8392ed139eb 100644--- a/tests/hermes_cli/test_anon_sign_in_flow.py+++ b/tests/hermes_cli/test_anon_sign_in_flow.py@@ -219,8 +219,12 @@ def test_already_signed_in_short_circuits_before_any_network(portal):assert states[0].precondition is Trueassert portal.calls == []-def test_free_tier_off_yields_unavailable(portal, monkeypatch):- monkeypatch.setattr(anon_auth, "guest_enabled", lambda: False)+def test_guests_switched_off_yields_unavailable(portal):+ _seed_free_tier()+ from hermes_cli.config import load_config, save_config+ config = load_config()+ config["nous"] = {"guest": False}+ save_config(config)portal.calls.clear()states = _drain()@@ -231,7 +235,7 @@ def test_free_tier_off_yields_unavailable(portal, monkeypatch):assert portal.calls == []def test_no_identity_on_disk_yields_unavailable_without_touching_the_portal(portal, monkeypatch):- """A sign-in never creates the identity it signs in from: the boot bootstrap is the only creator.+ """A sign-in never creates the identity it signs in from (the trial claim and connector use do).With nothing on disk the flow yields ``Unavailable`` and makes no portal call and no mint attempt."""monkeypatch.setattr(anon_auth, "ensure_portal_identity",lambda **kwargs: (_ for _ in ()).throw(AssertionError("run_sign_in must not mint")))diff --git a/tests/hermes_cli/test_anon_surfaces.py b/tests/hermes_cli/test_anon_surfaces.pyindex 9eed6105f15..de87f789674 100644--- a/tests/hermes_cli/test_anon_surfaces.py+++ b/tests/hermes_cli/test_anon_surfaces.py@@ -13,7 +13,6 @@ import dataclassesimport jsonimport reimport time-from datetime import datetimefrom pathlib import Pathfrom types import SimpleNamespace@@ -29,6 +28,7 @@ from hermes_cli import ()from hermes_cli.auth import _load_auth_storefrom hermes_constants import get_hermes_home+from tests.hermes_cli.anon_portal import as_local_desktop_backendWELCOME = "https://welcome-api.nousresearch.com/v1"# Words that must never appear on a user-facing free-tier surface.@@ -54,6 +54,7 @@ def _guest_state() -> dict:"auth_method": "anonymous", "account_tier": "anonymous", "anon_token": "anon_t","access_token": _jwt(), "expires_at": "2030-01-01T00:00:00+00:00","inference_base_url": WELCOME, "user_id": "nas_user:abc", "org_id": "nas_organisation:def",+ anon_auth.WELCOME_CLAIM_FLAG: True,}@@ -69,7 +70,8 @@ def _account_state() -> dict:@pytest.fixturedef isolated_store(monkeypatch, tmp_path):monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")+ # The welcome trial carries inference only on the desktop's local backend.+ as_local_desktop_backend(monkeypatch)for var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NOUS_API_KEY"):monkeypatch.delenv(var, raising=False)# No network: the account lookup is derived from the JWT the store already holds.@@ -210,25 +212,12 @@ def test_the_paid_tool_notice_switches_wording_inside_a_chat():) == nous_account.FREE_TIER_NEEDS_ACCOUNT-def test_cli_chat_status_names_the_free_tier(isolated_store):- from hermes_cli.cli_session_mixin import CLISessionMixin-+def test_a_claimed_guest_off_the_desktop_backend_is_not_the_free_tier(isolated_store, monkeypatch, capsys):+ """On the CLI surface the trial carries no inference: the guest reads as not signed in."""+ monkeypatch.delenv("HERMES_DESKTOP", raising=False)+ monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)_write_auth(_guest_state())- rendered = []- cli = SimpleNamespace(- _session_db=None,- session_id="cli-free-tier-status",- session_start=datetime.now(),- agent=SimpleNamespace(session_total_tokens=0, reasoning_config=None),- provider="nous",- model=anon_auth.GUEST_MODEL,- _agent_running=False,- reasoning_config=None,- show_reasoning=None,- session_key="cli:free-tier-status",- _get_status_bar_snapshot=dict,- _console_print=lambda text, **_kwargs: rendered.append(text),- )- CLISessionMixin._show_session_status(cli)- assert anon_auth.FREE_TIER_STATUS_LINE in rendered[0]+ auth_commands.auth_status_command(SimpleNamespace(provider="nous"))+ text = capsys.readouterr().out+ assert "free tier" not in text.lower() and anon_auth.GUEST_MODEL not in textdiff --git a/tests/hermes_cli/test_anon_upgrade.py b/tests/hermes_cli/test_anon_upgrade.pyindex b6ffe141eb6..252554f46ae 100644--- a/tests/hermes_cli/test_anon_upgrade.py+++ b/tests/hermes_cli/test_anon_upgrade.py@@ -99,7 +99,6 @@ def portal(monkeypatch, tmp_path):monkeypatch.setenv("HERMES_PORTAL_BASE_URL", PORTAL)monkeypatch.setenv("HERMES_ANON_API_SECRET", "test-secret")monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")for var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NOUS_API_KEY"):monkeypatch.delenv(var, raising=False)from hermes_cli import auth_nousdiff --git a/tests/hermes_cli/test_banner.py b/tests/hermes_cli/test_banner.pyindex fc8dcd8ecc2..2c9013876ba 100644--- a/tests/hermes_cli/test_banner.py+++ b/tests/hermes_cli/test_banner.py@@ -35,29 +35,20 @@ def test_cprint_falls_back_to_plain_print_when_prompt_toolkit_has_no_console(capassert capsys.readouterr().out == "fallback text\n"-def test_empty_model_shows_the_free_tier_route_when_it_carries_inference(tmp_path, monkeypatch):- """The banner prints before credentials resolve, so ``model`` is empty on a fresh install. On the- free tier the route is known locally (identity on disk + tier on): the banner shows its model.- When nothing resolves the red "no model configured" line stays."""+def test_empty_model_shows_no_model_configured(tmp_path, monkeypatch):+ """The banner prints before credentials resolve; with no model it says so rather than guessing."""monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))(tmp_path / ".hermes").mkdir()- from hermes_cli import anon_auth-- def render(carries: bool) -> str:- with (- patch.object(model_tools, "check_tool_availability", return_value=([], [])),- patch.object(banner, "get_available_skills", return_value={}),- patch.object(banner, "get_update_result", return_value=None),- patch.object(tools.mcp_tool_discovery, "get_mcp_status", return_value=[]),- patch.object(anon_auth, "free_tier_route", return_value=carries),- ):- console = Console(record=True, force_terminal=False, color_system=None, width=160)- banner.build_welcome_banner(console=console, model="", cwd="/tmp/project", tools=[],- enabled_toolsets=[], provider="auto")- return console.export_text()-- assert "welcome" in render(True) and "no model configured" not in render(True)- assert "no model configured" in render(False)+ with (+ patch.object(model_tools, "check_tool_availability", return_value=([], [])),+ patch.object(banner, "get_available_skills", return_value={}),+ patch.object(banner, "get_update_result", return_value=None),+ patch.object(tools.mcp_tool_discovery, "get_mcp_status", return_value=[]),+ ):+ console = Console(record=True, force_terminal=False, color_system=None, width=160)+ banner.build_welcome_banner(console=console, model="", cwd="/tmp/project", tools=[],+ enabled_toolsets=[], provider="auto")+ assert "no model configured" in console.export_text()def test_build_welcome_banner_does_not_center_pad_hero_art():diff --git a/tests/hermes_cli/test_cli_first_message.py b/tests/hermes_cli/test_cli_first_message.pyindex d3c84ec2b32..f43188d7d23 100644--- a/tests/hermes_cli/test_cli_first_message.py+++ b/tests/hermes_cli/test_cli_first_message.py@@ -30,7 +30,7 @@ def test_first_cli_message_in_a_fresh_home_reaches_the_model_unchanged(tmp_path))env = {**os.environ, "HERMES_HOME": str(home), "PYTHONUTF8": "1"}env["PYTHONPATH"] = str(ROOT) + os.pathsep + env.get("PYTHONPATH", "")- for name in ("HERMES_GUEST_ONBOARDING", "HERMES_DESKTOP"):+ for name in ("HERMES_DESKTOP", "HERMES_DASHBOARD_SESSION_TOKEN"):env.pop(name, None)proc = subprocess.run([sys.executable, "-m", "hermes_cli.main", "chat", "-q", PROMPT],diff --git a/tests/hermes_cli/test_free_tier_offer.py b/tests/hermes_cli/test_free_tier_offer.pyindex 4db4fc5d17c..4cb9439e694 100644--- a/tests/hermes_cli/test_free_tier_offer.py+++ b/tests/hermes_cli/test_free_tier_offer.py@@ -26,8 +26,7 @@ class _Clock:@pytest.fixturedef clock(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / "root" / "profiles" / "setup"))- monkeypatch.setattr(anon_auth, "has_guest", lambda: True)- monkeypatch.setattr(anon_auth, "guest_enabled", lambda: True)+ monkeypatch.setattr(anon_auth, "free_inference_active", lambda state=None: True)fake = _Clock()monkeypatch.setattr(free_tier_offer, "_clock", fake)return fake@@ -105,11 +104,10 @@ def test_record_is_install_wide_across_profiles(clock, tmp_path, monkeypatch):assert free_tier_offer.offer_due_in() == DELAY[email protected]("signed_in,tier_on", [(True, True), (False, False)], ids=["signed-in", "tier-off"])-def test_never_offered_off_the_free_tier(clock, monkeypatch, signed_in, tier_on):+def test_never_offered_off_the_free_tier(clock, monkeypatch):+ """Signed in, a connector-only guest, or off the desktop backend: the trial carries nothing here."""free_tier_offer.record_task_done()clock.now += DELAY- monkeypatch.setattr(anon_auth, "has_guest", lambda: not signed_in)- monkeypatch.setattr(anon_auth, "guest_enabled", lambda: tier_on)+ monkeypatch.setattr(anon_auth, "free_inference_active", lambda state=None: False)assert free_tier_offer.offer_due_in() is Noneassert free_tier_offer.claim_offer() is Falsediff --git a/tests/hermes_cli/test_multiplex_cli_cache_scope.py b/tests/hermes_cli/test_multiplex_cli_cache_scope.pyindex ee5a4e297ba..6f6fb4c11be 100644--- a/tests/hermes_cli/test_multiplex_cli_cache_scope.py+++ b/tests/hermes_cli/test_multiplex_cli_cache_scope.py@@ -207,7 +207,6 @@ def test_banner_skills_are_the_routed_profiles(homes):def test_failed_guest_mint_only_suppresses_that_profile(homes, monkeypatch, tmp_path):a, b = homes- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared"))import hermes_cli.anon_auth as anonfrom hermes_cli import auth_nousdiff --git a/tests/hermes_cli/test_provider_precedence.py b/tests/hermes_cli/test_provider_precedence.pyindex 45f21cc89a7..33d92403910 100644--- a/tests/hermes_cli/test_provider_precedence.py+++ b/tests/hermes_cli/test_provider_precedence.py@@ -81,56 +81,65 @@ class TestProviderPrecedence:assert resolve_provider("auto") == "openrouter"-def _logged_out(monkeypatch):- monkeypatch.setattr("hermes_cli.auth._load_auth_store", dict)- monkeypatch.setattr("hermes_cli.auth.get_auth_status", lambda p: {"logged_in": False})+def portal(monkeypatch, tmp_path):+ from tests.hermes_cli.anon_portal import install_portal+ return install_portal(monkeypatch, tmp_path)-def _free_tier(monkeypatch, *, on=True, identity=False):- """Free tier switch + whether a free-tier identity already exists. The resolver is a READ: any- call into the creator from inside it is a bug, so the stub fails loudly."""- monkeypatch.setattr("hermes_cli.anon_auth.guest_enabled", lambda: on)- monkeypatch.setattr("hermes_cli.anon_auth.has_guest", lambda: identity)+def _never_mint(monkeypatch):+ """The resolver is a READ: any call into the creator from inside it is a bug."""monkeypatch.setattr("hermes_cli.anon_auth.ensure_portal_identity",lambda **kw: (_ for _ in ()).throw(AssertionError("resolve_provider must not mint")))+def _claimed_trial_with_aws(monkeypatch):+ """A claimed welcome trial on the desktop's local backend, then a leftover ~/.aws profile."""+ from tests.hermes_cli.anon_portal import claimed_trial+ _clear_provider_env(monkeypatch)+ claimed_trial(monkeypatch)+ _never_mint(monkeypatch)+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: True)++class TestFreeTierBeatsImplicitHostCredentials:- """NS-829: a leftover ~/.aws profile must not pre-empt the free tier on a fresh install.-- The ladder: explicit intent still wins, an EXISTING free-tier identity sits above the implicit- Bedrock chain, the free tier off (or its identity absent) restores Bedrock. The resolver never- creates the identity; the boot bootstrap does, before any turn asks."""-- @pytest.mark.parametrize("free_tier_on, identity, env_key, login, expected", [- (True, True, None, None, "nous"), # existing identity beats the AWS chain- (True, False, None, None, "bedrock"), # no identity yet: Bedrock, nothing minted- (False, True, None, None, "bedrock"), # free tier off: Bedrock as before- (True, True, "OPENAI_API_KEY", None, "openai-api"), # env key still wins- (True, True, None, "anthropic", "anthropic"), # a sign-in still wins- ])- def test_free_tier_sits_above_the_bedrock_chain(self, monkeypatch, free_tier_on, identity,- env_key, login, expected):- _clear_provider_env(monkeypatch)- _config(monkeypatch, "")- if login:- _login(monkeypatch, login)- else:- _logged_out(monkeypatch)+ """NS-829: a leftover ~/.aws profile must not pre-empt the welcome trial on a fresh install.++ A claimed trial on the desktop's local backend sits above the implicit Bedrock chain; explicit+ intent still beats it; off the desktop backend a claimed guest never resolves to nous. The+ resolver never creates the identity."""++ def test_a_claimed_trial_on_the_desktop_backend_beats_the_bedrock_chain(self, portal, monkeypatch):+ _claimed_trial_with_aws(monkeypatch)+ assert resolve_provider("auto") == "nous"++ @pytest.mark.parametrize("env_key, config_provider, expected", [+ ("OPENAI_API_KEY", None, "openai-api"), # an exported key wins+ (None, "zai", "zai"), # a config pin wins+ ], ids=["env-key", "config-provider"])+ def test_explicit_providers_beat_a_claimed_trial(self, portal, monkeypatch, env_key, config_provider,+ expected):+ _claimed_trial_with_aws(monkeypatch)if env_key:monkeypatch.setenv(env_key, "sk-test-key")- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: True)- _free_tier(monkeypatch, on=free_tier_on, identity=identity)+ if config_provider:+ _config(monkeypatch, {"provider": config_provider, "default": "some-model"})assert resolve_provider("auto") == expected- def test_skip_free_tier_answers_what_else_would_carry_inference(self, monkeypatch):- """The bootstrap's question: with the free tier hidden, an existing identity is not an- answer and the ladder falls through to the next real rung."""- _clear_provider_env(monkeypatch)- _config(monkeypatch, "")- _logged_out(monkeypatch)+ def test_on_the_cli_surface_a_claimed_guest_never_resolves_to_nous(self, portal, monkeypatch):+ _claimed_trial_with_aws(monkeypatch)+ monkeypatch.delenv("HERMES_DESKTOP", raising=False)+ monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)+ assert resolve_provider("auto") == "bedrock"+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)+ with pytest.raises(AuthError):+ resolve_provider("auto")++ def test_skip_free_tier_answers_what_else_would_carry_inference(self, portal, monkeypatch):+ """With the free tier hidden, a claimed trial is not an answer and the ladder falls through+ to the next real rung."""+ _claimed_trial_with_aws(monkeypatch)monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)- _free_tier(monkeypatch, on=True, identity=True)assert resolve_provider("auto") == "nous"with pytest.raises(AuthError):resolve_provider("auto", skip_free_tier=True)diff --git a/tests/hermes_cli/test_resolve_provider_custom_endpoint.py b/tests/hermes_cli/test_resolve_provider_custom_endpoint.pyindex 834561e72db..ba0b83562d8 100644--- a/tests/hermes_cli/test_resolve_provider_custom_endpoint.py+++ b/tests/hermes_cli/test_resolve_provider_custom_endpoint.py@@ -18,7 +18,6 @@ def isolated_home(tmp_path, monkeypatch):home.mkdir()(home / ".env").write_text("", encoding="utf-8")monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.delenv("HERMES_GUEST_ONBOARDING", raising=False)for var in ("OPENAI_API_KEY", "OPENROUTER_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_BASE_URL","OPENROUTER_BASE_URL", "HERMES_INFERENCE_PROVIDER", "NOUS_API_KEY"):monkeypatch.delenv(var, raising=False)diff --git a/tests/hermes_cli/test_shared_metrics_signals.py b/tests/hermes_cli/test_shared_metrics_signals.pyindex b43ab0d35ef..71de653b66e 100644--- a/tests/hermes_cli/test_shared_metrics_signals.py+++ b/tests/hermes_cli/test_shared_metrics_signals.py@@ -387,7 +387,6 @@ def _guest_sign_in(token_status, token_body):monkeypatch.setattr(auth_device_flow, "time", fake_time)monkeypatch.setattr(anon_auth, "current_nous_state", lambda: {"auth_method": anon_auth.ANON_AUTH_METHOD, "anon_token": "t", "portal_base_url": "https://p"})- monkeypatch.setattr(anon_auth, "guest_enabled", lambda: True)monkeypatch.setattr(anon_auth, "_anon_headers", dict)replies = {"/api/oauth/device/code": (200, {"device_code": "d", "user_code": "U", "verification_uri": "https://p/v",diff --git a/tests/hermes_cli/test_stream_json.py b/tests/hermes_cli/test_stream_json.pyindex e7c8df5d111..3e872faf8cd 100644--- a/tests/hermes_cli/test_stream_json.py+++ b/tests/hermes_cli/test_stream_json.py@@ -92,7 +92,6 @@ def _run_stream_json_chat(monkeypatch, capsys, run_conversation, credentials_ok=monkeypatch.setattr(cli_entry, "_pin_kanban_board_env", lambda: None)monkeypatch.setattr(cli_entry, "_confirm_startup_expensive_model_override", lambda _a: None)monkeypatch.setattr(cli_entry, "_warn_retired_xai_models", lambda: None)- monkeypatch.setattr("hermes_cli.free_tier_bootstrap.run_bootstrap", lambda **_k: None)monkeypatch.setattr("hermes_cli.quiet_single_query.continue_quiet_notify_completions", lambda *_a, **_k: None)parser, _, _ = build_top_level_parser()diff --git a/tests/hermes_cli/test_tui_first_run_routing.py b/tests/hermes_cli/test_tui_first_run_routing.pyindex ea8c57d2639..2780c09f4cf 100644--- a/tests/hermes_cli/test_tui_first_run_routing.py+++ b/tests/hermes_cli/test_tui_first_run_routing.py@@ -20,7 +20,6 @@ class _Launched(Exception):def _run_chat(monkeypatch, argv, *, provider_configured):import hermes_cli.main as main_modfrom hermes_cli._parser import build_top_level_parser- import hermes_cli.free_tier_bootstrap as bootstrapimport hermes_cli.observability.shared_metrics_consent as consentparser, _subparsers, chat_parser = build_top_level_parser()@@ -35,7 +34,6 @@ def _run_chat(monkeypatch, argv, *, provider_configured):def classic_main(**_k):calls.append("classic")- monkeypatch.setattr(bootstrap, "run_bootstrap", lambda **_k: None)monkeypatch.setattr(main_mod, "_has_any_provider_configured", lambda: provider_configured)monkeypatch.setattr(main_mod, "_first_run_setup_guard", lambda _args: calls.append("guard"))monkeypatch.setattr(consent, "offer_consent_before_chat", lambda _args: calls.append("offer"))diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 25cca72ecb5..07873e16fac 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -1488,7 +1488,7 @@ CONFIG_SCHEMA = ProviderConfigSchema(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+ (``provider_configured: false``: nothing carried inference at boot) must follow at once, withthe ``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 fbdiff --git a/tests/tools/test_connectors_guest_on_first_use.py b/tests/tools/test_connectors_guest_on_first_use.pyindex cdfae3cb04f..82032ab0a6d 100644--- a/tests/tools/test_connectors_guest_on_first_use.py+++ b/tests/tools/test_connectors_guest_on_first_use.py@@ -19,9 +19,7 @@ from tests.hermes_cli.anon_portal import install_portal@pytest.fixturedef nas(monkeypatch, tmp_path):- fake = install_portal(monkeypatch, tmp_path)- monkeypatch.delenv("HERMES_GUEST_ONBOARDING")- return fake+ return install_portal(monkeypatch, tmp_path)def test_first_hosted_action_creates_one_connectors_only_guest(nas, monkeypatch):diff --git a/tests/tools/test_managed_tool_gateway.py b/tests/tools/test_managed_tool_gateway.pyindex cb3ae0d8682..5e7c35bfe96 100644--- a/tests/tools/test_managed_tool_gateway.py+++ b/tests/tools/test_managed_tool_gateway.py@@ -222,7 +222,6 @@ def test_read_nous_provider_state_falls_back_to_global_root_for_share_auth_profi"providers": {"nous": {"auth_method": "anonymous", "access_token": "tok"}},}))monkeypatch.setenv("HERMES_HOME", str(profile))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)import hermes_constantsdiff --git a/tests/tools/test_web_free_fast_search.py b/tests/tools/test_web_free_fast_search.pyindex 8b1832a73ff..a8e327f4978 100644--- a/tests/tools/test_web_free_fast_search.py+++ b/tests/tools/test_web_free_fast_search.py@@ -11,7 +11,10 @@ from threading import Threadimport pytest-# Anonymous guest: NAS tier claim says "anonymous" — no Portal account behind the identity.+from tests.hermes_cli.anon_portal import as_local_desktop_backend++# Anonymous guest: NAS tier claim says "anonymous" — no Portal account behind the identity. It claimed+# the desktop's welcome trial (``_write_home`` reads it on the local desktop backend).ANON = {"sub": "anon-1", "account_tier": "anonymous", "paid_access": False}# Registered Portal account, signed in, no credits and no tool pool.EXHAUSTED = {"sub": "user-1", "paid_access": False, "tool_access": {"enabled": False, "coverage": {}}}@@ -25,6 +28,9 @@ def _nous_state(claims: dict, auth_method: str) -> dict:# anon_auth persists the tier alongside the token.if claims.get("account_tier"):state["account_tier"] = claims["account_tier"]+ if auth_method == "anonymous":+ from hermes_cli.anon_auth import WELCOME_CLAIM_FLAG+ state[WELCOME_CLAIM_FLAG] = Truereturn state@@ -73,7 +79,7 @@ def _write_home(home, monkeypatch, *, nous_state=None, config=None):home.mkdir(parents=True)monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")+ as_local_desktop_backend(monkeypatch)monkeypatch.delenv("PERPLEXITY_API_KEY", raising=False)monkeypatch.delenv("TOOL_GATEWAY_USER_TOKEN", raising=False)atomic_config_write(home / "config.yaml", {"web": {"keyless_rescue": False}, **(config or {})})diff --git a/tests/tui_gateway/test_free_tier_rpc.py b/tests/tui_gateway/test_free_tier_rpc.pyindex bbb9287bf34..d4a94594eb3 100644--- a/tests/tui_gateway/test_free_tier_rpc.py+++ b/tests/tui_gateway/test_free_tier_rpc.py@@ -1,64 +1,38 @@"""``free_tier.status`` / ``free_tier.ack_notice`` (pull) and the free-tier branch of ``billing.state``,-driven through the registered RPC handlers against a seeded free-tier identity."""+driven through the registered RPC handlers against a claimed welcome trial on the desktop's local+backend (the fake account service in ``tests.hermes_cli.anon_portal``)."""from __future__ import annotations-import base64-import json-import time-import pytestimport tui_gateway.server as srvfrom hermes_cli import anon_auth, free_tier_offerfrom hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store---def _jwt(**claims) -> str:- def seg(obj):- return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()- payload = {"sub": "nas_user:1", "client_id": "nas-anonymous", "account_tier": "anonymous",- "scope": "inference:invoke", "exp": int(time.time()) + 900, **claims}- return f"{seg({'alg': 'RS256'})}.{seg(payload)}.sig"+from tests.hermes_cli.anon_portal import as_local_desktop_backend, claimed_trial, install_portaldef _call(method: str, params: dict | None = None) -> dict:return srv._methods[method](1, params or {})["result"][email protected](autouse=True)-def _fresh_process_memos():- """``free_tier.provision`` routes through the boot record when one exists; a record another- test file left behind (has_identity) would make it skip the mint. Per-process state, per test,- both ways so this file leaves nothing behind either."""- from hermes_cli import free_tier_bootstrap-- def _reset():- free_tier_bootstrap.reset_for_tests()- anon_auth.reset_mint_memo_for_tests()- _reset()- yield- _reset()+def nas(tmp_path, monkeypatch):+ """The fake account service, read on the desktop's local backend of a first install."""+ fake = install_portal(monkeypatch, tmp_path)+ as_local_desktop_backend(monkeypatch)+ return fake@pytest.fixture-def guest(tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")- with _auth_store_lock():- store = _load_auth_store()- store.setdefault("providers", {})["nous"] = {- "auth_method": anon_auth.ANON_AUTH_METHOD, "account_tier": "anonymous", "anon_token": "anon_0001",- "client_id": "nas-anonymous", "access_token": _jwt(), "expires_at": "2999-01-01T00:00:00+00:00",- "inference_base_url": "https://welcome-api.nousresearch.com/v1"}- store["active_provider"] = "nous"- _save_auth_store(store)+def guest(nas, monkeypatch):+ """A guest that claimed the welcome trial."""+ return claimed_trial(monkeypatch)-def _set_guest_off(monkeypatch):- from hermes_cli import config as cfg_mod- monkeypatch.setattr(anon_auth, "guest_enabled", lambda: False)- return cfg_mod+def _set_guest_off():+ from hermes_constants import get_hermes_home+ (get_hermes_home() / "config.yaml").write_text("nous:\n guest: false\n", encoding="utf-8")def test_status_is_pull_from_local_state_and_ack_persists_on_the_identity(guest, monkeypatch):@@ -71,7 +45,7 @@ def test_status_is_pull_from_local_state_and_ack_persists_on_the_identity(guest,assert _load_auth_store()["providers"]["nous"][anon_auth.GUEST_NOTICE_FLAG] is True# nous.guest: false -> the identity exists but carries nothing; no notice either.- _set_guest_off(monkeypatch)+ _set_guest_off()status = _call("free_tier.status")assert status["has_guest"] is True and status["enabled"] is Falseassert status["available"] is False and status["notice_pending"] is False@@ -119,62 +93,45 @@ def test_billing_state_answers_the_free_tier_locally(guest, monkeypatch):assert res["free_tier_account"] is True and res["free_tier_model"] == "nous/welcome"assert res["usage"] == {"available": False}- _set_guest_off(monkeypatch)+ _set_guest_off()monkeypatch.setattr(bv, "build_billing_state", lambda *a, **kw: bv.BillingState(logged_in=False))res = _call("billing.state")assert res["free_tier_account"] is False and res["free_tier_model"] is None-def test_status_without_an_identity_is_a_pure_read(tmp_path, monkeypatch):+def test_status_without_an_identity_is_a_pure_read(nas):"""The desktop polls ``free_tier.status`` every status round; a poll must never create the identity- (that is the boot bootstrap's job)."""- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")- monkeypatch.setattr(anon_auth, "ensure_portal_identity",- lambda **kw: (_ for _ in ()).throw(AssertionError("free_tier.status must not mint")))+ (claiming the trial is ``onboarding.start``'s and ``free_tier.provision``'s job)."""status = _call("free_tier.status")assert status["has_guest"] is False and status["available"] is False and status["enabled"] is True+ assert nas.calls == []-def test_provision_sets_the_free_tier_up_through_the_lifecycle_primitive(tmp_path, monkeypatch):- """``free_tier.provision`` is the desktop's explicit retry: it calls the one creator- (``ensure_portal_identity(explicit=True)``) only when no identity exists, and reports the outcome."""- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")- calls = []- real_ensure = anon_auth.ensure_portal_identity-- def fake_provision(**kw):- calls.append(kw)- with _auth_store_lock():- store = _load_auth_store()- store.setdefault("providers", {})["nous"] = {- "auth_method": anon_auth.ANON_AUTH_METHOD, "account_tier": "anonymous", "anon_token": "anon_0002"}- _save_auth_store(store)- return store["providers"]["nous"]-- monkeypatch.setattr(anon_auth, "ensure_portal_identity", fake_provision)+def test_provision_claims_the_trial_once_while_it_is_claimable(nas):+ """``free_tier.provision`` is the desktop's explicit retry: it claims the welcome trial while+ nothing blocks the claim here, and reports the outcome."""assert _call("free_tier.provision") == {"has_guest": True, "enabled": True}- assert calls == [{"explicit": True, "force": True}]+ assert nas.creates() == 1 and anon_auth.free_inference_active()+assert _call("free_tier.provision") == {"has_guest": True, "enabled": True}- assert len(calls) == 1 # idempotent: an identity exists, nothing is minted+ assert nas.creates() == 1 # claimed already: nothing is minted again- def refused(**kw):- raise anon_auth.AuthError("Nous free tier is not open on this portal.", code="anon_gate_closed")- with _auth_store_lock():- store = _load_auth_store(); store["providers"].pop("nous"); _save_auth_store(store)- # The real primitive memoises the refusal; the RPC reports that memo.- monkeypatch.setattr(anon_auth, "ensure_portal_identity", real_ensure)- monkeypatch.setattr(anon_auth, "_reconcile_and_provision", refused)- anon_auth.reset_mint_memo_for_tests()+def test_provision_reports_a_refused_claim_and_the_users_retry_skips_the_cooldown(nas):+ nas.gate_closed = Trueresult = _call("free_tier.provision")- assert result["has_guest"] is False and "not open" in result["error"]- assert result["error_code"] == "anon_gate_closed" and result["retryable"] is False+ assert result["has_guest"] is False and result["enabled"] is True+ assert result["error_code"] == "anon_gate_closed" and result["retryable"] is False, result++ nas.gate_closed = False # still inside the refusal's cooldown+ assert _call("free_tier.provision") == {"has_guest": True, "enabled": True}+ assert anon_auth.free_inference_active()- _set_guest_off(monkeypatch)- monkeypatch.setattr(anon_auth, "ensure_portal_identity", lambda **kw: (_ for _ in ()).throw(AssertionError("must not run")))++def test_provision_does_nothing_with_guests_switched_off(nas):+ _set_guest_off()assert _call("free_tier.provision") == {"has_guest": False, "enabled": False}+ assert nas.calls == []def test_sign_in_offer_is_reported_then_claimed_once(guest, monkeypatch):@@ -197,6 +154,9 @@ def test_sign_in_offer_is_reported_then_claimed_once(guest, monkeypatch):def test_sign_in_offer_is_moot_once_signed_in(guest, monkeypatch):monkeypatch.setattr(free_tier_offer, "_clock", lambda: 10_000.0)free_tier_offer.record_task_done()- monkeypatch.setattr(anon_auth, "has_guest", lambda: False)+ with _auth_store_lock(): # the user signed in: the profile's Nous identity is an account now+ store = _load_auth_store()+ store["providers"]["nous"] = {"auth_method": "oauth", "access_token": "acct-token"}+ _save_auth_store(store)assert "nudge_due_in" not in _call("free_tier.status")assert _call("free_tier.claim_nudge") == {"claimed": False}diff --git a/tests/tui_gateway/test_free_tier_task_done.py b/tests/tui_gateway/test_free_tier_task_done.pyindex 6b0b5cf089a..d096f7bf85c 100644--- a/tests/tui_gateway/test_free_tier_task_done.py+++ b/tests/tui_gateway/test_free_tier_task_done.py@@ -18,8 +18,7 @@ CLEAN = {"completed": True, "final_response": "Here is your plan.", "user_interv@pytest.fixture(autouse=True)def free_tier(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- monkeypatch.setattr(anon_auth, "has_guest", lambda: True)- monkeypatch.setattr(anon_auth, "guest_enabled", lambda: True)+ monkeypatch.setattr(anon_auth, "free_inference_active", lambda state=None: True)monkeypatch.setattr(anon_auth, "is_anonymous_agent", lambda agent: getattr(agent, "anonymous", True))monkeypatch.setattr(free_tier_offer, "_clock", lambda: 5_000.0)diff --git a/tests/tui_gateway/test_onboarding_run_rpc.py b/tests/tui_gateway/test_onboarding_run_rpc.pyindex 13cd69342b9..c666e53b80d 100644--- a/tests/tui_gateway/test_onboarding_run_rpc.py+++ b/tests/tui_gateway/test_onboarding_run_rpc.py@@ -11,6 +11,7 @@ from tui_gateway import serverfrom agent.onboarding import PROFILE_BUILD_FLAGfrom hermes_cli import profilesfrom hermes_cli.config import read_user_config_raw+from tests.hermes_cli.anon_portal import as_local_desktop_backend@pytest.fixture@@ -21,7 +22,6 @@ def launched_under_work(tmp_path, monkeypatch) -> tuple[Path, Path]:monkeypatch.setenv("HERMES_HOME", str(root))work = profiles.create_profile("work", no_alias=True)monkeypatch.setenv("HERMES_HOME", str(work))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")return root, work@@ -34,17 +34,21 @@ def _onboarding(home: Path) -> dict:def test_state_answers_run_and_eligible(launched_under_work, monkeypatch):- # The user's own "work" profile is install history, so an unset flag is not due.- assert _call("onboarding.state")["result"] == {"run": False, "eligible": True, "session_id": None, "run_id": None}+ # The user's own "work" profile is install history, so an unset flag is not due, and on the+ # desktop's local backend nothing carries a first chat: the trial is never claimed on a used machine.+ as_local_desktop_backend(monkeypatch)+ for var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "NOUS_API_KEY"):+ monkeypatch.delenv(var, raising=False)+ assert _call("onboarding.state")["result"] == {"run": False, "eligible": False, "session_id": None, "run_id": None}- monkeypatch.delenv("HERMES_GUEST_ONBOARDING")- assert _call("onboarding.state")["result"]["eligible"] is False+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")+ assert _call("onboarding.state")["result"]["eligible"] is Truedef test_set_run_writes_the_root_config(launched_under_work):root, work = launched_under_work- assert _call("onboarding.set_run", {"run": True})["result"] == {"run": True, "eligible": True, "session_id": None, "run_id": None}+ assert _call("onboarding.set_run", {"run": True})["result"] == {"run": True, "eligible": False, "session_id": None, "run_id": None}assert _onboarding(root)["run"] is Trueassert "run" not in _onboarding(work)assert _call("onboarding.state")["result"]["run"] is Truediff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 29c198fbe21..dd74fb8391a 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -9381,9 +9381,9 @@ def test_enable_gateway_prompts_sets_gateway_env(monkeypatch):def test_setup_status_answers_from_the_bootstrap_record_once_it_exists(monkeypatch):- """Under ``hermes serve`` the boot bootstrap owns the free-tier identity; ``setup.status`` reports- its record (blocking for it while it is in flight) instead of re-probing, so a client's first poll- sees the identity that exists rather than racing the mint."""+ """Under ``hermes serve`` the boot bootstrap records who carries inference; ``setup.status``+ reports its record (blocking for it while it is in flight) instead of re-probing, so a client's+ first poll sees the boot's answer rather than racing it."""import threadingfrom hermes_cli import free_tier_bootstrap as fbfb.reset_for_tests()