From 042a4fe7d6be89082d733e138689507f271c568f Mon Sep 17 00:00:00 2001 From: samuelcardillo Date: Mon, 5 Oct 2026 21:30:34 +0400 Subject: [PATCH 1/2] feat(whatsapp): observe-unmentioned group context (Telegram observe-mode parity) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port Telegram's `observe_unmentioned_group_messages` to the WhatsApp bridge so a require_mention bot can FOLLOW a group conversation without answering every message. Behavior (all opt-in, default unchanged): - `whatsapp.observe_unmentioned_group_messages: true` + `whatsapp.observe_allowed_chats:` (explicit group-JID allowlist, mirroring Telegram's observe_allowed_chats gate). - Group messages the require_mention gate would skip are appended to the group's SHARED session transcript as `observed=True` rows (sender-tagged `[Name|id]`), never dispatched. - Observed rows land in a chat-scoped session (user identity stripped, same mechanism Telegram uses), so a later @mention / wake-word / reply-to-bot turn in the same chat resolves to the same session and receives the stored chatter as a context-only block (`_build_gateway_agent_history` already splits `observed` rows out of replayable history when the turn's channel prompt carries the observed-context marker). - Slash-command turns keep the original sender identity; free-response chats are never observed; the bot's own messages and DMs are never observed. Auth fix required by the shared-session design: - `_GROUP_CHAT_ENV` gains `WHATSAPP_GROUP_ALLOWED_CHATS`. Attributed trigger turns carry `user_id=None` (chat-scoped source); central authz previously only knew chat-scoped group allowlists for Telegram/QQBOT, so every such WhatsApp turn was dropped by the no-user-id guard in `_hm_admit_event` while observed rows kept accumulating. This gives WhatsApp the same escape hatch Telegram observe-mode ships with. Config: - YAML bridge: `observe_unmentioned_group_messages` → `WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES`, `observe_allowed_chats` → `WHATSAPP_OBSERVE_ALLOWED_CHATS` (env wins, as with all WHATSAPP_* keys). Tests: tests/gateway/test_whatsapp_observe_unmentioned_groups.py (17 cases: observe gating matrix, shared-session storage, attribution, user-less-turn authorization, history-builder marker recognition). --- gateway/authz_mixin.py | 8 +- gateway/platforms/whatsapp_common.py | 105 +++++++++ gateway/run.py | 8 +- plugins/platforms/whatsapp/adapter.py | 23 +- ...est_whatsapp_observe_unmentioned_groups.py | 203 ++++++++++++++++++ 5 files changed, 339 insertions(+), 8 deletions(-) create mode 100644 tests/gateway/test_whatsapp_observe_unmentioned_groups.py diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py index ff15f3e21fcc6..b7dbe9b467ecd 100644 --- a/gateway/authz_mixin.py +++ b/gateway/authz_mixin.py @@ -34,7 +34,13 @@ _ALLOWED_USERS_ENV = {Platform(k): v for k, v in _PLATFORM_ALLOWLIST_ENV.items()} _ALLOW_ALL_ENV = {p: v.replace("_ALLOWED_USERS", "_ALLOW_ALL_USERS") for p, v in _ALLOWED_USERS_ENV.items()} _GROUP_USER_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_USERS"} -_GROUP_CHAT_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_CHATS", Platform.QQBOT: "QQ_GROUP_ALLOWED_USERS"} +_GROUP_CHAT_ENV = { + Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_CHATS", Platform.QQBOT: "QQ_GROUP_ALLOWED_USERS", + # WhatsApp observe-unmentioned mode (Telegram parity) strips user_id on triggered group turns + # so they share the group session with observed rows; without a chat-scoped grant the + # no-user-id guard would drop every such turn (WhatsApp had no entry here by default). + Platform.WHATSAPP: "WHATSAPP_GROUP_ALLOWED_CHATS", +} _ALLOW_BOTS_ENV = { # Bots admitted by {PLATFORM}_ALLOW_BOTS bypass the human allowlist (#4466). Checked before the # no-user-id guard below: some platforms deliver bot/automation traffic with no user_id at all -- e.g. diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.py index 1ac99c8839aa4..1322aa26699f9 100644 --- a/gateway/platforms/whatsapp_common.py +++ b/gateway/platforms/whatsapp_common.py @@ -11,10 +11,12 @@ from __future__ import annotations +import dataclasses import json import logging import os import re +from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, Optional @@ -264,6 +266,109 @@ def _should_process_message(self, data: Dict[str, Any]) -> bool: or self._message_matches_mention_patterns(data) ) + # ---------------------------------------------- observed group context (Telegram observe_unmentioned parity) + + def _whatsapp_observe_unmentioned_group_messages(self) -> bool: + """``extra.observe_unmentioned_group_messages`` else WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES (default false).""" + configured = (self.config.extra or {}).get("observe_unmentioned_group_messages") + if configured is None: + configured = _get_wsecret("WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES", default="false") or "false" + if isinstance(configured, str): + return configured.lower() in _TRUTHY + return bool(configured) + + def _whatsapp_observe_allowed_chats(self) -> set: + """Chats where observed context may be collected: ``extra.observe_allowed_chats`` (blank = unset) + else WHATSAPP_OBSERVE_ALLOWED_CHATS. Empty = observe nothing (explicit allowlist required, + mirroring Telegram's ``observe_allowed_chats`` gate).""" + return self._coerce_allow_list( + _extra_or_wsecret(self.config.extra, "observe_allowed_chats", "WHATSAPP_OBSERVE_ALLOWED_CHATS")) + + def _whatsapp_should_observe_unmentioned_group_message(self, data: Dict[str, Any]) -> bool: + """True when a group message skipped by the trigger gate should be stored as observed context.""" + if not data.get("isGroup", False) or data.get("fromMe"): + return False + if not self._whatsapp_observe_unmentioned_group_messages(): + return False + chat_id = str(data.get("chatId") or "") + # Observed context is shared at chat scope, so require an explicit chat allowlist. + allowed = self._whatsapp_observe_allowed_chats() + if not allowed or chat_id not in allowed: + return False + # Free-response chats dispatch every message, so they are never observed. + if chat_id in self._whatsapp_free_response_chats(): + return False + # Only observe messages the require_mention gate would skip. + if ( + str(data.get("body") or "").strip().startswith("/") + or self._message_is_reply_to_bot(data) + or self._message_mentions_bot(data) + or self._message_matches_mention_patterns(data) + ): + return False + return True + + @staticmethod + def _whatsapp_group_observe_shared_source(source): + """Chat-scoped source so observed rows land in the group's shared session (no per-user split).""" + return dataclasses.replace(source, user_id=None, user_name=None, user_id_alt=None) + + @staticmethod + def _whatsapp_group_observe_attributed_text(event) -> str: + user_id = event.source.user_id or "unknown" + return f"[{event.source.user_name or user_id}|{user_id}]\n{event.text or ''}" + + def _whatsapp_group_observe_channel_prompt(self) -> str: + return ( + "You are handling a WhatsApp group chat message.\n" + "- observed WhatsApp group context may be provided in a separate context-only block " + "before the current message; it is not necessarily addressed to you.\n" + "- Treat only the current new message as a request explicitly directed at you, " + "and use observed context only when the current message asks for it.") + + async def _observe_unmentioned_group_message(self, data: Dict[str, Any]) -> None: + """Append skipped group chatter to the group's shared session without dispatching.""" + store = getattr(self, "_session_store", None) + if not store: + return + try: + event = await self._build_message_event(data, _skip_policy_gate=True) + if event is None: + return + session_entry = store.get_or_create_session(self._whatsapp_group_observe_shared_source(event.source)) + entry = { + "role": "user", "content": self._whatsapp_group_observe_attributed_text(event), + "timestamp": datetime.now(tz=timezone.utc).isoformat(), "observed": True} + if event.message_id: + entry["message_id"] = str(event.message_id) + store.append_to_transcript(session_entry.session_id, entry) + logger.info( + "[%s] WhatsApp group message observed (no bot trigger): chat=%s from=%s", + getattr(self, "name", "whatsapp"), data.get("chatId") or "unknown", + event.source.user_id or "unknown") + except Exception as exc: + logger.warning("[%s] Failed to observe WhatsApp group message: %s", getattr(self, "name", "whatsapp"), exc) + + def _apply_whatsapp_group_observe_attribution(self, event): + """Align triggered group turns with observed-history attribution (adds the channel prompt).""" + if not event or not self._whatsapp_observe_unmentioned_group_messages(): + return event + raw = getattr(event, "raw_message", None) + if not raw or not raw.get("isGroup", False): + return event + chat_id = str(raw.get("chatId") or "") + allowed = self._whatsapp_observe_allowed_chats() + if not allowed or chat_id not in allowed: + return event + observe_prompt = self._whatsapp_group_observe_channel_prompt() + channel_prompt = f"{event.channel_prompt}\n\n{observe_prompt}" if event.channel_prompt else observe_prompt + if str(getattr(event, "text", "") or "").strip().startswith("/"): + # Commands keep the original source (user_id) so sender checks can identify the sender. + return dataclasses.replace(event, channel_prompt=channel_prompt) + return dataclasses.replace( + event, text=self._whatsapp_group_observe_attributed_text(event), + source=self._whatsapp_group_observe_shared_source(event.source), channel_prompt=channel_prompt) + # ------------------------------------------------------------------ formatting def format_message(self, content: str) -> str: """Convert markdown to WhatsApp syntax (*bold*, _italic_, ~strike~); fenced and diff --git a/gateway/run.py b/gateway/run.py index c2733ae906d98..64fa2d9b3c86e 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -1167,16 +1167,20 @@ def _build_replay_entry( _TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER = "observed Telegram group context" +_WHATSAPP_OBSERVED_CONTEXT_PROMPT_MARKER = "observed WhatsApp group context" _OBSERVED_GROUP_CONTEXT_HEADER = "[Observed Telegram group context - context only, not requests]" _CURRENT_ADDRESSED_MESSAGE_HEADER = "[Current addressed message - answer only this unless it explicitly asks you to use the observed context]" def _uses_telegram_observed_group_context(channel_prompt: Optional[str]) -> bool: - """Return True for Telegram group turns that may include observed chatter. + """Return True for group turns (Telegram or WhatsApp) that may include observed chatter. Observed rows must not replay as ordinary user turns, or a weak wake word makes old chatter look like work. """ - return bool(channel_prompt and _TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER in channel_prompt) + if not channel_prompt: + return False + return (_TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER in channel_prompt + or _WHATSAPP_OBSERVED_CONTEXT_PROMPT_MARKER in channel_prompt) def _csv_or_list_to_set(raw: Any) -> set[str]: diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py index 4a8b085979fdc..5400b2b121485 100644 --- a/plugins/platforms/whatsapp/adapter.py +++ b/plugins/platforms/whatsapp/adapter.py @@ -2,6 +2,7 @@ client; messages are polled over a local HTTP API and responses are posted back through it.""" import asyncio +import dataclasses import logging import mimetypes import os @@ -9,6 +10,7 @@ import re import signal import subprocess +from datetime import datetime, timezone from contextlib import suppress from functools import wraps from pathlib import Path @@ -859,14 +861,19 @@ async def _poll_messages(self) -> None: async with self._bridge_req("get", "messages", 30) as resp: if resp.status == 200: for msg_data in await resp.json(): + # Observed-context collector runs BEFORE the trigger gate so a skipped + # group message is stored (never dispatched) when configured. + if not msg_data.get("isGroup", False) or not msg_data.get("fromMe", False): + if self._whatsapp_should_observe_unmentioned_group_message(msg_data): + await self._observe_unmentioned_group_message(msg_data) event = await self._build_message_event(msg_data) if event: # Fire-and-forget: a slow bridge /read must not delay dispatch. asyncio.create_task(self._send_read_receipt(msg_data)) if event.message_type == MessageType.TEXT: - self._enqueue_text_event(event) + self._enqueue_text_event(self._apply_whatsapp_group_observe_attribution(event)) else: - await self.handle_message(event) + await self.handle_message(self._apply_whatsapp_group_observe_attribution(event)) except asyncio.CancelledError: break except Exception as e: @@ -967,10 +974,14 @@ def _quoted_media(self, data: Dict[str, Any], raw_reply_id: Any) -> list[tuple[s print(f"[{self.name}] Attached quoted-reply media: {path}", flush=True) return accepted - async def _build_message_event(self, data: Dict[str, Any]) -> Optional[MessageEvent]: - """Build a MessageEvent from bridge message data, downloading images to cache.""" + async def _build_message_event(self, data: Dict[str, Any], *, _skip_policy_gate: bool = False) -> Optional[MessageEvent]: + """Build a MessageEvent from bridge message data, downloading images to cache. + + ``_skip_policy_gate=True`` is for the observed-context collector: the message already passed + ``_whatsapp_should_observe_unmentioned_group_message``, so the trigger gate must not re-drop it. + """ try: - if not self._should_process_message(data): + if not _skip_policy_gate and not self._should_process_message(data): return None msg_type = self._classify_bridge_message(data) source = self.build_source(chat_id=data.get("chatId", ""), chat_name=data.get("chatName"), chat_type="group" if data.get("isGroup", False) else "dm", @@ -1156,6 +1167,8 @@ def interactive_setup() -> None: ("group_policy", "WHATSAPP_GROUP_POLICY", "lower"), ("mention_patterns", "WHATSAPP_MENTION_PATTERNS", "json"), ("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS", "csv"), ("allow_from", "WHATSAPP_ALLOWED_USERS", "csv"), ("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS", "csv"), + ("observe_unmentioned_group_messages", "WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES", "lower"), + ("observe_allowed_chats", "WHATSAPP_OBSERVE_ALLOWED_CHATS", "csv"), ) diff --git a/tests/gateway/test_whatsapp_observe_unmentioned_groups.py b/tests/gateway/test_whatsapp_observe_unmentioned_groups.py new file mode 100644 index 0000000000000..fa05aee79b326 --- /dev/null +++ b/tests/gateway/test_whatsapp_observe_unmentioned_groups.py @@ -0,0 +1,203 @@ +"""WhatsApp observe-unmentioned group context (Telegram observe-mode parity). + +Two behaviors under test: + +1. With ``observe_unmentioned_group_messages`` enabled and an explicit chat allowlist, + group messages the ``require_mention`` gate skips are stored as ``observed=True`` + transcript rows in the group's SHARED session (no per-user split), mirroring + ``telegram.observe_unmentioned_group_messages``. Triggered turns in the same chat are + re-sourced to that shared session and tagged with the observed-context channel prompt + so ``_build_gateway_agent_history`` splits the observed rows out of replayable history. + +2. Regression for the user-less trigger turn: because attribution strips ``user_id`` + from the event source, gateway authorization must admit the turn via a chat-scoped + group allowlist — ``_GROUP_CHAT_ENV`` gains ``WHATSAPP_GROUP_ALLOWED_CHATS`` (it only + listed Telegram/QQBOT before). Without it, every triggered group turn is dropped by + the no-user-id guard in ``_hm_admit_event`` while observed rows keep accumulating. +""" + +import asyncio + +import pytest + +from gateway.config import Platform, PlatformConfig +from gateway.platforms.event import MessageEvent, MessageType +from gateway.session import SessionSource +from gateway.run import _uses_telegram_observed_group_context as uses_observed_context # noqa: E402 + +GROUP_JID = "120363414190214470@g.us" +OTHER_JID = "120363433018457345@g.us" + +OBSERVE_EXTRA = { + "observe_unmentioned_group_messages": True, + "observe_allowed_chats": f"{GROUP_JID},{OTHER_JID}", +} + + +def _adapter_with_extra(extra): + from plugins.platforms.whatsapp.adapter import WhatsAppAdapter + return WhatsAppAdapter(PlatformConfig(enabled=True, extra=extra)) + + +def _group_data(body, *, chat=GROUP_JID, sender="447468411310", from_me=False, **kw): + data = {"chatId": chat, "body": body, "isGroup": True, "fromMe": from_me, + "senderId": sender, "senderName": "Tester", "messageId": "MSG1"} + data.update(kw) + return data + + +class TestObserveGating: + def test_feature_off_by_default(self): + adapter = _adapter_with_extra({}) + assert adapter._whatsapp_observe_unmentioned_group_messages() is False + assert adapter._whatsapp_observe_allowed_chats() == set() + + def test_plain_chatter_in_allowlisted_group_is_observed(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("lunch later?")) is True + + def test_mention_is_never_observed(self, monkeypatch): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + monkeypatch.setattr(type(adapter), "_message_is_reply_to_bot", lambda self, d: False) + monkeypatch.setattr(type(adapter), "_message_mentions_bot", lambda self, d: True) + monkeypatch.setattr(type(adapter), "_message_matches_mention_patterns", lambda self, d: False) + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("hey @bot")) is False + + def test_reply_to_bot_is_never_observed(self, monkeypatch): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + monkeypatch.setattr(type(adapter), "_message_is_reply_to_bot", lambda self, d: True) + monkeypatch.setattr(type(adapter), "_message_mentions_bot", lambda self, d: False) + monkeypatch.setattr(type(adapter), "_message_matches_mention_patterns", lambda self, d: False) + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("thanks")) is False + + def test_wake_word_pattern_is_never_observed(self, monkeypatch): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + monkeypatch.setattr(type(adapter), "_message_is_reply_to_bot", lambda self, d: False) + monkeypatch.setattr(type(adapter), "_message_mentions_bot", lambda self, d: False) + monkeypatch.setattr(type(adapter), "_message_matches_mention_patterns", lambda self, d: True) + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("eva what time?")) is False + + def test_command_is_never_observed(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("/new")) is False + + def test_non_allowlisted_chat_is_never_observed(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + assert adapter._whatsapp_should_observe_unmentioned_group_message( + _group_data("hi", chat="999999999@g.us")) is False + + def test_own_messages_and_dms_are_never_observed(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + assert adapter._whatsapp_should_observe_unmentioned_group_message( + _group_data("echo", from_me=True)) is False + assert adapter._whatsapp_should_observe_unmentioned_group_message( + _group_data("hi", chat="447468411310@s.whatsapp.net", isGroup=False)) is False + + def test_empty_observe_allowlist_observes_nothing(self): + adapter = _adapter_with_extra({"observe_unmentioned_group_messages": True}) + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("hi")) is False + + +class TestObserveStorageAndAttribution: + def _event(self, body="hello", uid="447468411310"): + data = _group_data(body) + source = SessionSource(platform=Platform.WHATSAPP, chat_id=GROUP_JID, chat_name="G", + chat_type="group", user_id=uid, user_name="Tester", message_id="MSG1") + return MessageEvent(text=body, message_type=MessageType.TEXT, source=source, + raw_message=data, message_id="MSG1"), source + + def test_observer_writes_observed_row_into_shared_session(self, monkeypatch): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + appended, keys = [], [] + + async def fake_build(data, *, _skip_policy_gate=False): + _, src = self._event(data["body"]) + return MessageEvent(text=data["body"], message_type=MessageType.TEXT, source=src, + raw_message=data, message_id="MSG1") + + class FakeEntry: + session_id = "sess_1" + + class FakeStore: + def get_or_create_session(self, source): + from gateway.session import build_session_key + keys.append(build_session_key(source, group_sessions_per_user=True, profile="p")) + return FakeEntry() + + def append_to_transcript(self, sid, entry): + appended.append((sid, entry)) + + monkeypatch.setattr(type(adapter), "_build_message_event", staticmethod(fake_build)) + adapter._session_store = FakeStore() + asyncio.run(adapter._observe_unmentioned_group_message(_group_data("lunch later?"))) + assert len(appended) == 1 + sid, entry = appended[0] + assert sid == "sess_1" + assert entry["observed"] is True and entry["role"] == "user" + assert entry["content"].startswith("[Tester|447468411310]") + # Shared chat-scoped session: no per-user suffix (observed rows and later + # attributed trigger turns must resolve to the SAME session key). + assert keys and keys[0].endswith(f"whatsapp:group:{GROUP_JID}") + + def test_triggered_text_turn_is_attributed_and_shared(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + event, _ = self._event("@bot summarize this") + out = adapter._apply_whatsapp_group_observe_attribution(event) + assert "observed WhatsApp group context" in (out.channel_prompt or "") + assert out.source.user_id is None and out.source.chat_id == GROUP_JID + assert out.text.startswith("[Tester|447468411310]") + + def test_triggered_command_keeps_sender_identity(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + event, _ = self._event("/new", uid="971555544440") + event = MessageEvent(text="/new", message_type=MessageType.COMMAND, source=event.source, + raw_message=event.raw_message) + out = adapter._apply_whatsapp_group_observe_attribution(event) + assert out.source.user_id == "971555544440" + assert "observed WhatsApp group context" in (out.channel_prompt or "") + + def test_attribution_noop_when_feature_disabled(self): + adapter = _adapter_with_extra({}) + event, source = self._event() + out = adapter._apply_whatsapp_group_observe_attribution(event) + assert out.source.user_id == source.user_id + assert "observed WhatsApp group context" not in (out.channel_prompt or "") + + +class TestTriggeredTurnAuthorization: + """Attributed trigger turns carry ``user_id=None``; the chat-scoped group allowlist must + admit them (mirrors ``TELEGRAM_GROUP_ALLOWED_CHATS``).""" + + def test_whatsapp_registered_in_group_chat_env(self): + from gateway.authz_mixin import _GROUP_CHAT_ENV + assert _GROUP_CHAT_ENV.get(Platform.WHATSAPP) == "WHATSAPP_GROUP_ALLOWED_CHATS" + + def test_chat_scoped_grant_admits_userless_group_turn(self, monkeypatch): + from gateway.authz_mixin import GatewayAuthorizationMixin + source = SessionSource(platform=Platform.WHATSAPP, chat_id=GROUP_JID, chat_type="group", + user_id=None) + mixin = GatewayAuthorizationMixin.__new__(GatewayAuthorizationMixin) + monkeypatch.setattr("gateway.authz_mixin._auth_env", + lambda name: GROUP_JID if name == "WHATSAPP_GROUP_ALLOWED_CHATS" else "") + monkeypatch.setattr(mixin, "_adapter_profile_for_source", lambda s: None, raising=False) + monkeypatch.setattr(mixin, "_adapter_extra_for_source", lambda s: {}, raising=False) + monkeypatch.setattr(mixin, "_adapter_flag", lambda *a, **k: False, raising=False) + assert mixin._chat_scoped_grant(source, None, is_group=True, allow_adapter_delegation=True) is True + + def test_chat_scoped_grant_rejects_unlisted_chat(self, monkeypatch): + from gateway.authz_mixin import GatewayAuthorizationMixin + source = SessionSource(platform=Platform.WHATSAPP, chat_id="999999999@g.us", chat_type="group", + user_id=None) + mixin = GatewayAuthorizationMixin.__new__(GatewayAuthorizationMixin) + monkeypatch.setattr("gateway.authz_mixin._auth_env", + lambda name: GROUP_JID if name == "WHATSAPP_GROUP_ALLOWED_CHATS" else "") + monkeypatch.setattr(mixin, "_adapter_profile_for_source", lambda s: None, raising=False) + monkeypatch.setattr(mixin, "_adapter_extra_for_source", lambda s: {}, raising=False) + monkeypatch.setattr(mixin, "_adapter_flag", lambda *a, **k: False, raising=False) + assert mixin._chat_scoped_grant(source, None, is_group=True, allow_adapter_delegation=True) is False + + def test_history_builder_uses_whatsapp_marker(self): + assert uses_observed_context("You are handling a WhatsApp group chat message.\n- observed WhatsApp group context may be provided") is True + assert uses_observed_context("observed Telegram group context ...") is True + assert uses_observed_context(None) is False + assert uses_observed_context("plain prompt") is False From 210fb9ef1f19a9a608d54e137cea74fa814d6ef9 Mon Sep 17 00:00:00 2001 From: samuelcardillo Date: Thu, 8 Oct 2026 07:52:04 +0400 Subject: [PATCH 2/2] fix: preserve boot spool-recovery lifecycle (review N1) + drop unrelated main-drift hunks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous rework commit accidentally carried new-main state into gateway/run.py, removing _recover_pending_flushes and its startup call while the old-base ecosystem (shutdown_flush.py, test_profile_spool_recovery.py) still expects them. Restore the old-base run.py (which already contains the WhatsApp marker change) and rebuild the other five files as feature-only diffs — no unrelated main drift. Verified: test_profile_spool_recovery + test_shutdown_flush 12 passed (was 11 + collection error); observe tests 18 passed; sibling suites 117 passed. --- gateway/authz_mixin.py | 5 +- gateway/platforms/whatsapp_common.py | 51 +++-- gateway/session.py | 21 +- plugins/platforms/whatsapp/adapter.py | 8 +- ...est_whatsapp_observe_unmentioned_groups.py | 209 +++++++++++------- 5 files changed, 189 insertions(+), 105 deletions(-) diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py index b7dbe9b467ecd..70176c03c0807 100644 --- a/gateway/authz_mixin.py +++ b/gateway/authz_mixin.py @@ -36,9 +36,8 @@ _GROUP_USER_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_USERS"} _GROUP_CHAT_ENV = { Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_CHATS", Platform.QQBOT: "QQ_GROUP_ALLOWED_USERS", - # WhatsApp observe-unmentioned mode (Telegram parity) strips user_id on triggered group turns - # so they share the group session with observed rows; without a chat-scoped grant the - # no-user-id guard would drop every such turn (WhatsApp had no entry here by default). + # WhatsApp group-level chat grant: admit user-less group principals the same way Telegram + # observe-mode does (anonymous senders, adapter flows that deliver without a user id). Platform.WHATSAPP: "WHATSAPP_GROUP_ALLOWED_CHATS", } _ALLOW_BOTS_ENV = { diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.py index 1322aa26699f9..2a5bff0cfee03 100644 --- a/gateway/platforms/whatsapp_common.py +++ b/gateway/platforms/whatsapp_common.py @@ -284,19 +284,27 @@ def _whatsapp_observe_allowed_chats(self) -> set: return self._coerce_allow_list( _extra_or_wsecret(self.config.extra, "observe_allowed_chats", "WHATSAPP_OBSERVE_ALLOWED_CHATS")) + def _whatsapp_observe_scope_active(self, chat_id: str) -> bool: + """Single effective observe scope used by BOTH collection and attribution (F-002): feature + enabled + chat explicitly allowlisted + mention-gated intake (require_mention on, chat not + free-response). When normal processing already dispatches every message there is nothing + to observe and no attribution may re-source the event.""" + if not self._whatsapp_observe_unmentioned_group_messages(): + return False + if not self._whatsapp_require_mention(): + return False + if chat_id in self._whatsapp_free_response_chats(): + return False + allowed = self._whatsapp_observe_allowed_chats() + return bool(allowed) and chat_id in allowed + def _whatsapp_should_observe_unmentioned_group_message(self, data: Dict[str, Any]) -> bool: """True when a group message skipped by the trigger gate should be stored as observed context.""" if not data.get("isGroup", False) or data.get("fromMe"): return False - if not self._whatsapp_observe_unmentioned_group_messages(): - return False chat_id = str(data.get("chatId") or "") - # Observed context is shared at chat scope, so require an explicit chat allowlist. - allowed = self._whatsapp_observe_allowed_chats() - if not allowed or chat_id not in allowed: - return False - # Free-response chats dispatch every message, so they are never observed. - if chat_id in self._whatsapp_free_response_chats(): + # Single effective scope: mention-gated intake + explicit chat allowlist (F-002). + if not self._whatsapp_observe_scope_active(chat_id): return False # Only observe messages the require_mention gate would skip. if ( @@ -310,8 +318,10 @@ def _whatsapp_should_observe_unmentioned_group_message(self, data: Dict[str, Any @staticmethod def _whatsapp_group_observe_shared_source(source): - """Chat-scoped source so observed rows land in the group's shared session (no per-user split).""" - return dataclasses.replace(source, user_id=None, user_name=None, user_id_alt=None) + """Shared-session source: the sender id is KEPT (admission/slash checks still see the + principal) but the session is declared shared, so observed chatter, addressed turns and + commands all key ONE group lane (F-001/F-003).""" + return dataclasses.replace(source, shared_session=True) @staticmethod def _whatsapp_group_observe_attributed_text(event) -> str: @@ -338,7 +348,7 @@ async def _observe_unmentioned_group_message(self, data: Dict[str, Any]) -> None session_entry = store.get_or_create_session(self._whatsapp_group_observe_shared_source(event.source)) entry = { "role": "user", "content": self._whatsapp_group_observe_attributed_text(event), - "timestamp": datetime.now(tz=timezone.utc).isoformat(), "observed": True} + "timestamp": datetime.now(tz=timezone.utc), "observed": True} if event.message_id: entry["message_id"] = str(event.message_id) store.append_to_transcript(session_entry.session_id, entry) @@ -350,24 +360,29 @@ async def _observe_unmentioned_group_message(self, data: Dict[str, Any]) -> None logger.warning("[%s] Failed to observe WhatsApp group message: %s", getattr(self, "name", "whatsapp"), exc) def _apply_whatsapp_group_observe_attribution(self, event): - """Align triggered group turns with observed-history attribution (adds the channel prompt).""" - if not event or not self._whatsapp_observe_unmentioned_group_messages(): + """Align triggered group turns with observed-history attribution (adds the channel prompt). + + The caller identity survives admission (F-001): the source keeps ``user_id`` and only the + routing declaration (``shared_session``) changes, so session controls act on the same + shared lane as the observed transcript (F-003).""" + if not event: return event raw = getattr(event, "raw_message", None) if not raw or not raw.get("isGroup", False): return event chat_id = str(raw.get("chatId") or "") - allowed = self._whatsapp_observe_allowed_chats() - if not allowed or chat_id not in allowed: + if not self._whatsapp_observe_scope_active(chat_id): return event observe_prompt = self._whatsapp_group_observe_channel_prompt() channel_prompt = f"{event.channel_prompt}\n\n{observe_prompt}" if event.channel_prompt else observe_prompt + shared_source = dataclasses.replace(event.source, shared_session=True) if str(getattr(event, "text", "") or "").strip().startswith("/"): - # Commands keep the original source (user_id) so sender checks can identify the sender. - return dataclasses.replace(event, channel_prompt=channel_prompt) + # Commands keep the original source (user_id) so sender checks identify the sender, + # but route to the shared session (F-003). + return dataclasses.replace(event, source=shared_source, channel_prompt=channel_prompt) return dataclasses.replace( event, text=self._whatsapp_group_observe_attributed_text(event), - source=self._whatsapp_group_observe_shared_source(event.source), channel_prompt=channel_prompt) + source=shared_source, channel_prompt=channel_prompt) # ------------------------------------------------------------------ formatting def format_message(self, content: str) -> str: diff --git a/gateway/session.py b/gateway/session.py index 6e6c6dd2926c2..98b98a925259c 100644 --- a/gateway/session.py +++ b/gateway/session.py @@ -94,6 +94,10 @@ class SessionSource: # Discord auto-thread continuity: the thread id a CHANNEL message WILL be delivered into, so # the initiating message and later in-thread follow-ups share ONE session. prospective_thread_id: Optional[str] = None + # The adapter declares this chat's session shared by every participant even though the + # sender id is kept (WhatsApp/Telegram observe mode: commands and text turns keep user_id + # for admission/slash-access checks while observed chatter keys the shared lane). + shared_session: bool = False # Wire-INVISIBLE trust signal (never in to_dict/from_dict, so a peer cannot forge it): came # over the authenticated relay WebSocket. ``platform`` is the UNDERLYING platform, not # ``relay``, so authz must key upstream trust off THIS flag. @@ -143,6 +147,8 @@ def _optional(names) -> None: _optional(self._OPTIONAL_POST_SCOPE) if self.auto_thread_created: d["auto_thread_created"] = True + if self.shared_session: + d["shared_session"] = True _optional(self._OPTIONAL_TAIL) return d @@ -157,7 +163,8 @@ def from_dict(cls, data: Dict[str, Any]) -> "SessionSource": platform=Platform(data["platform"]), chat_id=str(data["chat_id"]), chat_type=data.get("chat_type", "dm"), scope_id=data.get("scope_id", data.get("guild_id")), - auto_thread_created=bool(data.get("auto_thread_created", False)), **plain, + auto_thread_created=bool(data.get("auto_thread_created", False)), + shared_session=bool(data.get("shared_session", False)), **plain, ) @@ -647,6 +654,8 @@ def is_shared_multi_user_session( isolation rules in :func:`build_session_key`).""" if source.chat_type == "dm": return False + if getattr(source, "shared_session", False): + return True return not (thread_sessions_per_user if source.thread_id else group_sessions_per_user) @@ -706,8 +715,14 @@ def build_session_key( isolate_user = not chat_id else: # Threads are shared by default; per-user isolation only via thread_sessions_per_user or - # outside a thread. - isolate_user = group_sessions_per_user and not (thread_id and not thread_sessions_per_user) + # outside a thread. An adapter-declared shared_session keeps one lane even with the + # sender id present (WhatsApp/Telegram observe mode: commands keep user_id for access + # checks but must act on the shared conversation). + isolate_user = ( + group_sessions_per_user + and not (thread_id and not thread_sessions_per_user) + and not getattr(source, "shared_session", False) + ) # Duck-typed sources may lack user_id_alt: read the participant only when it matters. participant_id = _canonical_participant(source) if (isolate_user or not is_dm) else None diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py index 5400b2b121485..8688472cdfe97 100644 --- a/plugins/platforms/whatsapp/adapter.py +++ b/plugins/platforms/whatsapp/adapter.py @@ -483,10 +483,12 @@ def _bridge_env(self) -> dict: bridge_env.update(HERMES_IMAGE_CACHE_DIR=str(img_dir), HERMES_AUDIO_CACHE_DIR=str(audio_dir), HERMES_DOCUMENT_CACHE_DIR=str(doc_dir)) return bridge_env - def _bridge_died(self, detail: str) -> bool: + def _bridge_died(self, detail: str, code: str = "whatsapp_bridge_exited") -> bool: print(f"[{self.name}] {detail}") print(f"[{self.name}] Check log: {self._bridge_log}") self._close_bridge_log() + # Named so the reconnect status and connect telemetry say why instead of an unclassified failure. + self._set_fatal_error(code, f"{detail} (see {self._bridge_log})", retryable=True) return False async def _poll_bridge_health(self, died_msg: str) -> tuple[Optional[bool], bool, dict]: @@ -516,7 +518,7 @@ async def _wait_for_bridge(self) -> bool: if connected is False: return False if not http_ready: - return self._bridge_died("Bridge HTTP server did not start in 15s") + return self._bridge_died("Bridge HTTP server did not start in 15s", "whatsapp_bridge_timeout") if data.get("status") != "connected": print(f"[{self.name}] Bridge HTTP ready, waiting for WhatsApp connection...") connected, _, _ = await self._poll_bridge_health("Bridge process died during connection") @@ -572,7 +574,7 @@ async def connect(self, *, is_reconnect: bool = False) -> bool: f"{exc}. Set platforms.whatsapp.extra.bridge_port to a distinct free port; " "or stop the process holding it.", retryable=False) return False - if not self._preflight(): + if not await asyncio.to_thread(self._preflight): return False bridge_path = Path(self._bridge_script) lock_acquired = False diff --git a/tests/gateway/test_whatsapp_observe_unmentioned_groups.py b/tests/gateway/test_whatsapp_observe_unmentioned_groups.py index fa05aee79b326..4301df5fe5377 100644 --- a/tests/gateway/test_whatsapp_observe_unmentioned_groups.py +++ b/tests/gateway/test_whatsapp_observe_unmentioned_groups.py @@ -1,29 +1,27 @@ """WhatsApp observe-unmentioned group context (Telegram observe-mode parity). -Two behaviors under test: - -1. With ``observe_unmentioned_group_messages`` enabled and an explicit chat allowlist, - group messages the ``require_mention`` gate skips are stored as ``observed=True`` - transcript rows in the group's SHARED session (no per-user split), mirroring - ``telegram.observe_unmentioned_group_messages``. Triggered turns in the same chat are - re-sourced to that shared session and tagged with the observed-context channel prompt - so ``_build_gateway_agent_history`` splits the observed rows out of replayable history. - -2. Regression for the user-less trigger turn: because attribution strips ``user_id`` - from the event source, gateway authorization must admit the turn via a chat-scoped - group allowlist — ``_GROUP_CHAT_ENV`` gains ``WHATSAPP_GROUP_ALLOWED_CHATS`` (it only - listed Telegram/QQBOT before). Without it, every triggered group turn is dropped by - the no-user-id guard in ``_hm_admit_event`` while observed rows keep accumulating. +Covers the four review contracts for this feature: + +- F-001: attributed trigger turns keep the caller identity (``user_id`` survives), so an + already-allowed participant stays admitted without any extra chat-grant configuration. +- F-002: one effective observe scope (feature flag + explicit chat allowlist + mention-gated + intake) governs BOTH collection and attribution; normal-processing and free-response chats + are never observed nor re-sourced. +- F-003: text turns, observed chatter, commands and restored origins key the SAME shared + session (``SessionSource.shared_session``) while commands keep their sender for access checks. +- F-004: observed-row timestamps persist through the real SessionDB writer without + corrupt-timestamp warnings (datetime object, which ``coerce_epoch`` accepts). """ import asyncio +from datetime import datetime, timezone import pytest from gateway.config import Platform, PlatformConfig from gateway.platforms.event import MessageEvent, MessageType -from gateway.session import SessionSource from gateway.run import _uses_telegram_observed_group_context as uses_observed_context # noqa: E402 +from gateway.session import SessionSource, build_session_key GROUP_JID = "120363414190214470@g.us" OTHER_JID = "120363433018457345@g.us" @@ -31,6 +29,9 @@ OBSERVE_EXTRA = { "observe_unmentioned_group_messages": True, "observe_allowed_chats": f"{GROUP_JID},{OTHER_JID}", + # Observe mode only applies to mention-gated intake (F-002 scope); the tests exercise + # that posture explicitly. + "require_mention": True, } @@ -46,6 +47,11 @@ def _group_data(body, *, chat=GROUP_JID, sender="447468411310", from_me=False, * return data +def _source(uid="447468411310", chat=GROUP_JID): + return SessionSource(platform=Platform.WHATSAPP, chat_id=chat, chat_name="G", + chat_type="group", user_id=uid, user_name="Tester", message_id="MSG1") + + class TestObserveGating: def test_feature_off_by_default(self): adapter = _adapter_with_extra({}) @@ -98,30 +104,56 @@ def test_empty_observe_allowlist_observes_nothing(self): assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("hi")) is False -class TestObserveStorageAndAttribution: - def _event(self, body="hello", uid="447468411310"): +class TestEffectiveScopeExclusivity: + """F-002: one effective scope governs collection AND attribution.""" + + def test_require_mention_off_disables_observation(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + monkey_free = {"free_response_chats": ""} + adapter.config.extra = {**OBSERVE_EXTRA, **monkey_free, "require_mention": False} + assert adapter._whatsapp_observe_scope_active(GROUP_JID) is False + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("hi")) is False + + def test_free_response_chat_disables_observation_and_attribution(self): + adapter = _adapter_with_extra({**OBSERVE_EXTRA, "free_response_chats": GROUP_JID}) + assert adapter._whatsapp_observe_scope_active(GROUP_JID) is False + assert adapter._whatsapp_should_observe_unmentioned_group_message(_group_data("hi")) is False + event = MessageEvent(text="hello", message_type=MessageType.TEXT, source=_source(), + raw_message=_group_data("hello")) + out = adapter._apply_whatsapp_group_observe_attribution(event) + assert out is event # untouched: original principal/text preserved + + def test_attribution_noop_when_feature_disabled(self): + adapter = _adapter_with_extra({}) + event = MessageEvent(text="hello", message_type=MessageType.TEXT, source=_source(), + raw_message=_group_data("hello")) + out = adapter._apply_whatsapp_group_observe_attribution(event) + assert out is event + + +class TestSharedSessionRouting: + """F-001/F-003: the principal survives; routing is declared via ``shared_session``.""" + + def _event(self, body="hello", uid="447468411310", msg_type=MessageType.TEXT): data = _group_data(body) - source = SessionSource(platform=Platform.WHATSAPP, chat_id=GROUP_JID, chat_name="G", - chat_type="group", user_id=uid, user_name="Tester", message_id="MSG1") - return MessageEvent(text=body, message_type=MessageType.TEXT, source=source, - raw_message=data, message_id="MSG1"), source + return MessageEvent(text=body, message_type=msg_type, source=_source(uid), + raw_message=data, message_id="MSG1"), data - def test_observer_writes_observed_row_into_shared_session(self, monkeypatch): + def test_observer_keeps_principal_and_declares_shared_session(self, monkeypatch): adapter = _adapter_with_extra(OBSERVE_EXTRA) - appended, keys = [], [] + seen_sources, appended = [], [] async def fake_build(data, *, _skip_policy_gate=False): - _, src = self._event(data["body"]) - return MessageEvent(text=data["body"], message_type=MessageType.TEXT, source=src, - raw_message=data, message_id="MSG1") + return MessageEvent(text=data["body"], message_type=MessageType.TEXT, + source=_source(data.get("senderId")), raw_message=data, + message_id=data.get("messageId")) class FakeEntry: session_id = "sess_1" class FakeStore: def get_or_create_session(self, source): - from gateway.session import build_session_key - keys.append(build_session_key(source, group_sessions_per_user=True, profile="p")) + seen_sources.append(source) return FakeEntry() def append_to_transcript(self, sid, entry): @@ -132,70 +164,91 @@ def append_to_transcript(self, sid, entry): asyncio.run(adapter._observe_unmentioned_group_message(_group_data("lunch later?"))) assert len(appended) == 1 sid, entry = appended[0] - assert sid == "sess_1" - assert entry["observed"] is True and entry["role"] == "user" + # F-001: principal survives on the observed source + assert seen_sources[0].user_id == "447468411310" + assert seen_sources[0].shared_session is True + # F-003: keys to the SHARED lane (no per-user suffix) even with the sender present + assert build_session_key(seen_sources[0], group_sessions_per_user=True, profile="p") == \ + "agent:p:whatsapp:group:" + GROUP_JID + assert entry["observed"] is True assert entry["content"].startswith("[Tester|447468411310]") - # Shared chat-scoped session: no per-user suffix (observed rows and later - # attributed trigger turns must resolve to the SAME session key). - assert keys and keys[0].endswith(f"whatsapp:group:{GROUP_JID}") - def test_triggered_text_turn_is_attributed_and_shared(self): + def test_attribution_keeps_user_id_and_shares_session(self): adapter = _adapter_with_extra(OBSERVE_EXTRA) event, _ = self._event("@bot summarize this") out = adapter._apply_whatsapp_group_observe_attribution(event) + # F-001: user_id survives admission + assert out.source.user_id == "447468411310" + assert out.source.shared_session is True assert "observed WhatsApp group context" in (out.channel_prompt or "") - assert out.source.user_id is None and out.source.chat_id == GROUP_JID assert out.text.startswith("[Tester|447468411310]") - def test_triggered_command_keeps_sender_identity(self): + def test_command_keeps_sender_and_shares_session(self): adapter = _adapter_with_extra(OBSERVE_EXTRA) - event, _ = self._event("/new", uid="971555544440") - event = MessageEvent(text="/new", message_type=MessageType.COMMAND, source=event.source, - raw_message=event.raw_message) + event, _ = self._event("/new", uid="971555544440", msg_type=MessageType.COMMAND) out = adapter._apply_whatsapp_group_observe_attribution(event) assert out.source.user_id == "971555544440" + assert out.source.shared_session is True assert "observed WhatsApp group context" in (out.channel_prompt or "") - def test_attribution_noop_when_feature_disabled(self): - adapter = _adapter_with_extra({}) - event, source = self._event() - out = adapter._apply_whatsapp_group_observe_attribution(event) - assert out.source.user_id == source.user_id - assert "observed WhatsApp group context" not in (out.channel_prompt or "") - - -class TestTriggeredTurnAuthorization: - """Attributed trigger turns carry ``user_id=None``; the chat-scoped group allowlist must - admit them (mirrors ``TELEGRAM_GROUP_ALLOWED_CHATS``).""" - - def test_whatsapp_registered_in_group_chat_env(self): - from gateway.authz_mixin import _GROUP_CHAT_ENV - assert _GROUP_CHAT_ENV.get(Platform.WHATSAPP) == "WHATSAPP_GROUP_ALLOWED_CHATS" - - def test_chat_scoped_grant_admits_userless_group_turn(self, monkeypatch): - from gateway.authz_mixin import GatewayAuthorizationMixin - source = SessionSource(platform=Platform.WHATSAPP, chat_id=GROUP_JID, chat_type="group", - user_id=None) - mixin = GatewayAuthorizationMixin.__new__(GatewayAuthorizationMixin) - monkeypatch.setattr("gateway.authz_mixin._auth_env", - lambda name: GROUP_JID if name == "WHATSAPP_GROUP_ALLOWED_CHATS" else "") - monkeypatch.setattr(mixin, "_adapter_profile_for_source", lambda s: None, raising=False) - monkeypatch.setattr(mixin, "_adapter_extra_for_source", lambda s: {}, raising=False) - monkeypatch.setattr(mixin, "_adapter_flag", lambda *a, **k: False, raising=False) - assert mixin._chat_scoped_grant(source, None, is_group=True, allow_adapter_delegation=True) is True - - def test_chat_scoped_grant_rejects_unlisted_chat(self, monkeypatch): - from gateway.authz_mixin import GatewayAuthorizationMixin - source = SessionSource(platform=Platform.WHATSAPP, chat_id="999999999@g.us", chat_type="group", - user_id=None) - mixin = GatewayAuthorizationMixin.__new__(GatewayAuthorizationMixin) - monkeypatch.setattr("gateway.authz_mixin._auth_env", - lambda name: GROUP_JID if name == "WHATSAPP_GROUP_ALLOWED_CHATS" else "") - monkeypatch.setattr(mixin, "_adapter_profile_for_source", lambda s: None, raising=False) - monkeypatch.setattr(mixin, "_adapter_extra_for_source", lambda s: {}, raising=False) - monkeypatch.setattr(mixin, "_adapter_flag", lambda *a, **k: False, raising=False) - assert mixin._chat_scoped_grant(source, None, is_group=True, allow_adapter_delegation=True) is False + def test_text_command_observed_all_key_one_session(self): + """F-003 invariant: addressed text, command, observed chatter and a restored command + origin resolve to ONE session key at default ``group_sessions_per_user=True``.""" + adapter = _adapter_with_extra(OBSERVE_EXTRA) + text_event, _ = self._event("@bot summarize this") + cmd_event, _ = self._event("/new", uid="971555544440", msg_type=MessageType.COMMAND) + observed_src = adapter._whatsapp_group_observe_shared_source(_source()) + text_out = adapter._apply_whatsapp_group_observe_attribution(text_event) + cmd_out = adapter._apply_whatsapp_group_observe_attribution(cmd_event) + restored_cmd = SessionSource.from_dict(cmd_out.source.to_dict()) + keys = { + build_session_key(text_out.source, group_sessions_per_user=True, profile="p"), + build_session_key(cmd_out.source, group_sessions_per_user=True, profile="p"), + build_session_key(observed_src, group_sessions_per_user=True, profile="p"), + build_session_key(restored_cmd, group_sessions_per_user=True, profile="p"), + } + assert len(keys) == 1 + assert keys.pop().endswith(f"whatsapp:group:{GROUP_JID}") + # the command STILL carries its sender for access checks + assert cmd_out.source.user_id == "971555544440" + + +class TestDurableTimestamp: + """F-004: the observer's timestamp survives the real SessionDB writer.""" + + def test_datetime_timestamp_round_trips_without_warning(self, tmp_path, monkeypatch): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + frozen = datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc) + monkeypatch.setattr("gateway.platforms.whatsapp_common.datetime", + type("D", (), {"now": staticmethod(lambda tz=None: frozen)})) + async def fake_build(data, *, _skip_policy_gate=False): + return MessageEvent(text=data["body"], message_type=MessageType.TEXT, + source=_source(data.get("senderId")), raw_message=data, + message_id=data.get("messageId")) + + monkeypatch.setattr(type(adapter), "_build_message_event", staticmethod(fake_build)) + from agent import secret_scope as ss + (tmp_path / ".env").write_text("", encoding="utf-8") + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(tmp_path)) + try: + from gateway.session import SessionStore + from gateway.config import GatewayConfig + store = SessionStore(tmp_path / "state", GatewayConfig()) + adapter._session_store = store + asyncio.run(adapter._observe_unmentioned_group_message(_group_data("lunch later?"))) + session_entry = store._entries[next(iter(store._entries))] + rows = store.load_transcript(session_entry.session_id) + assert rows and rows[-1]["observed"] is True + # exact durable readback, no fallback substitution + assert rows[-1]["timestamp"] == pytest.approx(frozen.timestamp()) + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + +class TestHistoryBuilderMarker: def test_history_builder_uses_whatsapp_marker(self): assert uses_observed_context("You are handling a WhatsApp group chat message.\n- observed WhatsApp group context may be provided") is True assert uses_observed_context("observed Telegram group context ...") is True