diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py index ff15f3e21fcc6..70176c03c0807 100644 --- a/gateway/authz_mixin.py +++ b/gateway/authz_mixin.py @@ -34,7 +34,12 @@ _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 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 = { # 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..2a5bff0cfee03 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,124 @@ 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_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 + chat_id = str(data.get("chatId") or "") + # 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 ( + 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): + """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: + 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), "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). + + 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 "") + 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 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=shared_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/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 4a8b085979fdc..8688472cdfe97 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 @@ -481,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]: @@ -514,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") @@ -570,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 @@ -859,14 +863,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 +976,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 +1169,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..4301df5fe5377 --- /dev/null +++ b/tests/gateway/test_whatsapp_observe_unmentioned_groups.py @@ -0,0 +1,256 @@ +"""WhatsApp observe-unmentioned group context (Telegram observe-mode parity). + +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.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" + +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, +} + + +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 + + +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({}) + 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 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) + return MessageEvent(text=body, message_type=msg_type, source=_source(uid), + raw_message=data, message_id="MSG1"), data + + def test_observer_keeps_principal_and_declares_shared_session(self, monkeypatch): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + seen_sources, appended = [], [] + + 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")) + + class FakeEntry: + session_id = "sess_1" + + class FakeStore: + def get_or_create_session(self, source): + seen_sources.append(source) + 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] + # 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]") + + 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.text.startswith("[Tester|447468411310]") + + def test_command_keeps_sender_and_shares_session(self): + adapter = _adapter_with_extra(OBSERVE_EXTRA) + 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_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 + assert uses_observed_context(None) is False + assert uses_observed_context("plain prompt") is False