Skip to content

The agent that grows with you

fix(gateway): busy-text debounce/hard-cap come from per-profile config, not process env

teknium15a074a02cb47
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 49f4ddcfcf5..af0fdeed9d1 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -107,9 +107,8 @@ def _or_default(thunk, default, exc=(TypeError, ValueError)):
return default
-def _float_env(name: str, default: float) -> float:
- raw = os.environ.get(name, "").strip()
- return _or_default(lambda: float(raw) if raw else default, default)
+DEFAULT_BUSY_TEXT_DEBOUNCE_SECONDS = 0.35
+DEFAULT_BUSY_TEXT_HARD_CAP_SECONDS = 1.0
def _thread_metadata_for_source(source, reply_to_message_id: str | None = None) -> dict | None:
@@ -1896,12 +1895,13 @@ class BasePlatformAdapter(ABC):
self._pending_text_batches: Dict[str, MessageEvent] = {}
self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}
self._session_tasks: Dict[str, asyncio.Task] = {}
- # Legacy env knob; the runner syncs the busy_input_mode value after construction.
- # Default "interrupt" so a pre-sync read never silently queues.
- self._busy_text_mode: str = (
- os.environ.get("HERMES_GATEWAY_BUSY_TEXT_MODE", "interrupt").strip().lower() or "interrupt")
- self._busy_text_debounce_seconds: float = _float_env("HERMES_GATEWAY_BUSY_TEXT_DEBOUNCE_SECONDS", 0.35)
- self._busy_text_hard_cap_seconds: float = _float_env("HERMES_GATEWAY_BUSY_TEXT_HARD_CAP_SECONDS", 1.0)
+ # Busy-text policy is a per-profile config decision the runner installs after construction
+ # (``_wire_adapter_handlers``); a constructor-time process-env read would freeze the launch
+ # profile's values into every profile's adapter under multiplexing (#116893). Defaults here
+ # only cover a pre-sync read so it never silently queues.
+ self._busy_text_mode: str = "interrupt"
+ self._busy_text_debounce_seconds: float = DEFAULT_BUSY_TEXT_DEBOUNCE_SECONDS
+ self._busy_text_hard_cap_seconds: float = DEFAULT_BUSY_TEXT_HARD_CAP_SECONDS
self._text_debounce: dict[str, TextDebounceState] = {}
# handle_message() tasks; shutdown cancels them so a replaced gateway stops working.
self._background_tasks: set[asyncio.Task] = set()
diff --git a/gateway/run.py b/gateway/run.py
index 8d8de6b8a64..11e03fafddf 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3486,6 +3486,8 @@ class GatewayRunner(
# Secondary-profile busy modes snapshotted at multiplex startup; handlers never reread config.
self._busy_input_modes_by_profile: Dict[str, str] = {}
self._busy_text_modes_by_profile: Dict[str, str] = {}
+ self._busy_text_timing = self._busy_text_timing_from_config(_load_gateway_config())
+ self._busy_text_timing_by_profile: Dict[str, tuple[float, float]] = {}
self._restart_drain_timeout = self._load_restart_drain_timeout()
# Live launchd ``ExitTimeOut`` for this job (None when not launchd-owned). Read once at
# boot — launchd fixes it at load — and applied only to signal-driven stops, which are the
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 5d204023d87..b72ae600dd0 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -1105,7 +1105,7 @@ class GatewayAdapterLifecycleMixin:
def _wire_adapter_handlers(
self, adapter: BasePlatformAdapter, *, message_handler=None, fatal_error_handler=None,
busy_session_handler=None, authorization_check=None, platform_event_handler=None,
- busy_text_mode: Optional[str] = None,
+ busy_text_mode: Optional[str] = None, busy_text_timing: Optional[tuple[float, float]] = None,
) -> None:
"""Install the runner callbacks every adapter needs (defaults = primary handlers;
secondary wiring passes profile-scoped variants). ``set_reaction_handler`` is optional."""
@@ -1122,6 +1122,9 @@ class GatewayAdapterLifecycleMixin:
)
adapter.set_platform_event_handler(platform_event_handler or self._primary_platform_event_handler())
adapter._busy_text_mode = (self._busy_text_mode if busy_text_mode is None else busy_text_mode)
+ timing = busy_text_timing or getattr(self, "_busy_text_timing", None)
+ if timing:
+ adapter._busy_text_debounce_seconds, adapter._busy_text_hard_cap_seconds = timing
def _configure_profile_adapter(
self, adapter: BasePlatformAdapter, profile_name: str, platform: Platform
@@ -1137,6 +1140,7 @@ class GatewayAdapterLifecycleMixin:
# Voice transcripts from this bot's channels dispatch through THIS adapter (primary wiring lives at
# connect time; see #75198).
text_modes = getattr(self, "_busy_text_modes_by_profile", None)
+ timings = getattr(self, "_busy_text_timing_by_profile", None)
self._wire_adapter_handlers(
adapter,
message_handler=self._make_profile_message_handler(profile_name),
@@ -1149,6 +1153,7 @@ class GatewayAdapterLifecycleMixin:
if isinstance(text_modes, dict)
else self._busy_text_mode
),
+ busy_text_timing=(timings.get(profile_name) if isinstance(timings, dict) else None),
)
# Voice transcripts from this bot's channels dispatch through THIS adapter.
self._bind_voice_input_callback(adapter)
diff --git a/gateway/run_config_loaders.py b/gateway/run_config_loaders.py
index 9cf2d9b8f1f..2bc225783b1 100644
--- a/gateway/run_config_loaders.py
+++ b/gateway/run_config_loaders.py
@@ -271,6 +271,29 @@ class GatewayConfigLoadersMixin:
text_mode = fallback_text
return input_mode, text_mode
+ @staticmethod
+ def _busy_text_timing_from_config(config: dict) -> tuple[float, float]:
+ """``display.busy_text_debounce_seconds`` / ``display.busy_text_hard_cap_seconds`` for one
+ profile, without consulting process env (#116893). A non-numeric or negative value is
+ rejected with a warning naming the key, never silently coerced."""
+ from gateway.platforms.base import DEFAULT_BUSY_TEXT_DEBOUNCE_SECONDS, DEFAULT_BUSY_TEXT_HARD_CAP_SECONDS
+ out = []
+ for key, default in (("busy_text_debounce_seconds", DEFAULT_BUSY_TEXT_DEBOUNCE_SECONDS),
+ ("busy_text_hard_cap_seconds", DEFAULT_BUSY_TEXT_HARD_CAP_SECONDS)):
+ raw = cfg_get(config, "display", key, default=None)
+ if raw is None or raw == "":
+ out.append(default)
+ continue
+ try:
+ value = float(raw)
+ if value < 0 or value != value:
+ raise ValueError(raw)
+ except (TypeError, ValueError):
+ logger.warning("display.%s=%r is not a non-negative number; using %s", key, raw, default)
+ value = default
+ out.append(value)
+ return out[0], out[1]
+
def _snapshot_profile_busy_modes(self, profile_name: str, config: dict) -> None:
"""Cache a routed profile's busy policy for this gateway lifetime."""
input_mode, text_mode = self._busy_modes_from_config(
@@ -279,6 +302,8 @@ class GatewayConfigLoadersMixin:
)
self.__dict__.setdefault("_busy_input_modes_by_profile", {})[profile_name] = input_mode
self.__dict__.setdefault("_busy_text_modes_by_profile", {})[profile_name] = text_mode
+ self.__dict__.setdefault("_busy_text_timing_by_profile", {})[profile_name] = (
+ self._busy_text_timing_from_config(config))
def _busy_profile_name_for_source(self, source: SessionSource) -> Optional[str]:
"""Return the routed profile whose busy policy applies, if any."""
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index 8d0b17a597c..bd8022a2291 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -205,7 +205,8 @@ class GatewayProfileReconcileMixin:
await self._bounded_adapter_teardown(adapter, platform, profile=name)
# Its ``<name>:<platform>`` runtime entries describe a profile that no longer exists.
_write_runtime_status_quiet(drop_profile_platforms=name)
- for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile"):
+ for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile",
+ "_busy_text_timing_by_profile"):
store = getattr(self, attr, None)
if isinstance(store, dict):
store.pop(name, None)
diff --git a/tests/gateway/test_multiplex_busy_input_mode.py b/tests/gateway/test_multiplex_busy_input_mode.py
index e5ca3cbb17c..0005b991892 100644
--- a/tests/gateway/test_multiplex_busy_input_mode.py
+++ b/tests/gateway/test_multiplex_busy_input_mode.py
@@ -508,3 +508,43 @@ async def test_primary_adapter_busy_origin_uses_routed_privacy(
assert asdict(event.source) == original
assert get_hermes_home_override() == ambient
assert key not in adapter._pending_messages
+
+
+async def test_secondary_busy_text_timing_follows_profile_config_not_process_env(tmp_path, monkeypatch):
+ """Debounce / hard-cap are per-profile config (#116893): a launch-process env value must not
+ reach a secondary profile's adapter, and each profile keeps its own numbers across A->B->A."""
+ monkeypatch.setenv("HERMES_GATEWAY_BUSY_TEXT_DEBOUNCE_SECONDS", "9.0")
+ monkeypatch.setenv("HERMES_GATEWAY_BUSY_TEXT_HARD_CAP_SECONDS", "9.0")
+ runner = _runner()
+ runner._busy_text_timing = (0.35, 1.0)
+ homes = {"alpha": tmp_path / "alpha", "beta": tmp_path / "beta"}
+ for name, (debounce, cap) in {"alpha": (0.1, 0.5), "beta": (2.0, 4.0)}.items():
+ homes[name].mkdir()
+ (homes[name] / "config.yaml").write_text(
+ f"display:\n busy_text_debounce_seconds: {debounce}\n busy_text_hard_cap_seconds: {cap}\n",
+ encoding="utf-8")
+
+ seen = {}
+ for name in ("alpha", "beta", "alpha"):
+ assert await runner._start_one_profile_adapters(name, homes[name], {}) == 0
+ adapter = _adapter()
+ runner._profile_adapters[name][Platform.TELEGRAM] = adapter
+ runner._configure_profile_adapter(adapter, name, Platform.TELEGRAM)
+ seen.setdefault(name, []).append((adapter._busy_text_debounce_seconds, adapter._busy_text_hard_cap_seconds))
+
+ assert seen["alpha"] == [(0.1, 0.5), (0.1, 0.5)]
+ assert seen["beta"] == [(2.0, 4.0)]
+ # A fresh adapter never carries the process-env value either.
+ fresh = _adapter()
+ assert (fresh._busy_text_debounce_seconds, fresh._busy_text_hard_cap_seconds) == (0.35, 1.0)
+
+
+def test_busy_text_timing_rejects_non_numeric_config(caplog):
+ """A typo in the timing keys warns and falls back instead of crashing or silently coercing."""
+ import logging
+ with caplog.at_level(logging.WARNING, logger="gateway.run_config_loaders"):
+ timing = GatewayRunner._busy_text_timing_from_config(
+ {"display": {"busy_text_debounce_seconds": "fast", "busy_text_hard_cap_seconds": -3}})
+ assert timing == (0.35, 1.0)
+ assert "busy_text_debounce_seconds" in caplog.text and "busy_text_hard_cap_seconds" in caplog.text
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index eda38a873cb..c374b30a45d 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -440,8 +440,12 @@ Gateway steers (including explicit `/steer`) and active-turn redirects carry the
display:
busy_input_mode: steer # or queue, or interrupt (default)
busy_ack_enabled: true # set to false to suppress the ⚡/⏳/⏩ chat reply entirely
+ busy_text_debounce_seconds: 0.35 # quiet window before merged busy text is delivered
+ busy_text_hard_cap_seconds: 1.0 # never hold merged busy text longer than this
```
+All four keys are read from each profile's own `config.yaml`, so multiplexed profiles keep independent busy policies; there is no process-environment override.
+
The first time you message a busy agent on any platform, Hermes appends a one-line reminder to the busy-ack explaining the knob (`"💡 First-time tip — …"`). The reminder fires once per install — a flag under `onboarding.seen.busy_input_prompt` latches it. Delete that key to see the tip again.
If you find the busy acknowledgment noisy, set `display.busy_ack_enabled: false`. Input handling is unchanged; only the confirmation message is hidden.