The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): a profile's channel status follows its gateway and enabled secret sources
kshitijk4poorbdaef8d90b24
diff --git a/gateway/config_env.py b/gateway/config_env.pyindex faf3b19673b..294c1b6382c 100644--- a/gateway/config_env.py+++ b/gateway/config_env.py@@ -7,11 +7,15 @@ copy the values into ``extra``" — declared by each platform plugin as ``Platfomsgraph_webhook, relay) keep their small functions here."""+import copyimport loggingimport os+from contextvars import ContextVarfrom typing import Optionalfrom gateway.config import (+ _BUILTIN_PLATFORM_VALUES,+ _discovered_registry_entry,GatewayConfig,HomeChannel,Platform,@@ -53,10 +57,15 @@ def _enable_credential_names(platform: Platform) -> tuple:return names+# Set by builtin_platform_status: a status read for another profile must neither repeat the gateway's+# operational logs on every dashboard poll nor use up its one-time warnings.+_STATUS_READ: ContextVar[bool] = ContextVar("gateway_env_status_read", default=False)++def _warn_explicit_disable_beats_env(platform: Platform) -> None:"""One-time WARNING: ``platforms.<x>.enabled: false`` wins over env creds (whichused to force-enable), so users relying on "creds in .env = on" learn why it went dark."""- if platform in _EXPLICIT_DISABLE_WARNED:+ if platform in _EXPLICIT_DISABLE_WARNED or _STATUS_READ.get():return_EXPLICIT_DISABLE_WARNED.add(platform)names = _enable_credential_names(platform)@@ -241,7 +250,7 @@ def _configured_plugin_entries(config: GatewayConfig) -> list:return []-def _bundled_env_fallbacks(config: GatewayConfig, entries: list) -> list:+def _bundled_env_fallbacks(config: GatewayConfig, entries: list, *, only: Optional[Platform] = None) -> list:"""Env rows of bundled platforms with activation evidence but no registry entry (discoverysuppressed or the plugin disabled), read from their ``gateway_env`` files; see``gateway.platform_env.bundled_env_rows``. They only run the env steps, never the enable pass."""@@ -249,7 +258,10 @@ def _bundled_env_fallbacks(config: GatewayConfig, entries: list) -> list:from gateway.platform_activation import activation_predicatefrom gateway.platform_env import _BUNDLED_ENV_SIBLINGS, bundled_env_rowshave = {getattr(e, "name", "") for e in entries}- names = (set(Platform._scan_bundled_plugin_platforms()[0]) | set(_BUNDLED_ENV_SIBLINGS)) - have+ if only is not None: # bundled_env_rows() answers for one name without scanning every manifest+ names = {only.value} - have+ else:+ names = (set(Platform._scan_bundled_plugin_platforms()[0]) | set(_BUNDLED_ENV_SIBLINGS)) - haveif not names:return []wanted = activation_predicate(yaml_cfg={}, platform_names=config.platforms)@@ -325,7 +337,9 @@ def _relay(config: GatewayConfig) -> None:for platform, platform_config in config.platforms.items():if platform in skip or not platform_config.enabled:continue- if platform_config.extra.get("_enabled_explicit"):+ if _STATUS_READ.get():+ pass # status reads repeat this on every poll+ elif platform_config.extra.get("_enabled_explicit"):logger.warning("Relay connector is configured via GATEWAY_RELAY_URL; ""disabling directly-connected platform '%s' even though "@@ -349,18 +363,83 @@ def _scrub_explicit_markers(config: GatewayConfig) -> None:platform_config.extra.pop("_enabled_explicit", None)-def _apply_env_overrides(config: GatewayConfig) -> None:+def _apply_env_overrides(config: GatewayConfig, *, only: Optional[Platform] = None) -> None:"""Apply environment variable overrides to *config*.Order: plugin platforms' declared env rows, then the core-only rows (api_server, webhook,msgraph_webhook; each touches only its own platform), then the registry enable pass, relaydisabling (needs every platform's final ``enabled``), and the marker scrub, which must be last.+ ``only`` limits the plugin passes to that built-in platform's own entry and bundled env rows+ (no per-call manifest scan; see ``builtin_platform_status``)."""- entries = _configured_plugin_entries(config)- _apply_plugin_env_overrides(config, entries + _bundled_env_fallbacks(config, entries))+ if only is None:+ entries = _configured_plugin_entries(config)+ else:+ entry = _discovered_registry_entry(only)+ entries = [entry] if entry is not None else []+ _apply_plugin_env_overrides(config, entries + _bundled_env_fallbacks(config, entries, only=only))_api_server(config)_webhook(config)_msgraph_webhook(config)_enable_plugin_platforms_from_env(config, entries)_relay(config)_scrub_explicit_markers(config)+++def builtin_platform_status(platform_id: str, yaml_cfg: dict) -> Optional[tuple[bool, bool]]:+ """``(enabled, connected)`` as the gateway decides them for one built-in platform of the profile+ whose config.yaml is *yaml_cfg*, with env read through the bound secret scope; None for a+ plugin-only id.++ For judging one platform of a profile that is not the process's own (the dashboard's Channels+ page): ``load_gateway_config()`` there enumerates that profile's platform plugins and constructs+ ``Platform(<plugin id>)`` for them, process-wide pseudo-members every other profile then sees.+ So only this platform's and the relay's blocks (the relay can disable it) go through the+ loader's own steps (section merge, administrator-pinned keys, top-level bridge; see+ ``load_yaml_layer``), which also record an explicit ``enabled`` for the env pass. The env pass's+ logs and one-time warnings are held back.+ """+ if platform_id not in _BUILTIN_PLATFORM_VALUES:+ return None+ from gateway.config_loader import (+ _apply_managed_extra, bridge_platform_shared_keys, merge_platform_sections, snapshot_authored_extra,+ )+ from hermes_cli.managed_scope import apply_managed_overlay++ platform = Platform(platform_id)+ names = {platform_id, Platform.RELAY.value}+ top, nested = _platform_layers(yaml_cfg, names)+ platforms = merge_platform_sections(top, nested, gw_data={})+ authored = snapshot_authored_extra(platforms) # no gateway.json layer here: the merge is config.yaml only+ managed_top, managed_nested = _platform_layers(apply_managed_overlay({}), names)+ _apply_managed_extra(authored, {**managed_top, "gateway": managed_nested}, platforms)+ bridge_platform_shared_keys(top, nested["platforms"], {}, platforms, [platform, Platform.RELAY], authored=authored)+ for block in platforms.values():+ block.pop("home_channel", None) # status needs none; HomeChannel.from_dict can raise or name another platform+ config = GatewayConfig.from_dict({"platforms": platforms})+ token = _STATUS_READ.set(True)+ try:+ _apply_env_overrides(config, only=platform)+ platform_config = config.platforms.get(platform)+ if platform_config is None:+ return False, False+ return bool(platform_config.enabled), config._is_platform_connected(platform, platform_config)+ finally:+ _STATUS_READ.reset(token)+++def _platform_layers(yaml_cfg: dict, names: set) -> tuple[dict, dict]:+ """*yaml_cfg*'s platform blocks for *names* only, as the loader's two inputs: the root layer+ (``platforms.<id>`` and top-level ``<id>:``) and the ``gateway:`` layer."""+ gateway_section = yaml_cfg.get("gateway") if isinstance(yaml_cfg.get("gateway"), dict) else {}+ top = {"platforms": _only_keys(yaml_cfg.get("platforms"), names), **_only_keys(yaml_cfg, names)}+ nested = {"platforms": _only_keys(gateway_section.get("platforms"), names), **_only_keys(gateway_section, names)}+ return top, nested+++def _only_keys(section, names: set) -> dict:+ """Copies of *section*'s entries named in *names* (no others reach the loader's ``Platform(key)``+ probes, and the merge and bridge, which write into blocks they reuse, never touch the caller's)."""+ if not isinstance(section, dict):+ return {}+ return {key: copy.deepcopy(value) for key, value in section.items() if key in names}diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.pyindex 19902f67f6f..b62875a229b 100644--- a/hermes_cli/web_routers/messaging.py+++ b/hermes_cli/web_routers/messaging.py@@ -17,6 +17,7 @@ import timeimport urllib.parsefrom datetime import datetime, timezone, UTCfrom pathlib import Path+from collections.abc import Collectionfrom typing import Any, Optionalfrom fastapi import APIRouter, HTTPException@@ -52,6 +53,8 @@ _telegram_onboarding_request_sync = late("_telegram_onboarding_request_sync", "h_whatsapp_session_path = late("_whatsapp_session_path", "hermes_cli.web_server_messaging")_write_platform_enabled = late("_write_platform_enabled", "hermes_cli.web_server_messaging")load_env = late("load_env", "hermes_cli.config")+get_secret_source_values = late("get_secret_source_values", "hermes_cli.env_loader")+builtin_platform_status = late("builtin_platform_status", "gateway.config_env")load_config = late("load_config", "hermes_cli.config")read_runtime_status = late("read_runtime_status", "gateway.status")remove_env_value = late("remove_env_value", "hermes_cli.config")@@ -156,37 +159,31 @@ def _require_platform(platform_id: str) -> dict[str, Any]:return entry-def _scoped_secret_keys() -> frozenset[str]:- try:- config = load_config()- onepassword = ((config.get("secrets") or {}).get("onepassword") or {})- mappings = onepassword.get("env") or {}- return frozenset(key for key, reference in mappings.items() if key and reference)- except Exception:- return frozenset()--def _platform_enablement(- platform_id: str, entry: dict[str, Any], env_on_disk: dict[str, str], scoped: bool+ platform_id: str, entry: dict[str, Any], env_on_disk: dict[str, str], scoped: bool,+ source_keys: Collection[str] = (),) -> tuple[bool, bool, dict | None]:- """(enabled, configured, home_channel). Profile-scoped: derive from the profile's- config.yaml + .env only — load_gateway_config()'s env-override layer reads- os.environ and would leak the root install's tokens into the profile's state."""+ """(enabled, configured, home_channel). Profile-scoped: the profile's config.yaml, .env and+ enabled secret sources only, never ``load_gateway_config()`` (see ``builtin_platform_status``)."""required = entry["required_env"]if scoped:- secret_keys = _scoped_secret_keys()- configured = all(env_on_disk.get(key) or key in secret_keys for key in required) if required else False+ # ``source_keys``: names the profile's enabled secret sources resolved (1Password, Bitwarden, a plugin).+ configured = bool(required) and all(env_on_disk.get(key) or key in source_keys for key in required)try:- plat_cfg = (load_config().get("platforms") or {}).get(platform_id)+ config = load_config()+ plat_cfg = (config.get("platforms") or {}).get(platform_id)plat_cfg = plat_cfg if isinstance(plat_cfg, dict) else {}- if not required:- configured = bool(plat_cfg)hc = plat_cfg.get("home_channel")- # Setup writes credentials without a platforms entry; explicit disable wins.- raw_enabled = plat_cfg.get("enabled")- enabled = False if raw_enabled is False else bool(raw_enabled) or configured+ status = None if required else builtin_platform_status(platform_id, config)+ if status is not None:+ enabled, configured = status # token-free built-in: nothing to judge but the gateway's verdict+ else:+ # Setup writes credentials without a platforms entry; explicit disable wins.+ raw_enabled = plat_cfg.get("enabled")+ enabled = False if raw_enabled is False else bool(raw_enabled) or configuredhome_channel = hc if isinstance(hc, dict) else None- except Exception:+ except Exception: # health: allow BLE001 -- one platform's bad config must not blank the page+ _log.debug("Profile-scoped status for %s failed", platform_id, exc_info=True)enabled, home_channel = False, Nonereturn enabled, configured, home_channeltry:@@ -206,7 +203,7 @@ def _platform_enablement(def _messaging_platform_payload(entry: dict[str, Any], env_on_disk: dict[str, str], runtime: dict | None,- scoped: bool = False, profile_home: Optional[Path] = None,+ scoped: bool = False, profile_home: Optional[Path] = None, source_keys: Collection[str] = (),) -> dict[str, Any]:platform_id = entry["id"]rt = runtime if isinstance(runtime, dict) else {}@@ -241,12 +238,12 @@ def _messaging_platform_payload(for key in entry["env_vars"]:value, info = env_value(key), _messaging_env_info(key)env_vars.append({- "key": key, "required": key in entry["required_env"], "is_set": bool(value) or (scoped and key in _scoped_secret_keys()),+ "key": key, "required": key in entry["required_env"], "is_set": bool(value) or key in source_keys,"redacted_value": redacted_credential_preview(value),"value": value if info["is_list"] else None, **info,})- enabled, configured, home_channel = _platform_enablement(platform_id, entry, env_on_disk, scoped)+ enabled, configured, home_channel = _platform_enablement(platform_id, entry, env_on_disk, scoped, source_keys)if gateway_running and runtime_platform.get("mirrored_from"):# Served secondary: the default's shared listener already answers this platform at# /p/<profile>/... (enabling it locally 409s), so the secondary's own empty config@@ -303,7 +300,12 @@ def _platform_payloads(scoped_dir: Optional[Path], entries) -> list[dict[str, An# ``hermes --profile X serve``).own_home = scoped_dir if scoped_dir is not None else get_process_hermes_home()runtime = served_profile_runtime(own_home, runtime) or runtime- return [_messaging_platform_payload(entry, env_on_disk, runtime, scoped=scoped_dir is not None, profile_home=scoped_dir)+ # Credentials a secret manager supplies have no .env line; only values the profile's enabled+ # sources resolved (into its secret scope, by ``_profile_scope``) count, and an empty one is unset.+ source_values = get_secret_source_values(scoped_dir) if scoped_dir is not None else {}+ source_keys = frozenset(key for key, value in source_values.items() if str(value).strip())+ return [_messaging_platform_payload(entry, env_on_disk, runtime, scoped=scoped_dir is not None,+ profile_home=scoped_dir, source_keys=source_keys)for entry in entries]diff --git a/tests/gateway/test_builtin_platform_status.py b/tests/gateway/test_builtin_platform_status.pynew file mode 100644index 00000000000..81566c45279--- /dev/null+++ b/tests/gateway/test_builtin_platform_status.py@@ -0,0 +1,77 @@+"""gateway.config_env.builtin_platform_status: the gateway's (enabled, connected) for one built-in platform,+from a profile's config dict, without load_gateway_config(). Run here without a multiplexer, so the env pass's+explicit-disable rule is visible (the dashboard's scoped reads run as a multiplex secondary, where the shared-+listener guard keeps env-only api_server/webhook off anyway)."""++from __future__ import annotations++import json++import pytest++from gateway.config_env import builtin_platform_status++_KEY = "k" * 32++[email protected](autouse=True)+def _plain_process(monkeypatch):+ from agent import secret_scope+ from hermes_cli import managed_scope++ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", False)+ for name in ("GATEWAY_RELAY_URL", "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS"): # not in the suite's env filter+ monkeypatch.delenv(name, raising=False)+ managed_scope.invalidate_managed_cache()+ yield+ managed_scope.invalidate_managed_cache()+++def test_plugin_only_ids_are_not_judged():+ assert builtin_platform_status("workchat", {"platforms": {"workchat": {"enabled": True}}}) is None+++def test_the_callers_config_is_left_alone():+ config = {"platforms": {"webhook": {"extra": {}}}, "webhook": {"enabled": True, "port": 9}}+ before = json.dumps(config, sort_keys=True)++ builtin_platform_status("webhook", config)++ assert json.dumps(config, sort_keys=True) == before++[email protected]("config", [+ pytest.param({"platforms": {"api_server": {"enabled": False}}}, id="platforms"),+ pytest.param({"gateway": {"platforms": {"api_server": {"enabled": False}}}}, id="gateway-platforms"),+ pytest.param({"api_server": {"enabled": False}}, id="toplevel"),+])+def test_explicit_disable_beats_an_env_key(monkeypatch, config):+ monkeypatch.setenv("API_SERVER_KEY", _KEY)++ assert builtin_platform_status("api_server", config) == (False, True)+ assert builtin_platform_status("api_server", {}) == (True, True) # the same key alone enables it+++def test_an_administrator_pinned_key_outranks_the_users_empty_one(monkeypatch, tmp_path):+ from hermes_cli import managed_scope++ managed = tmp_path / "managed"+ managed.mkdir()+ (managed / "config.yaml").write_text(json.dumps({"api_server": {"key": _KEY}}), encoding="utf-8")+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ managed_scope.invalidate_managed_cache()+ user = {"platforms": {"api_server": {"enabled": True, "extra": {"key": ""}}}}++ # load_config() hands the dashboard the user config with the managed overlay deep-merged in.+ assert builtin_platform_status("api_server", managed_scope.apply_managed_overlay(user)) == (True, True)++ # ... which is the gateway's own verdict for that profile.+ from gateway.config import Platform, load_gateway_config++ home = tmp_path / "home"+ home.mkdir()+ (home / "config.yaml").write_text(json.dumps(user), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ gateway = load_gateway_config()+ api_server = gateway.platforms[Platform.API_SERVER]+ assert (api_server.enabled, gateway._is_platform_connected(Platform.API_SERVER, api_server)) == (True, True)diff --git a/tests/hermes_cli/test_web_messaging_platform_profile_scope.py b/tests/hermes_cli/test_web_messaging_platform_profile_scope.pyindex 4e969163b80..f2ab6155671 100644--- a/tests/hermes_cli/test_web_messaging_platform_profile_scope.py+++ b/tests/hermes_cli/test_web_messaging_platform_profile_scope.py@@ -57,6 +57,52 @@ def client(homes):return c+def test_a_gateway_block_for_a_profile_plugin_stays_in_that_profile(client, homes):+ """A ``gateway.<plugin id>`` block next to a token-free built-in must not register the profile's+ plugin process-wide while the dashboard reads the built-in's status."""+ from gateway.config import Platform++ _, work = homes+ (work / "config.yaml").write_text(yaml.safe_dump({+ "plugins": {"enabled": ["workchat"]},+ "gateway": {"workchat": {"enabled": True}},+ "platforms": {"webhook": {"enabled": True}},+ }), encoding="utf-8")+ leaked_before = "workchat" in Platform._value2member_map_ # an earlier test may have registered it++ scoped = client.get("/api/messaging/platforms", params={"profile": "work"}).json()["platforms"]+ root_ids = {p["id"] for p in client.get("/api/messaging/platforms").json()["platforms"]}++ assert next(p for p in scoped if p["id"] == "webhook")["configured"] is True+ assert ("workchat" in Platform._value2member_map_) is leaked_before+ assert "workchat" not in root_ids+++def test_a_managed_gateway_block_for_a_profile_plugin_stays_in_that_profile(client, homes, tmp_path, monkeypatch):+ """The administrator's config goes through the same filtered steps: a managed ``gateway.<plugin id>``+ block must not register the profile's plugin process-wide either."""+ from gateway.config import Platform+ from hermes_cli import managed_scope++ _, work = homes+ managed = tmp_path / "managed"+ managed.mkdir()+ (managed / "config.yaml").write_text(yaml.safe_dump({"gateway": {"workchat": {"enabled": True}}}), encoding="utf-8")+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ managed_scope.invalidate_managed_cache()+ (work / "config.yaml").write_text(yaml.safe_dump({+ "plugins": {"enabled": ["workchat"]}, "platforms": {"webhook": {"enabled": True}},+ }), encoding="utf-8")+ leaked_before = "workchat" in Platform._value2member_map_ # an earlier test may have registered it+ try:+ scoped = client.get("/api/messaging/platforms", params={"profile": "work"}).json()["platforms"]+ finally:+ managed_scope.invalidate_managed_cache()++ assert next(p for p in scoped if p["id"] == "webhook")["configured"] is True+ assert ("workchat" in Platform._value2member_map_) is leaked_before++def test_a_platform_installed_only_in_the_target_profile_is_editable_there(client, homes):root, work = homeslisted = client.get("/api/messaging/platforms?profile=work").json()diff --git a/tests/hermes_cli/test_web_server_messaging_profiles.py b/tests/hermes_cli/test_web_server_messaging_profiles.pyindex 6c470c9bb68..60282b54d11 100644--- a/tests/hermes_cli/test_web_server_messaging_profiles.py+++ b/tests/hermes_cli/test_web_server_messaging_profiles.py@@ -67,61 +67,121 @@ def _env_field(platform, key):return next(f for f in platform["env_vars"] if f["key"] == key)-def test_scoped_platform_without_required_env_is_configured_when_declared(- client, isolated_profiles, monkeypatch-):- """QR/onboarding platforms with no required env must use their config declaration."""- import hermes_cli.web_routers.messaging as messaging+def _on(platform_id, **block):+ return {"platforms": {platform_id: {"enabled": True, **block}}}++def no_platform_env(monkeypatch):+ """The token-free tables below assume none of these leak in from the host (a hosted container+ stamps GATEWAY_RELAY_URL, which disables direct platforms)."""+ for name in ("GATEWAY_RELAY_URL", "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "WHATSAPP_ENABLED", "WEBHOOK_ENABLED",+ "API_SERVER_ENABLED", "API_SERVER_KEY", "MSGRAPH_WEBHOOK_ENABLED", "MSGRAPH_WEBHOOK_CLIENT_STATE"):+ monkeypatch.delenv(name, raising=False)++[email protected]("platform_id, config, env, enabled, configured", [+ # Dashboard QR onboarding writes both; ``hermes whatsapp`` writes only the env flag.+ pytest.param("whatsapp", _on("whatsapp"), "WHATSAPP_ENABLED=true\n", True, True, id="whatsapp-paired"),+ pytest.param("whatsapp", {}, "WHATSAPP_ENABLED=true\n", True, True, id="whatsapp-env-flag-only"),+ # Declared but never paired: the gateway would not start the bridge.+ pytest.param("whatsapp", _on("whatsapp"), "", True, False, id="whatsapp-unpaired"),+ # The flag off wins over an enabled block (the explicit enable stops the plugin's re-enable pass).+ pytest.param("whatsapp", _on("whatsapp", extra={"mode": "bot"}), "WHATSAPP_ENABLED=false\n",+ False, False, id="whatsapp-flag-off"),+ # The dashboard's disable writes only ``enabled: false``; the leftover env flag must not re-enable it.+ pytest.param("whatsapp", {"platforms": {"whatsapp": {"enabled": False}}}, "WHATSAPP_ENABLED=true\n",+ False, True, id="whatsapp-disabled-flag-on"),+ pytest.param("webhook", _on("webhook"), "", True, True, id="webhook"),+ # Settings without ``enabled``: the gateway leaves it off, so the card must not say enabled.+ pytest.param("webhook", {"platforms": {"webhook": {"extra": {"port": 8123}}}}, "", False, True, id="webhook-not-enabled"),+ pytest.param("api_server", {}, "", False, False, id="api-server-absent"),+ # The API server refuses to start without a usable key.+ pytest.param("api_server", _on("api_server"), "", True, False, id="api-server-no-key"),+ pytest.param("api_server", _on("api_server", extra={"key": "k" * 24}), "", True, True, id="api-server-key"),+ pytest.param("api_server", {"platforms": {"api_server": {"enabled": False}}}, "API_SERVER_KEY=" + "k" * 32 + "\n",+ False, True, id="api-server-disabled-env-key"),+ # A top-level block is the gateway's too, explicit disable included.+ pytest.param("whatsapp", {"whatsapp": {"enabled": False}}, "WHATSAPP_ENABLED=true\n", False, True,+ id="whatsapp-toplevel-disabled-flag-on"),+ pytest.param("msgraph_webhook", _on("msgraph_webhook"), "", True, False, id="msgraph-no-client-state"),+ pytest.param("msgraph_webhook", _on("msgraph_webhook", extra={"client_state": "state"}), "", True, True,+ id="msgraph-client-state"),+ pytest.param("msgraph_webhook", {"platforms": {"msgraph_webhook": {"enabled": False}}},+ "MSGRAPH_WEBHOOK_ENABLED=true\nMSGRAPH_WEBHOOK_CLIENT_STATE=state\n", False, True,+ id="msgraph-disabled-env-on"),+ pytest.param("relay", _on("relay"), "", True, False, id="relay-no-url"),+])+def test_scoped_token_free_platform_status_matches_the_gateway(+ client, isolated_profiles, no_platform_env, platform_id, config, env, enabled, configured+):+ """Token-free built-ins show exactly what the profile's gateway decides for them."""worker_home = isolated_profiles["worker_alpha"]- (worker_home / "config.yaml").write_text(- yaml.safe_dump({"platforms": {"whatsapp": {"enabled": True}}}),- encoding="utf-8",- )- monkeypatch.setattr(messaging, "load_env", lambda: {})- monkeypatch.setattr(messaging, "load_config", lambda: {"platforms": {"whatsapp": {"enabled": True}}})+ (worker_home / "config.yaml").write_text(yaml.safe_dump(config), encoding="utf-8")+ (worker_home / ".env").write_text(env, encoding="utf-8")- resp = client.get(- "/api/messaging/platforms", params={"profile": "worker_alpha"}- )+ resp = client.get("/api/messaging/platforms", params={"profile": "worker_alpha"})assert resp.status_code == 200- whatsapp = next(p for p in resp.json()["platforms"] if p["id"] == "whatsapp")- assert whatsapp["configured"] is True+ platform = next((p for p in resp.json()["platforms"] if p["id"] == platform_id), None)+ assert platform is not None, platform_id+ assert (platform["enabled"], platform["configured"]) == (enabled, configured)+++_MSGRAPH = {"msgraph_webhook": {"enabled": True, "extra": {"client_state": "state"}}}++[email protected]("config, direct_enabled", [+ pytest.param({"platforms": {**_MSGRAPH, "relay": {"enabled": True}}}, False, id="relay-owns-connections"),+ pytest.param({"platforms": {**_MSGRAPH, "relay": {"enabled": False}}}, True, id="relay-opted-out"),+ pytest.param({"platforms": _MSGRAPH, "relay": {"enabled": False}}, True, id="relay-opted-out-toplevel"),+])+def test_scoped_status_follows_the_profiles_relay_block(+ client, isolated_profiles, no_platform_env, monkeypatch, config, direct_enabled+):+ """A container's relay URL disables direct platforms unless the profile's relay is turned off."""+ monkeypatch.setenv("GATEWAY_RELAY_URL", "https://relay.example.test")+ worker_home = isolated_profiles["worker_alpha"]+ (worker_home / "config.yaml").write_text(yaml.safe_dump(config), encoding="utf-8")++ platforms = client.get("/api/messaging/platforms", params={"profile": "worker_alpha"}).json()["platforms"]+ msgraph = next(p for p in platforms if p["id"] == "msgraph_webhook")+ assert (msgraph["enabled"], msgraph["configured"]) == (direct_enabled, True)-def test_scoped_platform_with_onepassword_mapping_is_configured(- client, isolated_profiles, monkeypatch+[email protected]("source_enabled, token, counts", [+ pytest.param(True, "1" * 9 + ":" + "a" * 35, True, id="enabled"),+ pytest.param(False, "1" * 9 + ":" + "a" * 35, False, id="disabled"),+ pytest.param(True, "", False, id="enabled-empty-value"),+ pytest.param(True, " ", False, id="enabled-blank-value"),+])+def test_scoped_onepassword_credential_counts_only_when_the_source_is_enabled(+ client, isolated_profiles, monkeypatch, source_enabled, token, counts):- """Profile-scoped dashboard reads must recognize secret-source mappings."""- import hermes_cli.web_routers.messaging as messaging+ """A 1Password-mapped token is set/configured only when the profile's source is on and resolves it+ to a value."""+ from agent.secret_sources.base import FetchResult+ from agent.secret_sources.onepassword import OnePasswordSource++ fetched = []++ def fake_fetch(self, cfg, home_path):+ fetched.append(home_path)+ return FetchResult(secrets={"TELEGRAM_BOT_TOKEN": token})+ monkeypatch.setattr(OnePasswordSource, "fetch", fake_fetch)worker_home = isolated_profiles["worker_alpha"]- (worker_home / "config.yaml").write_text(- yaml.safe_dump({- "platforms": {"telegram": {"enabled": True}},- "secrets": {"onepassword": {"env": {"TELEGRAM_BOT_TOKEN": "op://vault/item/credential"}}},- }),- encoding="utf-8",- )- monkeypatch.setattr(messaging, "load_env", lambda: {})- monkeypatch.setattr(- messaging,- "load_config",- lambda: {- "platforms": {"telegram": {"enabled": True}},- "secrets": {"onepassword": {"env": {"TELEGRAM_BOT_TOKEN": "op://vault/item/credential"}}},- },- )+ (worker_home / "config.yaml").write_text(yaml.safe_dump({+ "secrets": {"onepassword": {"enabled": source_enabled,+ "env": {"TELEGRAM_BOT_TOKEN": "op://vault/item/credential"}}},+ }), encoding="utf-8")- resp = client.get(- "/api/messaging/platforms", params={"profile": "worker_alpha"}- )+ telegram = _telegram(client.get("/api/messaging/platforms", params={"profile": "worker_alpha"}).json())- assert resp.status_code == 200- telegram = _telegram(resp.json())- assert telegram["configured"] is True- assert _env_field(telegram, "TELEGRAM_BOT_TOKEN")["is_set"] is True+ assert telegram["configured"] is counts+ assert _env_field(telegram, "TELEGRAM_BOT_TOKEN")["is_set"] is counts+ assert bool(fetched) is source_enabledclass TestProfileScopedMessagingReads: