Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion cron/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.<p>.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.

Expand Down Expand Up @@ -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]:
Expand Down
51 changes: 51 additions & 0 deletions gateway/display_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -252,13 +264,22 @@ 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()
if val == "generic" and setting == "long_running_notifications":
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"}
Expand All @@ -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.<platform>.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"))
21 changes: 21 additions & 0 deletions gateway/kanban_watchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
43 changes: 38 additions & 5 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.<p>.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)):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This covers only the post-boot _send_restart_notification() path. _notify_active_sessions_of_shutdown() still sends shutdown/restart notices to active sessions and home channels without this gate; apply the same resolver there or proactive_push: false does not suppress all restart-related unsolicited notifications.

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(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.<p>.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.
Expand Down
85 changes: 85 additions & 0 deletions tests/cron/test_proactive_push_gate.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading