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
61 changes: 61 additions & 0 deletions gateway/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,6 +1035,11 @@ class SendResult:
error: Optional[str] = None
raw_response: Any = None
retryable: bool = False # True for transient connection errors — base will retry automatically
# True when the adapter deliberately did not deliver the message because
# an adapter-level policy suppressed it (e.g. kind="status" in a group
# chat on a non-editing platform like iMessage). The send is reported
# successful so callers don't retry, but no platform message was sent.
suppressed: bool = False
# When the adapter had to split an oversized payload across multiple
# platform messages (e.g. Telegram edit_message overflow split-and-deliver),
# ``message_id`` is the LAST visible message id (so subsequent edits target
Expand Down Expand Up @@ -2450,6 +2455,34 @@ def _unwrap_ephemeral(self, response: Any) -> Tuple[Optional[str], int]:
return response.text, int(ttl or 0)
return response, 0

async def _should_suppress_status(
self,
chat_id: str,
*,
kind: str = "status",
metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""Policy hook: should a ``kind="status"`` message be dropped here?

Receives the target ``chat_id``, the declared ``kind`` (always
``"status"`` from the current call site, kept as a kwarg so future
kinds can route through the same hook without breaking overrides),
and any caller-supplied ``metadata`` (thread/topic info, chat_type
hint, etc.). Default returns ``False`` — every adapter delivers
status messages like a normal reply. Adapters that target chat
surfaces where status bubbles are intrusive (e.g. iMessage groups,
where every message is a permanent, un-editable bubble visible to
everyone) override this to return ``True`` for the affected chats.

Called from :meth:`_send_with_retry` *before* the actual provider
send when ``kind="status"``. Returning ``True`` causes the call to
return ``SendResult(success=True, suppressed=True)`` with no
platform delivery and a local audit log line. DMs and
editing-capable platforms should keep status messages visible —
they are useful progress signal there.
"""
return False

async def _send_with_retry(
self,
chat_id: str,
Expand All @@ -2458,6 +2491,8 @@ async def _send_with_retry(
metadata: Any = None,
max_retries: int = 2,
base_delay: float = 2.0,
*,
kind: str = "reply",
) -> "SendResult":
"""
Send a message with automatic retry for transient network errors.
Expand All @@ -2466,8 +2501,34 @@ async def _send_with_retry(
to a plain-text version before giving up. If all attempts fail due to
network errors, sends the user a brief delivery-failure notice so they
know to retry rather than waiting indefinitely.

``kind`` declares the message category so the adapter can apply a
per-platform policy. Default ``"reply"`` is the normal user-facing
agent response. ``"status"`` marks lifecycle / interrupt-ack /
queue-ack / steer-ack / provider-stall / warn messages that may be
suppressed on platforms where they would otherwise pollute a shared
chat (e.g. iMessage groups). Other values are passed through
unchanged so future kinds can be added without breaking adapters.
"""

# Adapter-level policy hook: a status message may be deliberately
# dropped (e.g. iMessage group chat) so callers don't have to know
# the per-platform rules. Suppression is reported as success with
# ``suppressed=True`` so retry/fallback logic doesn't trigger.
if kind == "status":
try:
if await self._should_suppress_status(chat_id, kind=kind, metadata=metadata):
logger.info(
"[%s] kind=status suppressed for chat_id=%s (adapter policy)",
self.name, chat_id,
)
return SendResult(success=True, suppressed=True)
except Exception as _policy_err:
logger.debug(
"[%s] _should_suppress_status raised, falling through to send: %s",
self.name, _policy_err,
)

result = await self.send(
chat_id=chat_id,
content=content,
Expand Down
36 changes: 36 additions & 0 deletions gateway/platforms/bluebubbles.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ def _normalize_server_url(raw: str) -> str:
return value.rstrip("/")


def _truthy(value: Any, default: bool = False) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}



Expand Down Expand Up @@ -124,6 +130,13 @@ def __init__(self, config: PlatformConfig):
if not str(self.webhook_path).startswith("/"):
self.webhook_path = f"/{self.webhook_path}"
self.send_read_receipts = bool(extra.get("send_read_receipts", True))
# Whether kind="status" messages are delivered into BlueBubbles / iMessage
# group chats. Default False because every iMessage send is a permanent,
# un-editable bubble visible to every member. DMs still receive status.
self.show_status_in_groups = _truthy(
os.getenv("BLUEBUBBLES_SHOW_STATUS_IN_GROUPS"),

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.

Please keep this behavior setting in the configured PlatformConfig.extra path only rather than adding a new environment-variable override; AGENTS.md:102-107 reserves behavioral settings for config.yaml.

bool(extra.get("show_status_in_groups", False)),
)
self.client: Optional[httpx.AsyncClient] = None
self._runner = None
self._private_api_enabled: Optional[bool] = None
Expand Down Expand Up @@ -669,10 +682,33 @@ async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
info["name"] = display_name
if participants:
info["participants"] = participants
if len(participants) > 1:
info["type"] = "group"
except Exception:
pass
return info

async def _should_suppress_status(
self,
chat_id: str,
*,
kind: str = "status",
metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""Drop kind="status" messages in BlueBubbles/iMessage groups by default."""
del kind, metadata
if self.show_status_in_groups:
return False
try:
info = await self.get_chat_info(str(chat_id or ""))
except Exception as exc:
logger.warning(
"[bluebubbles] get_chat_info failed during status policy check; dropping kind=status: %s",
exc,
)
return True

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 converts a chat-info failure into suppression, contrary to the base policy's stated fail-open contract. Return False here so an unavailable lookup still delivers the user-facing status message.

return (info or {}).get("type") == "group"

def format_message(self, content: str) -> str:
return strip_markdown(content)

Expand Down
29 changes: 23 additions & 6 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2537,6 +2537,7 @@ async def _handle_active_session_busy_message(self, event: MessageEvent, session
else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id)
),
metadata=thread_meta,
kind="status",
)
return True

Expand Down Expand Up @@ -2686,6 +2687,7 @@ async def _handle_active_session_busy_message(self, event: MessageEvent, session
else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id)
),
metadata=thread_meta,
kind="status",
)
except Exception as e:
logger.debug("Failed to send busy-ack: %s", e)
Expand Down Expand Up @@ -2807,7 +2809,12 @@ async def _notify_active_sessions_of_shutdown(self) -> None:
# correct forum topic / thread.
metadata = {"thread_id": thread_id} if thread_id else None

result = await adapter.send(chat_id, msg, metadata=metadata)
result = await adapter._send_with_retry(
chat_id=chat_id,
content=msg,
metadata=metadata,
kind="status",
)
if result is not None and getattr(result, "success", True) is False:
logger.debug(
"Failed to send shutdown notification to %s:%s: %s",
Expand Down Expand Up @@ -2853,9 +2860,18 @@ async def _notify_active_sessions_of_shutdown(self) -> None:
try:
metadata = {"thread_id": home.thread_id} if home.thread_id else None
if metadata:
result = await adapter.send(str(home.chat_id), msg, metadata=metadata)
result = await adapter._send_with_retry(
chat_id=str(home.chat_id),
content=msg,
metadata=metadata,
kind="status",
)
else:
result = await adapter.send(str(home.chat_id), msg)
result = await adapter._send_with_retry(
chat_id=str(home.chat_id),
content=msg,
kind="status",
)
if result is not None and getattr(result, "success", True) is False:
logger.debug(
"Failed to send shutdown notification to home channel %s:%s: %s",
Expand Down Expand Up @@ -14818,10 +14834,11 @@ def _status_callback_sync(event_type: str, message: str) -> None:
return
try:
_fut = asyncio.run_coroutine_threadsafe(
_status_adapter.send(
_status_chat_id,
message,
_status_adapter._send_with_retry(

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.

Current main's status callback first calls _prepare_gateway_status_message and then _send_or_update_status_coro (gateway/run.py:17812-17833). Preserve that shared filter/update route when porting this policy; replacing it with this direct send would bypass the current all-chat lifecycle-noise protection.

chat_id=_status_chat_id,
content=message,
metadata=_status_thread_metadata,
kind="status",
),
_loop_for_step,
)
Expand Down
104 changes: 104 additions & 0 deletions tests/gateway/test_bluebubbles_status_suppression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
from __future__ import annotations

from typing import Any, Dict, Optional

import pytest

from gateway.config import PlatformConfig
from gateway.platforms.bluebubbles import BlueBubblesAdapter
from gateway.platforms.base import SendResult


class _RecordingBlueBubblesAdapter(BlueBubblesAdapter):
def __init__(self, *, chat_type: str = "dm", show_status_in_groups: bool = False):
super().__init__(
PlatformConfig(
enabled=True,
extra={"show_status_in_groups": show_status_in_groups},
)
)
self._chat_type = chat_type
self.sent: list[dict[str, Any]] = []

async def send(
self,
chat_id: str,
content: str,
reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
self.sent.append(
{
"chat_id": chat_id,
"content": content,
"reply_to": reply_to,
"metadata": metadata,
}
)
return SendResult(success=True, message_id="bb-1")

async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
return {"name": chat_id, "type": self._chat_type, "chat_id": chat_id}


@pytest.mark.asyncio
async def test_bluebubbles_suppresses_kind_status_in_groups_by_default():
adapter = _RecordingBlueBubblesAdapter(chat_type="group")

result = await adapter._send_with_retry(
chat_id="chat;+;guid",
content="⚡ Interrupting current task",
kind="status",
)

assert result.success is True
assert result.suppressed is True
assert adapter.sent == []


@pytest.mark.asyncio
async def test_bluebubbles_delivers_normal_replies_in_groups():
adapter = _RecordingBlueBubblesAdapter(chat_type="group")

result = await adapter._send_with_retry(
chat_id="chat;+;guid",
content="normal answer",
)

assert result.success is True
assert result.suppressed is False
assert len(adapter.sent) == 1
assert adapter.sent[0]["content"] == "normal answer"


@pytest.mark.asyncio
async def test_bluebubbles_delivers_status_in_dms():
adapter = _RecordingBlueBubblesAdapter(chat_type="dm")

result = await adapter._send_with_retry(
chat_id="person@example.com",
content="⚡ Interrupting current task",
kind="status",
)

assert result.success is True
assert result.suppressed is False
assert len(adapter.sent) == 1


@pytest.mark.asyncio
async def test_bluebubbles_status_group_suppression_can_be_disabled():
adapter = _RecordingBlueBubblesAdapter(
chat_type="group",
show_status_in_groups=True,
)

result = await adapter._send_with_retry(
chat_id="chat;+;guid",
content="⚡ Interrupting current task",
kind="status",
)

assert result.success is True
assert result.suppressed is False
assert len(adapter.sent) == 1
Loading