From 8a989d5adf1aebf497288351582572c342d794ed Mon Sep 17 00:00:00 2001 From: Orrin Witt Date: Wed, 28 Oct 2026 23:52:57 -0400 Subject: [PATCH] feat(matrix): per-room group policy overrides (groupPolicyOverrides) (#6287) --- docs/chat-apps.md | 2 + nanobot/channels/matrix/manifest.py | 1 + nanobot/channels/matrix/runtime.py | 19 ++- .../matrix/tests/test_matrix_channel.py | 161 ++++++++++++++++++ nanobot/channels/matrix/webui/locales/en.json | 3 + nanobot/channels/matrix/webui/locales/es.json | 3 + nanobot/channels/matrix/webui/locales/fr.json | 3 + nanobot/channels/matrix/webui/locales/id.json | 3 + nanobot/channels/matrix/webui/locales/ja.json | 3 + nanobot/channels/matrix/webui/locales/ko.json | 3 + .../channels/matrix/webui/locales/pt-BR.json | 3 + nanobot/channels/matrix/webui/locales/vi.json | 3 + .../channels/matrix/webui/locales/zh-CN.json | 3 + .../channels/matrix/webui/locales/zh-TW.json | 3 + 14 files changed, 210 insertions(+), 3 deletions(-) diff --git a/docs/chat-apps.md b/docs/chat-apps.md index 297599f00..974b3435d 100644 --- a/docs/chat-apps.md +++ b/docs/chat-apps.md @@ -376,6 +376,7 @@ nanobot plugins enable matrix "allowFrom": ["@your_user:matrix.org"], "groupPolicy": "open", "groupAllowFrom": [], + "groupPolicyOverrides": {}, "allowRoomMentions": false, "maxMediaBytes": 20971520 } @@ -390,6 +391,7 @@ nanobot plugins enable matrix | `allowFrom` | User IDs allowed to interact. Empty denies all; use `["*"]` to allow everyone. | | `groupPolicy` | `open` (default), `mention`, `allowlist`, or `listen`. | | `groupAllowFrom` | Room allowlist (used when policy is `allowlist`). | +| `groupPolicyOverrides` | Optional per-room overrides for `groupPolicy`, keyed by Matrix room ID (for example, `"!abc123:matrix.org"`). Values mirror `groupPolicy`: `"open"`, `"mention"`, or `"allowlist"` (an `allowlist` override is checked against `groupAllowFrom`). Rooms not listed fall back to `groupPolicy`. | | `allowRoomMentions` | Accept `@room` mentions in mention mode. | | `replyToMessage` | Quote the user's message in non-threaded replies (default `true`). Set `false` to send without quotes; thread replies are unchanged. | | `e2eeEnabled` | E2EE support (default `true`). Set `false` for plaintext-only. | diff --git a/nanobot/channels/matrix/manifest.py b/nanobot/channels/matrix/manifest.py index d7c875d13..12d723b50 100644 --- a/nanobot/channels/matrix/manifest.py +++ b/nanobot/channels/matrix/manifest.py @@ -15,6 +15,7 @@ SETUP_SPEC = ChannelSetupSpec( "accessToken": field("secret"), "deviceId": field(), "groupPolicy": field("enum", choices=MATRIX_GROUP_POLICIES, default="open"), + "groupPolicyOverrides": field("json", default={}), "allowFrom": field("list"), "e2eeEnabled": field("bool", default=False), "sasVerification": field("bool", default=False), diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.py index caa05048f..df69004d6 100644 --- a/nanobot/channels/matrix/runtime.py +++ b/nanobot/channels/matrix/runtime.py @@ -319,6 +319,9 @@ class MatrixConfig(Base): group_allow_from: list[str] = Field(default_factory=list) allow_room_mentions: bool = False reply_to_message: bool = True + # Per-room policy overrides keyed by room id, e.g. {"!abc:matrix.org": "mention"}. + # Rooms not listed fall back to `group_policy` (issue #6286). + group_policy_overrides: dict[str, MatrixGroupPolicy] = Field(default_factory=dict) streaming: bool = False use_proxy: bool = False @@ -1217,13 +1220,17 @@ class MatrixChannel(BaseChannel): self._listen_buffers.pop(room_id, None) self._listen_dropped.pop(room_id, None) + def _effective_group_policy(self, room_id: str) -> MatrixGroupPolicy: + """Per-room override when present, else the channel-level group policy.""" + return self.config.group_policy_overrides.get(room_id, self.config.group_policy) + def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool: """Apply sender and room policy checks.""" if not self.is_allowed(event.sender): return False if self._is_direct_room(room): return True - policy = self.config.group_policy + policy = self._effective_group_policy(room.room_id) if policy == "open": return True if policy == "allowlist": @@ -1483,7 +1490,10 @@ class MatrixChannel(BaseChannel): async def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None: if event.sender == self.config.user_id or self._is_pre_startup_event(event): return - listen_mode = not self._is_direct_room(room) and self.config.group_policy == "listen" + listen_mode = ( + not self._is_direct_room(room) + and self._effective_group_policy(room.room_id) == "listen" + ) if listen_mode and not self._is_bot_mentioned(event): if self.is_allowed(event.sender): self._buffer_listen_message(room.room_id, event.sender, event.body) @@ -1511,7 +1521,10 @@ class MatrixChannel(BaseChannel): async def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None: if event.sender == self.config.user_id or self._is_pre_startup_event(event): return - listen_mode = not self._is_direct_room(room) and self.config.group_policy == "listen" + listen_mode = ( + not self._is_direct_room(room) + and self._effective_group_policy(room.room_id) == "listen" + ) if listen_mode and not self._is_bot_mentioned(event): if self.is_allowed(event.sender): media_body = getattr(event, "body", None) diff --git a/nanobot/channels/matrix/tests/test_matrix_channel.py b/nanobot/channels/matrix/tests/test_matrix_channel.py index 40449e860..e4b5a2658 100644 --- a/nanobot/channels/matrix/tests/test_matrix_channel.py +++ b/nanobot/channels/matrix/tests/test_matrix_channel.py @@ -3226,3 +3226,164 @@ async def test_listen_media_control_command_preserves_discussion(monkeypatch) -> await channel._on_message(room, _listen_event("what did we decide?", mentioned=True)) question = await bus.consume_inbound() assert "the picnic is on Sunday" in question.metadata[RUNTIME_CONTEXT_INPUT_META][0].content + + + + +@pytest.mark.asyncio +async def test_on_message_group_policy_override_requires_mentions_in_overridden_room() -> None: + channel = MatrixChannel( + _make_config( + group_policy="open", + group_policy_overrides={"!quiet:matrix.org": "mention"}, + ), + MessageBus(), + ) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + handled: list[str] = [] + + async def _fake_handle_message(**kwargs) -> None: + handled.append(kwargs["sender_id"]) + + channel._handle_message = _fake_handle_message # type: ignore[method-assign] + + quiet_room = SimpleNamespace( + room_id="!quiet:matrix.org", display_name="Quiet room", member_count=3 + ) + open_room = SimpleNamespace( + room_id="!room:matrix.org", display_name="Open room", member_count=3 + ) + event = SimpleNamespace(sender="@alice:matrix.org", body="Hello", source={"content": {}}) + + await channel._on_message(quiet_room, event) + assert handled == [] + assert client.typing_calls == [] + + await channel._on_message(open_room, event) + assert handled == ["@alice:matrix.org"] + assert client.typing_calls == [("!room:matrix.org", True, TYPING_NOTICE_TIMEOUT_MS)] + + +@pytest.mark.asyncio +async def test_on_message_group_policy_override_honors_bot_mentions() -> None: + channel = MatrixChannel( + _make_config( + group_policy="open", + group_policy_overrides={"!quiet:matrix.org": "mention"}, + ), + MessageBus(), + ) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + handled: list[str] = [] + + async def _fake_handle_message(**kwargs) -> None: + handled.append(kwargs["sender_id"]) + + channel._handle_message = _fake_handle_message # type: ignore[method-assign] + + room = SimpleNamespace(room_id="!quiet:matrix.org", display_name="Quiet room", member_count=3) + event = SimpleNamespace( + sender="@alice:matrix.org", + body="Hello", + source={"content": {"m.mentions": {"user_ids": ["@bot:matrix.org"]}}}, + ) + + await channel._on_message(room, event) + + assert handled == ["@alice:matrix.org"] + assert client.typing_calls == [("!quiet:matrix.org", True, TYPING_NOTICE_TIMEOUT_MS)] + + +@pytest.mark.asyncio +async def test_on_message_group_policy_override_opens_room_under_mention_policy() -> None: + channel = MatrixChannel( + _make_config( + group_policy="mention", + group_policy_overrides={"!dev:matrix.org": "open"}, + ), + MessageBus(), + ) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + handled: list[str] = [] + + async def _fake_handle_message(**kwargs) -> None: + handled.append(kwargs["sender_id"]) + + channel._handle_message = _fake_handle_message # type: ignore[method-assign] + + room = SimpleNamespace(room_id="!dev:matrix.org", display_name="Dev room", member_count=3) + event = SimpleNamespace(sender="@alice:matrix.org", body="Hello", source={"content": {}}) + + await channel._on_message(room, event) + + assert handled == ["@alice:matrix.org"] + assert client.typing_calls == [("!dev:matrix.org", True, TYPING_NOTICE_TIMEOUT_MS)] + + +@pytest.mark.asyncio +async def test_on_message_group_policy_override_allowlist_uses_group_allow_from() -> None: + channel = MatrixChannel( + _make_config( + group_policy="open", + group_allow_from=["!dev:matrix.org"], + group_policy_overrides={ + "!dev:matrix.org": "allowlist", + "!secret:matrix.org": "allowlist", + }, + ), + MessageBus(), + ) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + handled: list[str] = [] + + async def _fake_handle_message(**kwargs) -> None: + handled.append(kwargs["sender_id"]) + + channel._handle_message = _fake_handle_message # type: ignore[method-assign] + + event = SimpleNamespace(sender="@alice:matrix.org", body="Hello", source={"content": {}}) + + allowed_room = SimpleNamespace(room_id="!dev:matrix.org", member_count=3) + await channel._on_message(allowed_room, event) + assert handled == ["@alice:matrix.org"] + + denied_room = SimpleNamespace(room_id="!secret:matrix.org", member_count=3) + await channel._on_message(denied_room, event) + assert handled == ["@alice:matrix.org"] + assert client.typing_calls == [("!dev:matrix.org", True, TYPING_NOTICE_TIMEOUT_MS)] + + +@pytest.mark.asyncio +async def test_on_message_group_policy_override_leaves_direct_rooms_untouched() -> None: + channel = MatrixChannel( + _make_config( + group_policy="open", + group_policy_overrides={"!quiet:matrix.org": "mention"}, + ), + MessageBus(), + ) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + handled: list[str] = [] + + async def _fake_handle_message(**kwargs) -> None: + handled.append(kwargs["sender_id"]) + + channel._handle_message = _fake_handle_message # type: ignore[method-assign] + + room = SimpleNamespace(room_id="!quiet:matrix.org", display_name="Alice & bot", member_count=2) + event = SimpleNamespace(sender="@alice:matrix.org", body="Hello", source={"content": {}}) + + await channel._on_message(room, event) + + assert handled == ["@alice:matrix.org"] + assert client.typing_calls == [("!quiet:matrix.org", True, TYPING_NOTICE_TIMEOUT_MS)] diff --git a/nanobot/channels/matrix/webui/locales/en.json b/nanobot/channels/matrix/webui/locales/en.json index e75cb14ca..922402d9b 100644 --- a/nanobot/channels/matrix/webui/locales/en.json +++ b/nanobot/channels/matrix/webui/locales/en.json @@ -32,6 +32,9 @@ "listen": "Listen (reply on mention)" } }, + "groupPolicyOverrides": { + "label": "Room policy overrides (JSON)" + }, "allowFrom": { "label": "Allowed users" }, diff --git a/nanobot/channels/matrix/webui/locales/es.json b/nanobot/channels/matrix/webui/locales/es.json index 082f565ed..2a46ed317 100644 --- a/nanobot/channels/matrix/webui/locales/es.json +++ b/nanobot/channels/matrix/webui/locales/es.json @@ -32,6 +32,9 @@ "listen": "Escuchar (responder al mencionar)" } }, + "groupPolicyOverrides": { + "label": "Excepciones de reglas por sala (JSON)" + }, "allowFrom": { "label": "Usuarios permitidos" }, diff --git a/nanobot/channels/matrix/webui/locales/fr.json b/nanobot/channels/matrix/webui/locales/fr.json index f880e409a..31c574c4d 100644 --- a/nanobot/channels/matrix/webui/locales/fr.json +++ b/nanobot/channels/matrix/webui/locales/fr.json @@ -32,6 +32,9 @@ "listen": "Écouter (réponse sur mention)" } }, + "groupPolicyOverrides": { + "label": "Exceptions de règles par salon (JSON)" + }, "allowFrom": { "label": "Utilisateurs autorisés" }, diff --git a/nanobot/channels/matrix/webui/locales/id.json b/nanobot/channels/matrix/webui/locales/id.json index 145d74dac..0a44f3909 100644 --- a/nanobot/channels/matrix/webui/locales/id.json +++ b/nanobot/channels/matrix/webui/locales/id.json @@ -32,6 +32,9 @@ "listen": "Dengar (balas saat disebut)" } }, + "groupPolicyOverrides": { + "label": "Pengecualian aturan per ruang (JSON)" + }, "allowFrom": { "label": "Pengguna diizinkan" }, diff --git a/nanobot/channels/matrix/webui/locales/ja.json b/nanobot/channels/matrix/webui/locales/ja.json index c65b21e6a..fe801cc24 100644 --- a/nanobot/channels/matrix/webui/locales/ja.json +++ b/nanobot/channels/matrix/webui/locales/ja.json @@ -32,6 +32,9 @@ "listen": "リッスン(メンションで返信)" } }, + "groupPolicyOverrides": { + "label": "部屋ごとのルール例外(JSON)" + }, "allowFrom": { "label": "許可ユーザー" }, diff --git a/nanobot/channels/matrix/webui/locales/ko.json b/nanobot/channels/matrix/webui/locales/ko.json index 5fc72daa3..075a4d41a 100644 --- a/nanobot/channels/matrix/webui/locales/ko.json +++ b/nanobot/channels/matrix/webui/locales/ko.json @@ -32,6 +32,9 @@ "listen": "경청(멘션 시 응답)" } }, + "groupPolicyOverrides": { + "label": "방별 규칙 예외(JSON)" + }, "allowFrom": { "label": "허용 사용자" }, diff --git a/nanobot/channels/matrix/webui/locales/pt-BR.json b/nanobot/channels/matrix/webui/locales/pt-BR.json index 12a2b0715..ed2dc7e07 100644 --- a/nanobot/channels/matrix/webui/locales/pt-BR.json +++ b/nanobot/channels/matrix/webui/locales/pt-BR.json @@ -32,6 +32,9 @@ "listen": "Ouvir (responder ao mencionar)" } }, + "groupPolicyOverrides": { + "label": "Exceções de regras por sala (JSON)" + }, "allowFrom": { "label": "Usuários permitidos" }, diff --git a/nanobot/channels/matrix/webui/locales/vi.json b/nanobot/channels/matrix/webui/locales/vi.json index 63d1968d7..8fbd820a0 100644 --- a/nanobot/channels/matrix/webui/locales/vi.json +++ b/nanobot/channels/matrix/webui/locales/vi.json @@ -32,6 +32,9 @@ "listen": "Lắng nghe (trả lời khi được nhắc)" } }, + "groupPolicyOverrides": { + "label": "Ngoại lệ quy tắc theo phòng (JSON)" + }, "allowFrom": { "label": "Người dùng được phép" }, diff --git a/nanobot/channels/matrix/webui/locales/zh-CN.json b/nanobot/channels/matrix/webui/locales/zh-CN.json index b62a376cc..b99a726df 100644 --- a/nanobot/channels/matrix/webui/locales/zh-CN.json +++ b/nanobot/channels/matrix/webui/locales/zh-CN.json @@ -32,6 +32,9 @@ "listen": "旁听(被提及时回复)" } }, + "groupPolicyOverrides": { + "label": "按房间的规则例外(JSON)" + }, "allowFrom": { "label": "允许用户" }, diff --git a/nanobot/channels/matrix/webui/locales/zh-TW.json b/nanobot/channels/matrix/webui/locales/zh-TW.json index 76d8d1a41..3b5d33ffa 100644 --- a/nanobot/channels/matrix/webui/locales/zh-TW.json +++ b/nanobot/channels/matrix/webui/locales/zh-TW.json @@ -32,6 +32,9 @@ "listen": "旁聽(被提及時回覆)" } }, + "groupPolicyOverrides": { + "label": "按房間的規則例外(JSON)" + }, "allowFrom": { "label": "允許使用者" },