diff --git a/cron/scheduler.py b/cron/scheduler.py index b4e6001d19a9f..636bc12072763 100644 --- a/cron/scheduler.py +++ b/cron/scheduler.py @@ -1127,6 +1127,39 @@ def _expand_routing_tokens(part: str) -> List[str]: return expanded +def _filter_proactive_push_optout(targets: List[dict], job: dict) -> List[dict]: + """Drop delivery targets whose platform opted out of proactive push. + + A cron response is an unsolicited/background push, so a platform with + ``display.platforms.

.proactive_push=false`` (or global + ``display.proactive_push=false``) is skipped — even for ``deliver=all`` or an + explicit ``platform:chat`` target (a platform-level "do not disturb" wins + over a job's routing intent). Each skip is logged. Fail-open: if config can't + be read, deliver as before rather than silently dropping. + """ + if not targets: + return targets + try: + from hermes_cli.config import load_config + from gateway.display_config import platform_accepts_proactive_push + + user_config = load_config() + except Exception: + return targets + kept = [] + for t in targets: + pkey = str(t.get("platform", "")).lower() + if pkey and not platform_accepts_proactive_push(user_config, pkey): + logger.info( + "Job '%s': skipping proactive delivery to %s:%s — platform opted " + "out of proactive push (display.platforms.%s.proactive_push=false)", + job.get("id", "?"), t.get("platform"), t.get("chat_id"), pkey, + ) + continue + kept.append(t) + return kept + + def _resolve_delivery_targets(job: dict) -> List[dict]: """Resolve all concrete auto-delivery targets for a cron job. @@ -1157,7 +1190,8 @@ def _resolve_delivery_targets(job: dict) -> List[dict]: if key not in seen: seen.add(key) targets.append(target) - return targets + # Per-platform proactive-push gate: drop opted-out platforms (logs each). + return _filter_proactive_push_optout(targets, job) def _resolve_delivery_target(job: dict) -> Optional[dict]: diff --git a/gateway/display_config.py b/gateway/display_config.py index e352ea0e9d629..434d92a55d58d 100644 --- a/gateway/display_config.py +++ b/gateway/display_config.py @@ -58,6 +58,18 @@ # live, just cleaned up after success so the chat doesn't fill up with # stale breadcrumbs. Failed runs leave bubbles in place as breadcrumbs. "cleanup_progress": False, + # Per-platform master switch for UNSOLICITED / background pushes (cron job + # responses, background-review memory notifications, kanban notifiers, + # background-task results, restart notices). Default on for back-compat. + # A platform set to false receives NO proactive push — but normal + # request→response replies are unaffected (the gate only guards background + # delivery paths, never interactive replies). + "proactive_push": True, + # Memory-update review notifications in chat: "off" | "on" | "verbose". + # Registered here (③) so it resolves per-platform via resolve_display_setting + # and coexists, layered, with proactive_push: a memory-review push is + # delivered only when proactive_push != false AND memory_notifications != off. + "memory_notifications": "on", } # --------------------------------------------------------------------------- @@ -252,6 +264,7 @@ def _normalise(setting: str, value: Any) -> Any: "busy_ack_detail", "busy_steer_ack_enabled", "thinking_progress", + "proactive_push", }: if isinstance(value, str): val = value.strip().lower() @@ -259,6 +272,14 @@ def _normalise(setting: str, value: Any) -> Any: return "generic" return val in {"true", "1", "yes", "on", "raw", "verbose"} return bool(value) + if setting == "memory_notifications": + # Three modes; normalise bool/str to off|on|verbose (default on). + if value is False: + return "off" + if value is True: + return "on" + val = str(value).lower() + return val if val in ("off", "on", "verbose") else "on" if setting == "cleanup_progress": if isinstance(value, str): return value.lower() in {"true", "1", "yes", "on"} @@ -275,3 +296,33 @@ def _normalise(setting: str, value: Any) -> Any: except (TypeError, ValueError): return 0 return value + + +def platform_accepts_proactive_push(user_config: dict, platform_key: str) -> bool: + """Whether a platform accepts unsolicited / background pushes. + + Single source of truth for the per-platform proactive-push gate. Every + background delivery path (cron ``_deliver_result``, background-review + memory notifications, kanban notifiers, background-task results, restart + notices) consults this before delivering, so a platform opted out via + ``display.platforms..proactive_push: false`` (or globally via + ``display.proactive_push: false``) is skipped everywhere. + + Interactive replies (a user's message → the agent's response) must NOT go + through this gate — it guards only background/proactive delivery. + """ + return bool(resolve_display_setting(user_config, platform_key, "proactive_push", True)) + + +def effective_memory_notifications(user_config: dict, platform_key: str) -> str: + """Per-platform memory-review notification mode, layered under proactive_push. + + Returns ``"off"`` | ``"on"`` | ``"verbose"``. A memory-review notification is + delivered only when ``proactive_push != false`` AND + ``memory_notifications != off`` — so a platform opted out of proactive push + gets no memory notifications at all, regardless of its memory_notifications + setting (③ layered coexistence). + """ + if not platform_accepts_proactive_push(user_config, platform_key): + return "off" + return str(resolve_display_setting(user_config, platform_key, "memory_notifications", "on")) diff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.py index eb1c68ffd66b9..d60efa7fb142e 100644 --- a/gateway/kanban_watchers.py +++ b/gateway/kanban_watchers.py @@ -296,11 +296,32 @@ def _collect(): return deliveries deliveries = await asyncio.to_thread(_collect) + # Per-platform proactive-push gate: kanban terminal-event + # notifications are unsolicited pushes, so honour a platform's + # proactive_push opt-out. Loaded once per tick; fail-open. + try: + from hermes_cli.config import load_config as _load_push_cfg + from gateway.display_config import platform_accepts_proactive_push + _push_cfg = _load_push_cfg() + except Exception: + _push_cfg = None for d in deliveries: sub = d["sub"] task = d["task"] board_slug = d.get("board") platform_str = (sub["platform"] or "").lower() + if (_push_cfg is not None and platform_str + and not platform_accepts_proactive_push(_push_cfg, platform_str)): + logger.info( + "kanban notifier: skipping proactive delivery to %s/%s for %s — " + "platform opted out of proactive push", platform_str, + sub.get("chat_id"), sub["task_id"], + ) + # Advance the cursor so the opted-out event isn't replayed forever. + await asyncio.to_thread( + self._kanban_advance, sub, d["cursor"], board_slug, + ) + continue try: plat = _Platform(platform_str) except ValueError: diff --git a/gateway/run.py b/gateway/run.py index b81e87dba641f..c9fbb5522f915 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -14344,6 +14344,21 @@ async def _send_restart_notification(self) -> Optional[tuple[str, str, Optional[ ) return None + # Per-platform proactive-push gate: a restart notice is an + # unsolicited push, so honour display.platforms.

.proactive_push + # (unifies with the existing gateway_restart_notification flag). + try: + from hermes_cli.config import load_config as _load_push_cfg + from gateway.display_config import platform_accepts_proactive_push + if not platform_accepts_proactive_push(_load_push_cfg(), _platform_config_key(platform)): + logger.info( + "Restart notification suppressed: %s opted out of proactive push", + platform_str, + ) + return None + except Exception: + pass # fail-open + platform_cfg = self.config.platforms.get(platform) if platform_cfg is not None and not platform_cfg.gateway_restart_notification: logger.info( @@ -14410,6 +14425,20 @@ async def _send_home_channel_startup_notifications( if not home or not home.chat_id: continue + # Per-platform proactive-push gate (startup broadcast is a proactive + # push). Unifies with the existing gateway_restart_notification flag. + try: + from hermes_cli.config import load_config as _load_push_cfg + from gateway.display_config import platform_accepts_proactive_push + if not platform_accepts_proactive_push(_load_push_cfg(), _platform_config_key(platform)): + logger.info( + "Home-channel startup notification suppressed: %s opted out of proactive push", + platform.value, + ) + continue + except Exception: + pass # fail-open + platform_cfg = self.config.platforms.get(platform) if platform_cfg is not None and not platform_cfg.gateway_restart_notification: logger.info( @@ -17899,14 +17928,18 @@ def _bg_review_send(message: str) -> None: _pdc = getattr(_status_adapter, "_post_delivery_callbacks", None) if _pdc is not None: _pdc[session_key] = _release_bg_review_messages - # Memory update notifications in chat. Config: display.memory_notifications + # Memory update notifications in chat. # off — no chat notification (still logged to stdout) # on — generic "💾 Memory updated" (default) # verbose — content preview: "💾 Memory ➕ Hermes Repo..." - _mem_notif = user_config.get("display", {}).get("memory_notifications") - if isinstance(_mem_notif, bool): - _mem_notif = "on" if _mem_notif else "off" - agent.memory_notifications = str(_mem_notif).lower() if _mem_notif else "on" + # Resolved PER-PLATFORM (display.platforms.

.memory_notifications) + # and layered under the proactive-push gate: a platform opted out of + # proactive push gets no memory notifications at all. This is a + # background/proactive push — interactive replies are never gated. + from gateway.display_config import effective_memory_notifications + agent.memory_notifications = effective_memory_notifications( + user_config, platform_key + ) # ------------------------------------------------------------------ # Clarify callback: present a clarify prompt and block on a response. diff --git a/tests/cron/test_proactive_push_gate.py b/tests/cron/test_proactive_push_gate.py new file mode 100644 index 0000000000000..531dc0f4b1ad9 --- /dev/null +++ b/tests/cron/test_proactive_push_gate.py @@ -0,0 +1,85 @@ +"""Cron delivery honours the per-platform proactive-push opt-out gate.""" + +import pytest + +from cron.scheduler import _filter_proactive_push_optout, _resolve_delivery_targets + + +def _cfg(mp, config): + mp.setattr("hermes_cli.config.load_config", lambda: config) + + +# -- filter helper (unit) ---------------------------------------------------- + +def test_optout_platform_dropped_others_kept(monkeypatch): + _cfg(monkeypatch, {"display": {"platforms": {"line": {"proactive_push": False}}}}) + targets = [ + {"platform": "line", "chat_id": "U1", "thread_id": None}, + {"platform": "telegram", "chat_id": "T1", "thread_id": None}, + ] + kept = _filter_proactive_push_optout(targets, {"id": "j1"}) + assert [t["platform"] for t in kept] == ["telegram"] # line dropped, telegram kept + + +def test_deliver_all_still_respects_optout(monkeypatch): + # An explicit multi-target (deliver=all expands to many) still skips opt-out. + _cfg(monkeypatch, {"display": {"platforms": {"line": {"proactive_push": False}}}}) + targets = [ + {"platform": "line", "chat_id": "U1"}, + {"platform": "discord", "chat_id": "D1"}, + {"platform": "slack", "chat_id": "S1"}, + ] + kept = _filter_proactive_push_optout(targets, {"id": "j2"}) + assert {t["platform"] for t in kept} == {"discord", "slack"} + + +def test_global_optout_drops_all(monkeypatch): + _cfg(monkeypatch, {"display": {"proactive_push": False}}) + targets = [{"platform": "line", "chat_id": "U1"}, {"platform": "telegram", "chat_id": "T1"}] + assert _filter_proactive_push_optout(targets, {"id": "j3"}) == [] + + +def test_no_optout_keeps_everything(monkeypatch): + _cfg(monkeypatch, {"display": {}}) + targets = [{"platform": "line", "chat_id": "U1"}, {"platform": "telegram", "chat_id": "T1"}] + assert len(_filter_proactive_push_optout(targets, {"id": "j4"})) == 2 + + +def test_fail_open_on_config_error(monkeypatch): + def boom(): + raise RuntimeError("config unreadable") + monkeypatch.setattr("hermes_cli.config.load_config", boom) + targets = [{"platform": "line", "chat_id": "U1"}] + # Fail-open: deliver as before rather than silently dropping. + assert _filter_proactive_push_optout(targets, {"id": "j5"}) == targets + + +def test_skip_is_logged(monkeypatch, caplog): + import logging + _cfg(monkeypatch, {"display": {"platforms": {"line": {"proactive_push": False}}}}) + with caplog.at_level(logging.INFO): + _filter_proactive_push_optout([{"platform": "line", "chat_id": "U1"}], {"id": "jlog"}) + assert any("opted out of proactive push" in r.message and "jlog" in r.message + for r in caplog.records) + + +# -- integration through _resolve_delivery_targets --------------------------- + +def test_resolve_targets_filters_optout_origin(monkeypatch): + _cfg(monkeypatch, {"display": {"platforms": {"line": {"proactive_push": False}}}}) + job = { + "id": "sync", "deliver": "origin", + "origin": {"platform": "line", "chat_id": "Uddf", "thread_id": None}, + } + # deliver=origin resolves to line:Uddf, then the gate drops it → no targets. + assert _resolve_delivery_targets(job) == [] + + +def test_resolve_targets_keeps_non_optout_origin(monkeypatch): + _cfg(monkeypatch, {"display": {"platforms": {"line": {"proactive_push": False}}}}) + job = { + "id": "tg", "deliver": "origin", + "origin": {"platform": "telegram", "chat_id": "T1", "thread_id": None}, + } + targets = _resolve_delivery_targets(job) + assert [t["platform"] for t in targets] == ["telegram"] diff --git a/tests/gateway/test_display_config.py b/tests/gateway/test_display_config.py index d05807e41a79c..e38f4362b6a9e 100644 --- a/tests/gateway/test_display_config.py +++ b/tests/gateway/test_display_config.py @@ -607,3 +607,100 @@ def test_case_insensitive(self): config = {"display": {"reasoning_style": "SUBTEXT"}} assert resolve_display_setting(config, "telegram", "reasoning_style") == "subtext" + + +# --------------------------------------------------------------------------- +# proactive_push + memory_notifications (per-platform proactive-push gate) +# --------------------------------------------------------------------------- + +class TestProactivePushSetting: + """proactive_push resolves per-platform and defaults on.""" + + def test_default_is_true(self): + from gateway.display_config import platform_accepts_proactive_push + assert platform_accepts_proactive_push({}, "line") is True + + def test_per_platform_optout_isolated(self): + from gateway.display_config import platform_accepts_proactive_push + config = {"display": {"platforms": {"line": {"proactive_push": False}}}} + assert platform_accepts_proactive_push(config, "line") is False + # Other platforms unaffected. + assert platform_accepts_proactive_push(config, "telegram") is True + + def test_global_optout_all_platforms(self): + from gateway.display_config import platform_accepts_proactive_push + config = {"display": {"proactive_push": False}} + assert platform_accepts_proactive_push(config, "line") is False + assert platform_accepts_proactive_push(config, "telegram") is False + + def test_platform_override_beats_global(self): + from gateway.display_config import platform_accepts_proactive_push + config = {"display": {"proactive_push": False, + "platforms": {"telegram": {"proactive_push": True}}}} + assert platform_accepts_proactive_push(config, "telegram") is True + assert platform_accepts_proactive_push(config, "line") is False + + def test_yaml_off_string_normalises_to_false(self): + from gateway.display_config import platform_accepts_proactive_push + for val in ("off", "false", "no", "0"): + config = {"display": {"platforms": {"line": {"proactive_push": val}}}} + assert platform_accepts_proactive_push(config, "line") is False, val + + +class TestMemoryNotificationsRegistered: + """memory_notifications is now a per-platform overrideable key.""" + + def test_in_overrideable_keys(self): + from gateway.display_config import OVERRIDEABLE_KEYS + assert "memory_notifications" in OVERRIDEABLE_KEYS + assert "proactive_push" in OVERRIDEABLE_KEYS + + def test_default_on(self): + from gateway.display_config import resolve_display_setting + assert resolve_display_setting({}, "line", "memory_notifications", "on") == "on" + + def test_per_platform_modes(self): + from gateway.display_config import resolve_display_setting + config = {"display": {"platforms": { + "line": {"memory_notifications": "off"}, + "discord": {"memory_notifications": "verbose"}, + }}} + assert resolve_display_setting(config, "line", "memory_notifications", "on") == "off" + assert resolve_display_setting(config, "discord", "memory_notifications", "on") == "verbose" + assert resolve_display_setting(config, "telegram", "memory_notifications", "on") == "on" + + def test_bool_false_normalises_to_off(self): + from gateway.display_config import resolve_display_setting + config = {"display": {"platforms": {"line": {"memory_notifications": False}}}} + assert resolve_display_setting(config, "line", "memory_notifications", "on") == "off" + + +class TestEffectiveMemoryNotifications: + """memory_notifications layered under the proactive_push gate.""" + + def test_proactive_off_forces_notifications_off(self): + from gateway.display_config import effective_memory_notifications + cfg = {"display": {"platforms": {"line": { + "proactive_push": False, "memory_notifications": "verbose"}}}} + # proactive off wins → no memory notifications even if mode=verbose. + assert effective_memory_notifications(cfg, "line") == "off" + + def test_proactive_on_respects_mode_off(self): + from gateway.display_config import effective_memory_notifications + cfg = {"display": {"platforms": {"line": {"memory_notifications": "off"}}}} + assert effective_memory_notifications(cfg, "line") == "off" + + def test_proactive_on_respects_mode_verbose(self): + from gateway.display_config import effective_memory_notifications + cfg = {"display": {"platforms": {"discord": {"memory_notifications": "verbose"}}}} + assert effective_memory_notifications(cfg, "discord") == "verbose" + + def test_default_is_on(self): + from gateway.display_config import effective_memory_notifications + assert effective_memory_notifications({}, "telegram") == "on" + + def test_global_proactive_off_forces_off(self): + from gateway.display_config import effective_memory_notifications + cfg = {"display": {"proactive_push": False, + "platforms": {"line": {"memory_notifications": "on"}}}} + assert effective_memory_notifications(cfg, "line") == "off" diff --git a/tests/gateway/test_restart_notification.py b/tests/gateway/test_restart_notification.py index b090503c5b132..5f532e0e56c9c 100644 --- a/tests/gateway/test_restart_notification.py +++ b/tests/gateway/test_restart_notification.py @@ -688,3 +688,24 @@ async def test_restart_shutdown_notification_anchors_telegram_dm_topic(): "direct_messages_topic_id": "20197", "telegram_reply_to_message_id": "462", } + + +@pytest.mark.asyncio +async def test_send_restart_notification_suppressed_by_proactive_optout(tmp_path, monkeypatch): + """A platform opted out of proactive push gets no restart notice.""" + monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path) + monkeypatch.setattr( + "hermes_cli.config.load_config", + lambda: {"display": {"platforms": {"telegram": {"proactive_push": False}}}}, + ) + notify_path = tmp_path / ".restart_notify.json" + notify_path.write_text(json.dumps({"platform": "telegram", "chat_id": "42"})) + + runner, adapter = make_restart_runner() + adapter.send = AsyncMock() + + result = await runner._send_restart_notification() + + assert result is None # suppressed by the proactive-push gate + adapter.send.assert_not_called() # no unsolicited push to the opted-out platform + assert not notify_path.exists() # marker is still consumed (not replayed) diff --git a/tui_gateway/server.py b/tui_gateway/server.py index 7c9287aaab071..64ee989f68585 100644 --- a/tui_gateway/server.py +++ b/tui_gateway/server.py @@ -2367,7 +2367,7 @@ def _load_show_reasoning() -> bool: return bool((_load_cfg().get("display") or {}).get("show_reasoning", False)) -def _load_memory_notifications() -> str: +def _load_memory_notifications(platform_key: str = "cli") -> str: """Self-improvement review notification mode from config.yaml. Parity with the messaging gateway (``gateway/run.py``) and the classic CLI: @@ -2376,8 +2376,15 @@ def _load_memory_notifications() -> str: TUI/desktop backend always behaved as ``"on"`` and silently ignored a user who set ``off``. Accepts ``off`` / ``on`` (default) / ``verbose``; a bool is normalized for back-compat. + + Resolved through ``resolve_display_setting`` so a per-platform override + (``display.platforms..memory_notifications``) wins over the global + ``display.memory_notifications``, matching the messaging gateway. The TUI is + a single ``cli``-tier surface, so ``platform_key`` defaults to ``"cli"``. """ - raw = (_load_cfg().get("display") or {}).get("memory_notifications") + from gateway.display_config import resolve_display_setting + + raw = resolve_display_setting(_load_cfg(), platform_key, "memory_notifications", "on") if isinstance(raw, bool): return "on" if raw else "off" return str(raw).lower() if raw else "on"