Skip to content

The agent that grows with you

fix(gateway): split check_fn (passive probe) from ensure_deps_fn (active installer)

kshitij0d32607c62ea
diff --git a/gateway/config.py b/gateway/config.py
index b39ae8cfcb4..6dc18fda856 100644
--- a/gateway/config.py
+++ b/gateway/config.py
@@ -2522,13 +2522,12 @@ def _apply_env_overrides(config: GatewayConfig) -> None:
# Enablement gate (#31116): when a plugin registers ``is_connected``
# (the "has the user actually configured credentials for this?" check),
# we MUST consult it before flipping ``enabled = True``. Otherwise
- # ``check_fn`` alone — which for adapter plugins typically just
- # verifies the SDK is importable / lazy-installs it — silently enables
- # platforms the user never opted into, and the gateway then tries to
- # connect to Discord / Teams / Google Chat with no token and emits
- # noisy retry-forever errors. ``_platform_status`` was already fixed
- # for the same bug class in commit 7849a3d73; this is the runtime
- # counterpart.
+ # ``check_fn`` alone — a passive "is the SDK importable?" probe —
+ # silently enables platforms the user never opted into, and the gateway
+ # then tries to connect to Discord / Teams / Google Chat with no token
+ # and emits noisy retry-forever errors. ``_platform_status`` was
+ # already fixed for the same bug class in commit 7849a3d73; this is the
+ # runtime counterpart.
try:
from hermes_cli.plugins import discover_plugins
discover_plugins() # idempotent
@@ -2623,20 +2622,25 @@ def _apply_env_overrides(config: GatewayConfig) -> None:
)
continue
# Verify dependencies LAST — only for platforms that are already
- # enabled or passed the credential gate above. For adapter plugins
- # ``check_fn`` lazy-INSTALLS the platform SDK (pip) as a side
- # effect, so running it as an unconditional sweep over every
- # registered platform made ``load_gateway_config()`` pip-install
- # Discord/Telegram/Slack/Feishu/Dingtalk on every call — including
- # the desktop/dashboard readiness probe (``GET /api/status``, which
- # awaits this synchronously) — even when the user configured none
- # of them. That blocked startup until every install finished and
- # caused the desktop app to time out and boot-loop (stuck at 94%).
+ # enabled or passed the credential gate above. ``check_fn`` is a
+ # PASSIVE probe (never installs); a platform whose deps are
+ # missing but which registered ``ensure_deps_fn`` still gets
+ # enabled here — the registry's ``create_adapter()`` runs the
+ # active installer at gateway start, when the user actually
+ # wants the platform up. Historically the ACTIVE installer was
+ # wired as ``check_fn`` and this sweep pip-installed
+ # Discord/Telegram/Slack/Feishu/Dingtalk SDKs on every
+ # ``load_gateway_config()`` call — including the desktop/dashboard
+ # readiness probe (``GET /api/status``) — blocking startup until
+ # every install finished and boot-looping the desktop app at 94%.
+ # The check_fn/ensure_deps_fn split (#79812) makes that
+ # impossible by construction.
try:
- if not entry.check_fn():
- continue
+ deps_ok = bool(entry.check_fn())
except Exception as e:
logger.debug("check_fn for %s raised: %s", entry.name, e)
+ deps_ok = False
+ if not deps_ok and entry.ensure_deps_fn is None:
continue
if platform not in config.platforms:
config.platforms[platform] = PlatformConfig()
diff --git a/gateway/platform_registry.py b/gateway/platform_registry.py
index b3c19af1bcb..368dfc917cc 100644
--- a/gateway/platform_registry.py
+++ b/gateway/platform_registry.py
@@ -50,7 +50,11 @@ class PlatformEntry:
# (e.g. passing extra kwargs, wrapping in try/except).
adapter_factory: Callable[[Any], Any]
- # Returns True when the platform's dependencies are available.
+ # PASSIVE dependency probe: returns True when the platform's dependencies
+ # are available RIGHT NOW. Must be side-effect free — it is called from
+ # status displays (``hermes setup``, ``hermes status``, the dashboard
+ # readiness probe) and the config enablement pass, none of which may
+ # trigger a pip install. Put install logic in ``ensure_deps_fn`` instead.
check_fn: Callable[[], bool]
# Optional: given a PlatformConfig, is it properly configured?
@@ -58,6 +62,23 @@ class PlatformEntry:
# fail at connect() time with a descriptive error.
validate_config: Optional[Callable[[Any], bool]] = None
+ # ACTIVE dependency installer: make the platform's dependencies available,
+ # installing them (pip / lazy_deps) if needed. Returns True once deps are
+ # importable, False if they could not be installed. Called by
+ # ``create_adapter()`` when ``check_fn`` returns False — i.e. exactly at
+ # the moment the gateway is about to bring the platform up and the user
+ # has it enabled/configured. None = no auto-install; a False ``check_fn``
+ # is then a hard block (correct for platforms with no optional deps).
+ #
+ # Why two fields (#79812): when the ACTIVE installer was registered as
+ # ``check_fn``, every status display pip-installed SDKs as a side effect
+ # (desktop boot-loop at 94%, see gateway/config.py enablement comments);
+ # when the PASSIVE probe was registered instead, ``create_adapter()``
+ # returned None before ``connect()`` could lazy-install, so the deps
+ # never installed at all (Teams deadlock). Splitting the two roles makes
+ # both call sites correct by construction.
+ ensure_deps_fn: Optional[Callable[[], bool]] = None
+
# Optional: given a PlatformConfig, is the platform connected/enabled?
# Used by ``GatewayConfig.get_connected_platforms()`` and setup UI status.
# If None, falls back to ``validate_config`` or ``check_fn``.
@@ -280,7 +301,8 @@ class PlatformRegistry:
Returns None if:
- No entry registered for *name*
- - check_fn() returns False (missing deps)
+ - check_fn() returns False and deps can't be installed
+ (no ensure_deps_fn, or ensure_deps_fn() returned False)
- validate_config() returns False (misconfigured)
- The factory raises an exception
"""
@@ -290,7 +312,34 @@ class PlatformRegistry:
if entry is None:
return None
- if not entry.check_fn():
+ deps_ok = False
+ try:
+ deps_ok = bool(entry.check_fn())
+ except Exception as e:
+ logger.warning(
+ "Platform '%s' check_fn raised: %s", entry.label, e
+ )
+ if not deps_ok and entry.ensure_deps_fn is not None:
+ # Deps missing but the platform can install them on demand.
+ # This is the ONE place the active installer runs in the adapter
+ # path: the platform is enabled+configured and the gateway is
+ # about to connect it, so an install is what the user wants
+ # (#79812 — Teams' installer previously lived behind this very
+ # gate inside connect(), which could never be reached).
+ logger.info(
+ "Platform '%s' dependencies missing — attempting install...",
+ entry.label,
+ )
+ try:
+ deps_ok = bool(entry.ensure_deps_fn())
+ except Exception as e:
+ logger.warning(
+ "Platform '%s' dependency install raised: %s",
+ entry.label,
+ e,
+ )
+ deps_ok = False
+ if not deps_ok:
hint = f" ({entry.install_hint})" if entry.install_hint else ""
logger.warning(
"Platform '%s' requirements not met%s",
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 1d96bdad335..0ae0f7a32a4 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -964,12 +964,20 @@ class PluginContext:
"""Register a gateway platform adapter.
The adapter_factory receives a ``PlatformConfig`` and returns a
- ``BasePlatformAdapter`` subclass instance. The gateway calls
- ``check_fn()`` before instantiation to verify dependencies.
+ ``BasePlatformAdapter`` subclass instance.
+
+ ``check_fn`` is a PASSIVE dependency probe — "are deps importable
+ right now?". It must never install anything: status displays and
+ config loading call it freely. If your platform's SDK is
+ lazy-installable, pass the ACTIVE installer separately as
+ ``ensure_deps_fn`` (forwarded via ``entry_kwargs``); the gateway
+ calls it from ``create_adapter()`` when ``check_fn`` is False,
+ right before connecting the platform.
Extra keyword arguments are forwarded to ``PlatformEntry`` (e.g.
- ``setup_fn``, ``emoji``, ``allowed_users_env``, ``platform_hint``).
- Unknown keys raise TypeError from the dataclass constructor.
+ ``setup_fn``, ``emoji``, ``allowed_users_env``, ``platform_hint``,
+ ``ensure_deps_fn``). Unknown keys raise TypeError from the
+ dataclass constructor.
Example::
diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.py
index 9ea8330854c..e282067e46a 100644
--- a/plugins/platforms/dingtalk/adapter.py
+++ b/plugins/platforms/dingtalk/adapter.py
@@ -162,6 +162,18 @@ EXT_MAP = {
}
+def dingtalk_deps_present() -> bool:
+ """PASSIVE probe: are dingtalk-stream/httpx importable right now?
+
+ Registry ``check_fn`` — called from status displays and config loading,
+ so it must never install anything. The ACTIVE lazy-installer
+ (``check_dingtalk_requirements``) is registered as ``ensure_deps_fn``
+ and runs from ``create_adapter()`` when this returns False (#79812).
+ Credentials are gated separately via ``is_connected``/``validate_config``.
+ """
+ return DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE
+
+
def check_dingtalk_requirements() -> bool:
"""Check if DingTalk dependencies are available and configured.
@@ -1881,7 +1893,8 @@ def register(ctx) -> None:
name="dingtalk",
label="DingTalk",
adapter_factory=_build_adapter,
- check_fn=check_dingtalk_requirements,
+ check_fn=dingtalk_deps_present,
+ ensure_deps_fn=check_dingtalk_requirements,
is_connected=_is_connected,
validate_config=_is_connected,
required_env=["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"],
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 22d4c2af2da..cd3b2b0166d 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -432,6 +432,17 @@ def _profile_scoped_config_load() -> bool:
return False
+def discord_deps_present() -> bool:
+ """PASSIVE probe: is discord.py importable right now?
+
+ Registry ``check_fn`` — called from status displays and config loading,
+ so it must never install anything. The ACTIVE lazy-installer
+ (``check_discord_requirements``) is registered as ``ensure_deps_fn``
+ and runs from ``create_adapter()`` when this returns False (#79812).
+ """
+ return DISCORD_AVAILABLE
+
+
def check_discord_requirements() -> bool:
"""Check if Discord dependencies are available.
@@ -10106,7 +10117,8 @@ def register(ctx) -> None:
name="discord",
label="Discord",
adapter_factory=_build_adapter,
- check_fn=check_discord_requirements,
+ check_fn=discord_deps_present,
+ ensure_deps_fn=check_discord_requirements,
is_connected=_is_connected,
required_env=["DISCORD_BOT_TOKEN"],
install_hint="Run `hermes setup` to install Discord support.",
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index 8c50942042c..6ea37ed8186 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -1447,6 +1447,26 @@ def _load_lark_oapi() -> bool:
return True
+def feishu_deps_present() -> bool:
+ """PASSIVE probe: is lark-oapi installed right now?
+
+ Registry ``check_fn`` — called from status displays and config loading,
+ so it must never install anything. Uses ``feature_missing`` (cheap
+ importlib.metadata lookups) instead of importing the SDK, which is
+ deferred to ``_load_lark_oapi`` at connect time. The ACTIVE
+ lazy-installer (``check_feishu_requirements``) is registered as
+ ``ensure_deps_fn`` and runs from ``create_adapter()`` when this
+ returns False (#79812).
+ """
+ if FEISHU_AVAILABLE:
+ return True
+ try:
+ from tools.lazy_deps import feature_missing
+ return not feature_missing("platform.feishu")
+ except Exception: # pragma: no cover — defensive
+ return False
+
+
def check_feishu_requirements() -> bool:
"""Ensure Feishu dependencies are installed without importing the SDK."""
if FEISHU_AVAILABLE:
@@ -5857,7 +5877,8 @@ def register(ctx) -> None:
name="feishu",
label="Feishu / Lark",
adapter_factory=_build_adapter,
- check_fn=check_feishu_requirements,
+ check_fn=feishu_deps_present,
+ ensure_deps_fn=check_feishu_requirements,
is_connected=_is_connected,
validate_config=_is_connected,
required_env=["FEISHU_APP_ID", "FEISHU_APP_SECRET"],
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 67dccc8a5b1..9745ffba596 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -888,6 +888,22 @@ def _startup_env_secret(name: str) -> str:
return os.getenv(name, "").strip()
+def matrix_deps_present() -> bool:
+ """PASSIVE probe: are the ``platform.matrix`` packages installed?
+
+ Registry ``check_fn`` — called from status displays and config loading,
+ so it must never install anything. ``feature_missing`` is cheap
+ (per-spec importlib.metadata lookups). The ACTIVE lazy-installer
+ (``check_matrix_requirements``) is registered as ``ensure_deps_fn``
+ and runs from ``create_adapter()`` when this returns False (#79812).
+ """
+ try:
+ from tools.lazy_deps import feature_missing
+ return not feature_missing("platform.matrix")
+ except Exception: # pragma: no cover — defensive
+ return False
+
+
def check_matrix_requirements() -> bool:
"""Return True if the Matrix adapter can be used.
@@ -5276,7 +5292,8 @@ def register(ctx) -> None:
name="matrix",
label="Matrix",
adapter_factory=_build_adapter,
- check_fn=check_matrix_requirements,
+ check_fn=matrix_deps_present,
+ ensure_deps_fn=check_matrix_requirements,
is_connected=_is_connected,
required_env=["MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"],
install_hint="pip install 'mautrix[encryption]'",
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index ee50a4578ca..dc4b94ead03 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -283,6 +283,17 @@ class _ThreadContextCache:
messages: List[Dict[str, Any]] = field(default_factory=list)
+def slack_deps_present() -> bool:
+ """PASSIVE probe: are slack-bolt/slack-sdk importable right now?
+
+ Registry ``check_fn`` — called from status displays and config loading,
+ so it must never install anything. The ACTIVE lazy-installer
+ (``check_slack_requirements``) is registered as ``ensure_deps_fn``
+ and runs from ``create_adapter()`` when this returns False (#79812).
+ """
+ return SLACK_AVAILABLE
+
+
def check_slack_requirements() -> bool:
"""Check if Slack dependencies are available.
@@ -9055,7 +9066,8 @@ def register(ctx) -> None:
name="slack",
label="Slack",
adapter_factory=_build_adapter,
- check_fn=check_slack_requirements,
+ check_fn=slack_deps_present,
+ ensure_deps_fn=check_slack_requirements,
is_connected=_is_connected,
required_env=["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"],
install_hint="Run `hermes setup` to install Slack support.",
diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.py
index 71a3ceaa621..980f021136f 100644
--- a/plugins/platforms/teams/adapter.py
+++ b/plugins/platforms/teams/adapter.py
@@ -642,11 +642,12 @@ async def _standalone_send(
# Keep the old name as an alias so existing test imports don't break.
-# NOTE: ``check_requirements`` is the PASSIVE probe (status / unit tests) —
-# it must never trigger a pip install. ``check_teams_requirements`` is the
-# ACTIVE lazy-installer and is the registry ``check_fn`` — same contract as
-# Discord/Slack/Telegram. ``create_adapter()`` gates on ``check_fn`` before
-# the adapter exists, so install MUST run there; ``connect()`` re-checks.
+# NOTE: ``check_requirements`` is the PASSIVE probe (registry ``check_fn``,
+# status / unit tests) — it must never trigger a pip install.
+# ``check_teams_requirements`` is the ACTIVE lazy-installer, registered as
+# ``ensure_deps_fn``: the registry's ``create_adapter()`` runs it when the
+# passive probe fails, right before the gateway connects Teams (#79812).
+# ``connect()`` re-checks defensively.
@contextmanager
def _suppress_third_party_dotenv() -> Iterator[None]:
"""No-op ``dotenv.load_dotenv`` while importing the Teams SDK (#62935).
@@ -1467,10 +1468,12 @@ def register(ctx) -> None:
name="teams",
label="Microsoft Teams",
adapter_factory=lambda cfg: TeamsAdapter(cfg),
- # Active lazy-installer — NOT the passive ``check_requirements``.
- # Registry create_adapter() returns None when check_fn is False, so a
- # passive probe permanently blocks connect() and the deps never install.
- check_fn=check_teams_requirements,
+ # PASSIVE probe — deps importable right now? Never installs, so
+ # status displays / config loading can call it freely.
+ check_fn=check_requirements,
+ # ACTIVE lazy-installer — create_adapter() calls this when check_fn
+ # is False, right before the gateway connects Teams (#79812).
+ ensure_deps_fn=check_teams_requirements,
validate_config=validate_config,
is_connected=is_connected,
required_env=["TEAMS_CLIENT_ID", "TEAMS_CLIENT_SECRET", "TEAMS_TENANT_ID"],
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index ea6258b9f2d..0a7f8dea7b1 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -392,6 +392,17 @@ def _probe_voice_duration_seconds(path: str) -> Optional[int]:
return None
+def telegram_deps_present() -> bool:
+ """PASSIVE probe: is python-telegram-bot importable right now?
+
+ Registry ``check_fn`` — called from status displays and config loading,
+ so it must never install anything. The ACTIVE lazy-installer
+ (``check_telegram_requirements``) is registered as ``ensure_deps_fn``
+ and runs from ``create_adapter()`` when this returns False (#79812).
+ """
+ return TELEGRAM_AVAILABLE
+
+
def check_telegram_requirements() -> bool:
"""Check if Telegram dependencies are available.
@@ -10131,7 +10142,8 @@ def register(ctx) -> None:
name="telegram",
label="Telegram",
adapter_factory=_build_adapter,
- check_fn=check_telegram_requirements,
+ check_fn=telegram_deps_present,
+ ensure_deps_fn=check_telegram_requirements,
is_connected=_is_connected,
required_env=["TELEGRAM_BOT_TOKEN"],
install_hint="Run `hermes setup` to install Telegram support.",
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index 715445bd236..4770ec72110 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -1911,12 +1911,16 @@ def register(ctx) -> None:
allow_update_command=True,
)
- from plugins.platforms.wecom.callback_adapter import check_wecom_callback_requirements
+ from plugins.platforms.wecom.callback_adapter import (
+ check_wecom_callback_requirements,
+ ensure_wecom_callback_requirements,
+ )
ctx.register_platform(
name="wecom_callback",
label="WeCom Callback (self-built apps)",
adapter_factory=_build_callback_adapter,
check_fn=check_wecom_callback_requirements,
+ ensure_deps_fn=ensure_wecom_callback_requirements,
is_connected=_callback_is_connected,
validate_config=_callback_is_connected,
required_env=["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"],
diff --git a/plugins/platforms/wecom/callback_adapter.py b/plugins/platforms/wecom/callback_adapter.py
index 9c447f5ce5d..c4e1a19ec54 100644
--- a/plugins/platforms/wecom/callback_adapter.py
+++ b/plugins/platforms/wecom/callback_adapter.py
@@ -69,9 +69,43 @@ MESSAGE_DEDUP_TTL_SECONDS = 300
def check_wecom_callback_requirements() -> bool:
+ """PASSIVE probe: are aiohttp/httpx/defusedxml importable right now?
+
+ Registry ``check_fn`` — must never install anything. The ACTIVE
+ lazy-installer is ``ensure_wecom_callback_requirements`` below.
+ """
return AIOHTTP_AVAILABLE and HTTPX_AVAILABLE and DEFUSEDXML_AVAILABLE
+def ensure_wecom_callback_requirements() -> bool:
+ """ACTIVE lazy-installer for the ``platform.wecom_callback`` feature.
+
+ Registered as ``ensure_deps_fn``: the registry's ``create_adapter()``
+ runs it when the passive probe fails, right before the gateway connects
+ the platform (#79812). Installs ``defusedxml`` (the only non-core dep;
+ aiohttp/httpx ship with every messaging install) and rebinds the module
+ globals. Before this hook existed, the passive ``check_fn`` returned
+ False forever on installs without the ``wecom`` extra and the
+ ``platform.wecom_callback`` LAZY_DEPS entry was never exercised.
+ """
+ global ET, DEFUSEDXML_AVAILABLE
+ if check_wecom_callback_requirements():
+ return True
+
+ def _import() -> dict:
+ import defusedxml.ElementTree as _ET
+
+ return {"ET": _ET, "DEFUSEDXML_AVAILABLE": True}
+
+ try:
+ from tools.lazy_deps import ensure_and_bind
+ except Exception: # pragma: no cover — defensive
+ return False
+ if not ensure_and_bind("platform.wecom_callback", _import, globals(), prompt=False):
+ return False
+ return check_wecom_callback_requirements()
+
+
class WecomCallbackAdapter(BasePlatformAdapter):
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform.WECOM_CALLBACK)
diff --git a/tests/gateway/test_platform_registry.py b/tests/gateway/test_platform_registry.py
index 71ea088238d..1181718d938 100644
--- a/tests/gateway/test_platform_registry.py
+++ b/tests/gateway/test_platform_registry.py
@@ -100,6 +100,97 @@ class TestPlatformRegistry:
assert reg.create_adapter("novalidate", MagicMock()) is mock_adapter
+class TestEnsureDepsFn:
+ """check_fn (PASSIVE probe) vs ensure_deps_fn (ACTIVE installer) split.
+
+ Regression for #79812: Teams registered its passive probe as check_fn,
+ so create_adapter() returned None before connect() could lazy-install —
+ the SDK never installed. The inverse wiring (active installer as
+ check_fn) made status displays pip-install SDKs as a side effect.
+ create_adapter() now runs ensure_deps_fn when check_fn is False.
+ """
+
+ def _entry(self, name, *, check_fn, ensure_deps_fn=None):
+ adapter = MagicMock()
+ entry = PlatformEntry(
+ name=name,
+ label=name.title(),
+ adapter_factory=lambda cfg: adapter,
+ check_fn=check_fn,
+ ensure_deps_fn=ensure_deps_fn,
+ source="plugin",
+ )
+ return entry, adapter
+
+ def test_deps_present_skips_installer(self):
+ """check_fn True → adapter created, ensure_deps_fn never called."""
+ reg = PlatformRegistry()
+ installer = MagicMock(return_value=True)
+ entry, adapter = self._entry(
+ "ready", check_fn=lambda: True, ensure_deps_fn=installer
+ )
+ reg.register(entry)
+ assert reg.create_adapter("ready", MagicMock()) is adapter
+ installer.assert_not_called()
+
+ def test_missing_deps_runs_installer_then_creates(self):
+ """check_fn False + ensure_deps_fn True → install runs, adapter created."""
+ reg = PlatformRegistry()
+ installer = MagicMock(return_value=True)
+ entry, adapter = self._entry(
+ "installable", check_fn=lambda: False, ensure_deps_fn=installer
+ )
+ reg.register(entry)
+ assert reg.create_adapter("installable", MagicMock()) is adapter
+ installer.assert_called_once()
+
+ def test_install_failure_returns_none(self):
+ """check_fn False + ensure_deps_fn False → no adapter."""
+ reg = PlatformRegistry()
+ installer = MagicMock(return_value=False)
+ entry, _ = self._entry(
+ "broken", check_fn=lambda: False, ensure_deps_fn=installer
+ )
+ reg.register(entry)
+ assert reg.create_adapter("broken", MagicMock()) is None
+ installer.assert_called_once()
+
+ def test_no_installer_missing_deps_returns_none(self):
+ """check_fn False + no ensure_deps_fn → hard block (legacy behavior)."""
+ reg = PlatformRegistry()
+ entry, _ = self._entry("blocked", check_fn=lambda: False)
+ reg.register(entry)
+ assert reg.create_adapter("blocked", MagicMock()) is None
+
+ def test_installer_exception_returns_none(self):
+ """ensure_deps_fn raising is caught, adapter not created."""
+ reg = PlatformRegistry()
+
+ def _boom():
+ raise RuntimeError("pip exploded")
+
+ entry, _ = self._entry(
+ "explosive", check_fn=lambda: False, ensure_deps_fn=_boom
+ )
+ reg.register(entry)
+ assert reg.create_adapter("explosive", MagicMock()) is None
+
+ def test_check_fn_exception_falls_through_to_installer(self):
+ """A raising check_fn is treated as deps-missing, installer still runs."""
+ reg = PlatformRegistry()
+
+ def _bad_probe():
+ raise RuntimeError("probe error")
+
+ installer = MagicMock(return_value=True)
+ entry, adapter = self._entry(
+ "flaky", check_fn=_bad_probe, ensure_deps_fn=installer
+ )
+ reg.register(entry)
+ assert reg.create_adapter("flaky", MagicMock()) is adapter
+ installer.assert_called_once()
+
+
# ── GatewayConfig integration ────────────────────────────────────────────
@@ -494,3 +585,74 @@ class TestPluginEnablementGate:
)
finally:
_reg.unregister("myrejectedplat")
+
+ def test_missing_deps_with_installer_still_enables(
+ self, tmp_path, monkeypatch
+ ):
+ """is_connected=True + check_fn=False + ensure_deps_fn set → ENABLED.
+
+ The install is deferred to ``create_adapter()`` at gateway start
+ (#79812). Skipping enablement here would mean a configured platform
+ whose SDK isn't installed yet never gets the chance to install it.
+ """
+ from gateway.platform_registry import platform_registry as _reg
+
+ installer = MagicMock(return_value=True)
+ _reg.register(PlatformEntry(
+ name="myinstallableplat",
+ label="MyInstallable",
+ adapter_factory=lambda cfg: None,
+ check_fn=lambda: False, # SDK not installed yet
+ ensure_deps_fn=installer, # ...but installable on demand
+ is_connected=lambda cfg: True, # user configured credentials
+ source="plugin",
+ ))
+ try:
+ home = self._write_config(tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ from gateway.config import load_gateway_config, Platform
+ cfg = load_gateway_config()
+
+ plat = Platform("myinstallableplat")
+ assert plat in cfg.platforms and cfg.platforms[plat].enabled, (
+ "Configured platform with a registered installer must be "
+ "enabled; the install runs at create_adapter() time"
+ )
+ # Config loading must NOT have run the installer (that's the
+ # desktop boot-loop bug — see module docstring of
+ # test_startup_no_eager_platform_install.py).
+ installer.assert_not_called()
+ finally:
+ _reg.unregister("myinstallableplat")
+
+ def test_missing_deps_without_installer_not_enabled(
+ self, tmp_path, monkeypatch
+ ):
+ """is_connected=True + check_fn=False + NO ensure_deps_fn → skipped.
+
+ Without an installer, missing deps are a hard block — enabling the
+ platform would just queue guaranteed connect failures.
+ """
+ from gateway.platform_registry import platform_registry as _reg
+
+ _reg.register(PlatformEntry(
+ name="myhardblockplat",
+ label="MyHardBlock",
+ adapter_factory=lambda cfg: None,
+ check_fn=lambda: False,
+ is_connected=lambda cfg: True,
+ source="plugin",
+ ))
+ try:
+ home = self._write_config(tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ from gateway.config import load_gateway_config, Platform
+ cfg = load_gateway_config()
+
+ plat = Platform("myhardblockplat")
+ if plat in cfg.platforms:
+ assert cfg.platforms[plat].enabled is False
+ finally:
+ _reg.unregister("myhardblockplat")
diff --git a/tests/gateway/test_startup_no_eager_platform_install.py b/tests/gateway/test_startup_no_eager_platform_install.py
index 8a93a7b4faf..1848cb5d658 100644
--- a/tests/gateway/test_startup_no_eager_platform_install.py
+++ b/tests/gateway/test_startup_no_eager_platform_install.py
@@ -1,20 +1,22 @@
"""Regression tests: ``_apply_env_overrides`` must not lazy-install platform
SDKs for platforms the user has not configured.
-For adapter plugins, ``PlatformEntry.check_fn`` doubles as the lazy-installer
-(it pip-installs the platform SDK as a side effect — see e.g.
-``plugins/platforms/discord/adapter.py::check_discord_requirements``). The
-enablement sweep in ``_apply_env_overrides`` used to call ``check_fn`` for
-*every* registered plugin platform unconditionally, so a single
-``load_gateway_config()`` — which the desktop/dashboard readiness probe
-(``GET /api/status``) awaits synchronously — pip-installed Discord, Telegram,
-Slack, Feishu and Dingtalk even with ``platforms: none``. That blocked
-startup until every install finished and made the desktop app time out and
-boot-loop (stuck at 94%).
+Historically ``PlatformEntry.check_fn`` doubled as the lazy-installer
+(it pip-installed the platform SDK as a side effect). The enablement sweep
+in ``_apply_env_overrides`` used to call ``check_fn`` for *every* registered
+plugin platform unconditionally, so a single ``load_gateway_config()`` —
+which the desktop/dashboard readiness probe (``GET /api/status``) awaits
+synchronously — pip-installed Discord, Telegram, Slack, Feishu and Dingtalk
+even with ``platforms: none``. That blocked startup until every install
+finished and made the desktop app time out and boot-loop (stuck at 94%).
-The fix consults the cheap ``is_connected`` credential check FIRST and only
-runs the install-triggering ``check_fn`` for platforms that are already
-enabled or actually configured. These tests pin that contract.
+Two layers of protection now exist:
+1. The sweep consults the cheap ``is_connected`` credential check FIRST and
+ only reaches the dependency check for platforms that are already enabled
+ or actually configured (this file pins that contract).
+2. ``check_fn`` is now defined as a PASSIVE probe; the ACTIVE installer
+ lives on ``ensure_deps_fn`` and only runs from
+ ``platform_registry.create_adapter()`` (#79812).
"""
from unittest.mock import MagicMock, patch
diff --git a/tests/gateway/test_teams.py b/tests/gateway/test_teams.py
index 6362d04d75e..55d93145a4a 100644
--- a/tests/gateway/test_teams.py
+++ b/tests/gateway/test_teams.py
@@ -300,13 +300,14 @@ class TestTeamsPluginRegistration:
assert kwargs["name"] == "teams"
def test_register_check_fn_is_active_lazy_installer(self):
- # create_adapter() gates on check_fn before connect() exists.
- # Passive check_requirements would permanently block lazy install.
+ # check_fn is the PASSIVE probe (status displays call it freely);
+ # the ACTIVE lazy-installer rides on ensure_deps_fn, which
+ # create_adapter() invokes when the passive probe fails (#79812).
ctx = MagicMock()
register(ctx)
kwargs = ctx.register_platform.call_args[1]
- assert kwargs["check_fn"] is check_teams_requirements
- assert kwargs["check_fn"] is not check_requirements
+ assert kwargs["check_fn"] is check_requirements
+ assert kwargs["ensure_deps_fn"] is check_teams_requirements
def test_register_auth_env_vars(self):
ctx = MagicMock()
diff --git a/website/docs/developer-guide/adding-platform-adapters.md b/website/docs/developer-guide/adding-platform-adapters.md
index db2b9e988b5..d2209c638fc 100644
--- a/website/docs/developer-guide/adding-platform-adapters.md
+++ b/website/docs/developer-guide/adding-platform-adapters.md
@@ -120,7 +120,15 @@ def register(ctx):
name="my_platform",
label="My Platform",
adapter_factory=lambda cfg: MyPlatformAdapter(cfg),
+ # PASSIVE probe — "are deps/config present right now?". Called from
+ # status displays and config loading, so it must NEVER pip-install.
check_fn=check_requirements,
+ # ACTIVE installer (optional) — only for platforms with a
+ # lazy-installable SDK. create_adapter() calls it when check_fn
+ # returns False, right before the gateway connects the platform.
+ # Typically wraps tools.lazy_deps.ensure_and_bind(...). Omit it
+ # and a False check_fn is a hard block.
+ # ensure_deps_fn=ensure_requirements,
validate_config=validate_config,
required_env=["MY_PLATFORM_TOKEN"],
install_hint="pip install my-platform-sdk",