feat(matrix): add "listen" group policy (observe room, reply on mention) (#6289)

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
Orrin Wittandchengyongru authored and GitHub committed 2026-10-28 23:17:05 +08:00
1 parent 55210eb9f1
commit b1cc89e922
14 files changed
+465 -27

No files matched your search

+3 -1
View File
@@ -388,13 +388,15 @@ nanobot plugins enable matrix
| Option | Description | | Option | Description |
|--------|-------------| |--------|-------------|
| `allowFrom` | User IDs allowed to interact. Empty denies all; use `["*"]` to allow everyone. | | `allowFrom` | User IDs allowed to interact. Empty denies all; use `["*"]` to allow everyone. |
| `groupPolicy` | `open` (default), `mention`, or `allowlist`. | | `groupPolicy` | `open` (default), `mention`, `allowlist`, or `listen`. |
| `groupAllowFrom` | Room allowlist (used when policy is `allowlist`). | | `groupAllowFrom` | Room allowlist (used when policy is `allowlist`). |
| `allowRoomMentions` | Accept `@room` mentions in mention mode. | | `allowRoomMentions` | Accept `@room` mentions in mention mode. |
| `e2eeEnabled` | E2EE support (default `true`). Set `false` for plaintext-only. | | `e2eeEnabled` | E2EE support (default `true`). Set `false` for plaintext-only. |
| `sasVerification` | Complete Element-initiated SAS device verification for allowed users (default `false`). This does not add cross-signing, clear Element's cross-signing trust warning, or let the bot initiate verification. | | `sasVerification` | Complete Element-initiated SAS device verification for allowed users (default `false`). This does not add cross-signing, clear Element's cross-signing trust warning, or let the bot initiate verification. |
| `maxMediaBytes` | Max attachment size (default `20MB`). Set `0` to block all media. | | `maxMediaBytes` | Max attachment size (default `20MB`). Set `0` to block all media. |
In `listen` mode the bot reads every message from allowed senders in the room but replies only when mentioned (same mention semantics as `mention`, including `allowRoomMentions`). Unheard messages are kept in a bounded per-room buffer and attached as context to the next mention-triggered reply, so the answer reflects the conversation since its last response. The buffer clears once used, and nothing is ever replied to unheard messages. The buffer is in-memory only — if the bot restarts it starts empty (the bot does not announce the gap). When the buffer cap evicts older messages, the context block notes how many were dropped.
+3 -1
View File
@@ -5,6 +5,8 @@ from nanobot.channels.contracts import ChannelSetupSpec
from nanobot.channels.matrix.validation import validate from nanobot.channels.matrix.validation import validate
from nanobot.channels.plugin import ChannelPlugin from nanobot.channels.plugin import ChannelPlugin
MATRIX_GROUP_POLICIES = GROUP_POLICIES | {"listen"}
SETUP_SPEC = ChannelSetupSpec( SETUP_SPEC = ChannelSetupSpec(
fields={ fields={
"homeserver": field(default="https://matrix.org"), "homeserver": field(default="https://matrix.org"),
@@ -12,7 +14,7 @@ SETUP_SPEC = ChannelSetupSpec(
"password": field("secret"), "password": field("secret"),
"accessToken": field("secret"), "accessToken": field("secret"),
"deviceId": field(), "deviceId": field(),
"groupPolicy": field("enum", choices=GROUP_POLICIES, default="open"), "groupPolicy": field("enum", choices=MATRIX_GROUP_POLICIES, default="open"),
"allowFrom": field("list"), "allowFrom": field("list"),
"e2eeEnabled": field("bool", default=False), "e2eeEnabled": field("bool", default=False),
"sasVerification": field("bool", default=False), "sasVerification": field("bool", default=False),
+114 -14
View File
@@ -9,6 +9,7 @@ import mimetypes
import re import re
import sys import sys
import time import time
from collections import deque
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
@@ -17,6 +18,7 @@ from urllib.parse import quote, unquote, urlparse
from pydantic import Field from pydantic import Field
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, RuntimeContextBlock
from nanobot.security.workspace_policy import is_path_within from nanobot.security.workspace_policy import is_path_within
try: try:
@@ -63,6 +65,8 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel from nanobot.channels.base import BaseChannel
from nanobot.command.builtin import BUILTIN_COMMAND_SPECS
from nanobot.command.router import normalize_command_text
from nanobot.config.network import NetworkConfig from nanobot.config.network import NetworkConfig
from nanobot.config.paths import get_data_dir, get_media_dir from nanobot.config.paths import get_data_dir, get_media_dir
from nanobot.config_base import Base from nanobot.config_base import Base
@@ -218,6 +222,14 @@ class _SasVerificationRequest:
device_id: str device_id: str
timestamp_ms: int timestamp_ms: int
# Listen-mode transcript bounds: hard caps on the per-room buffer of unheard
# messages (RuntimeContextBlock content must be bounded and delimited).
_LISTEN_BUFFER_MAX_MESSAGES = 30
_LISTEN_BUFFER_MAX_CHARS = 6000
_LISTEN_LINE_MAX_CHARS = 500
def _render_markdown_html(text: str) -> str | None: def _render_markdown_html(text: str) -> str | None:
"""Render markdown to sanitized HTML; returns None for plain text.""" """Render markdown to sanitized HTML; returns None for plain text."""
try: try:
@@ -285,6 +297,9 @@ def _matrix_stream_key(chat_id: str, stream_id: str | None) -> str:
return chat_id if stream_id is None else f"{chat_id}\0{stream_id}" return chat_id if stream_id is None else f"{chat_id}\0{stream_id}"
MatrixGroupPolicy = Literal["open", "mention", "allowlist", "listen"]
class MatrixConfig(Base): class MatrixConfig(Base):
"""Matrix (Element) channel configuration.""" """Matrix (Element) channel configuration."""
@@ -300,7 +315,7 @@ class MatrixConfig(Base):
max_media_bytes: int = 20 * 1024 * 1024 max_media_bytes: int = 20 * 1024 * 1024
max_concurrent_media_downloads: int = 2 max_concurrent_media_downloads: int = 2
allow_from: list[str] = Field(default_factory=list) allow_from: list[str] = Field(default_factory=list)
group_policy: Literal["open", "mention", "allowlist"] = "open" group_policy: MatrixGroupPolicy = "open"
group_allow_from: list[str] = Field(default_factory=list) group_allow_from: list[str] = Field(default_factory=list)
allow_room_mentions: bool = False allow_room_mentions: bool = False
streaming: bool = False streaming: bool = False
@@ -346,6 +361,8 @@ class MatrixChannel(BaseChannel):
self._stream_bufs: dict[str, _StreamBuf] = {} self._stream_bufs: dict[str, _StreamBuf] = {}
self._sas_verification_requests: dict[str, _SasVerificationRequest] = {} self._sas_verification_requests: dict[str, _SasVerificationRequest] = {}
self._started_at_ms: int = 0 self._started_at_ms: int = 0
self._listen_buffers: dict[str, deque[str]] = {}
self._listen_dropped: dict[str, int] = {}
self._media_download_semaphore = asyncio.Semaphore( self._media_download_semaphore = asyncio.Semaphore(
max(1, int(self.config.max_concurrent_media_downloads)) max(1, int(self.config.max_concurrent_media_downloads))
) )
@@ -1142,6 +1159,63 @@ class MatrixChannel(BaseChannel):
ts = getattr(event, "server_timestamp", None) ts = getattr(event, "server_timestamp", None)
return isinstance(ts, int) and ts < self._started_at_ms return isinstance(ts, int) and ts < self._started_at_ms
def _buffer_listen_message(self, room_id: str, sender: str, content: str) -> None:
"""Record an unanswered room message for listen-mode context."""
text = " ".join(str(content).split())[:_LISTEN_LINE_MAX_CHARS]
line = f"{sender}: {text}" if text else f"{sender}: [attachment]"
buffer = self._listen_buffers.setdefault(room_id, deque())
buffer.append(line)
total = sum(len(entry) for entry in buffer)
dropped = self._listen_dropped.get(room_id, 0)
while buffer and (
len(buffer) > _LISTEN_BUFFER_MAX_MESSAGES or total > _LISTEN_BUFFER_MAX_CHARS
):
expired = buffer.popleft()
total -= len(expired)
dropped += 1
if dropped:
self._listen_dropped[room_id] = dropped
def _listen_context(self, room_id: str, content: str) -> list[RuntimeContextBlock] | None:
"""Read pending discussion for agent input, leaving control commands untouched."""
buffer = self._listen_buffers.get(room_id)
if not buffer:
return None
normalized = normalize_command_text(content)
parts = normalized.split(maxsplit=1)
command = next(
(spec for spec in BUILTIN_COMMAND_SPECS if parts and spec.command == parts[0].lower()),
None,
)
if command is not None and not (
command.lifecycle == "agent_turn"
or (
command.lifecycle == "agent_turn_with_args"
and normalized.lower().startswith(f"{command.command} ")
and bool(normalized[len(command.command):].strip())
)
):
return None
dropped = self._listen_dropped.get(room_id, 0)
notice = f"[{dropped} earlier messages not shown]\n" if dropped else ""
return [
RuntimeContextBlock(
source="matrix_room_transcript",
content=(
"Recent messages in this room not addressed to the bot "
"(context; do not respond to these):\n" + notice + "\n".join(buffer)
),
),
]
def _consume_listen_context(
self, room_id: str, content: str, context: list[RuntimeContextBlock] | None,
) -> None:
"""Clear handed-off discussion or an explicit room-session reset."""
if context or normalize_command_text(content).lower() == "/new":
self._listen_buffers.pop(room_id, None)
self._listen_dropped.pop(room_id, None)
def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool: def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool:
"""Apply sender and room policy checks.""" """Apply sender and room policy checks."""
if not self.is_allowed(event.sender): if not self.is_allowed(event.sender):
@@ -1153,7 +1227,7 @@ class MatrixChannel(BaseChannel):
return True return True
if policy == "allowlist": if policy == "allowlist":
return room.room_id in (self.config.group_allow_from or []) return room.room_id in (self.config.group_allow_from or [])
if policy == "mention": if policy == "mention" or policy == "listen":
return self._is_bot_mentioned(event) return self._is_bot_mentioned(event)
return False return False
@@ -1412,30 +1486,50 @@ class MatrixChannel(BaseChannel):
return meta return meta
async def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None: async def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None:
if ( if event.sender == self.config.user_id or self._is_pre_startup_event(event):
event.sender == self.config.user_id return
or self._is_pre_startup_event(event) listen_mode = not self._is_direct_room(room) and self.config.group_policy == "listen"
or not self._should_process_message(room, event) 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)
return
if not self._should_process_message(room, event):
return return
await self._start_typing_keepalive(room.room_id) await self._start_typing_keepalive(room.room_id)
try: try:
metadata = self._base_metadata(room, event)
listen_context = self._listen_context(room.room_id, event.body) if listen_mode else None
if listen_context:
metadata[RUNTIME_CONTEXT_INPUT_META] = listen_context
await self._handle_message( await self._handle_message(
sender_id=event.sender, chat_id=room.room_id, sender_id=event.sender, chat_id=room.room_id,
content=event.body, metadata=self._base_metadata(room, event), content=event.body, metadata=metadata,
session_key=self._thread_session_key(room.room_id, event), session_key=self._thread_session_key(room.room_id, event),
is_dm=self._is_direct_room(room), is_dm=self._is_direct_room(room),
) )
if listen_mode:
self._consume_listen_context(room.room_id, event.body, listen_context)
except Exception: except Exception:
await self._stop_typing_keepalive(room.room_id, clear_typing=True) await self._stop_typing_keepalive(room.room_id, clear_typing=True)
raise raise
async def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None: async def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None:
if ( if event.sender == self.config.user_id or self._is_pre_startup_event(event):
event.sender == self.config.user_id return
or self._is_pre_startup_event(event) listen_mode = not self._is_direct_room(room) and self.config.group_policy == "listen"
or not self._should_process_message(room, event) if listen_mode and not self._is_bot_mentioned(event):
): if self.is_allowed(event.sender):
media_body = getattr(event, "body", None)
media_note = (
" ".join(media_body.split())
if isinstance(media_body, str) and media_body.strip()
else ""
)
self._buffer_listen_message(
room.room_id, event.sender, media_note or "[attachment]"
)
return
if not self._should_process_message(room, event):
return return
attachment, marker = await self._fetch_media_attachment(event) attachment, marker = await self._fetch_media_attachment(event)
parts: list[str] = [] parts: list[str] = []
@@ -1451,20 +1545,26 @@ class MatrixChannel(BaseChannel):
elif marker: elif marker:
parts.append(marker) parts.append(marker)
content = "\n".join(parts)
await self._start_typing_keepalive(room.room_id) await self._start_typing_keepalive(room.room_id)
try: try:
meta = self._base_metadata(room, event) meta = self._base_metadata(room, event)
meta["attachments"] = [] meta["attachments"] = []
if attachment: if attachment:
meta["attachments"] = [attachment] meta["attachments"] = [attachment]
listen_context = self._listen_context(room.room_id, content) if listen_mode else None
if listen_context:
meta[RUNTIME_CONTEXT_INPUT_META] = listen_context
await self._handle_message( await self._handle_message(
sender_id=event.sender, chat_id=room.room_id, sender_id=event.sender, chat_id=room.room_id,
content="\n".join(parts), content=content,
media=[attachment["path"]] if attachment else [], media=[attachment["path"]] if attachment else [],
metadata=meta, metadata=meta,
session_key=self._thread_session_key(room.room_id, event), session_key=self._thread_session_key(room.room_id, event),
is_dm=self._is_direct_room(room), is_dm=self._is_direct_room(room),
) )
if listen_mode:
self._consume_listen_context(room.room_id, content, listen_context)
except Exception: except Exception:
await self._stop_typing_keepalive(room.room_id, clear_typing=True) await self._stop_typing_keepalive(room.room_id, clear_typing=True)
raise raise
@@ -4,7 +4,7 @@ import asyncio
import sys import sys
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import MagicMock from unittest.mock import AsyncMock, MagicMock
from urllib.parse import unquote from urllib.parse import unquote
import pytest import pytest
@@ -13,6 +13,7 @@ pytest.importorskip("nio")
pytest.importorskip("nh3") pytest.importorskip("nh3")
pytest.importorskip("mistune") pytest.importorskip("mistune")
from nio import JoinResponse, RoomSendResponse, SyncError from nio import JoinResponse, RoomSendResponse, SyncError
from pydantic import ValidationError
import nanobot.channels.matrix.runtime as matrix_module import nanobot.channels.matrix.runtime as matrix_module
from nanobot.bus.events import OutboundMessage from nanobot.bus.events import OutboundMessage
@@ -26,6 +27,7 @@ from nanobot.channels.matrix.runtime import (
_build_matrix_text_content, _build_matrix_text_content,
) )
from nanobot.config.network import NetworkConfig from nanobot.config.network import NetworkConfig
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, RuntimeContextBlock
_ROOM_SEND_UNSET = object() _ROOM_SEND_UNSET = object()
@@ -2868,3 +2870,325 @@ async def test_fetch_media_maps_streaming_cap_to_too_large(monkeypatch, tmp_path
assert attachment is None assert attachment is None
assert marker == "[attachment: payload.bin - too large]" assert marker == "[attachment: payload.bin - too large]"
assert client.room_send_calls == [] assert client.room_send_calls == []
def test_listen_policy_config_value_accepted_and_unknown_rejected() -> None:
assert MatrixConfig(group_policy="listen").group_policy == "listen"
assert MatrixConfig.model_validate({"groupPolicy": "listen"}).group_policy == "listen"
with pytest.raises(ValidationError):
MatrixConfig(group_policy="observe")
def test_listen_buffer_bounds_and_truncation() -> None:
channel = MatrixChannel(_make_config(), MessageBus())
for index in range(40):
channel._buffer_listen_message("!r:matrix.org", f"@u{index}:matrix.org", f"m{index}")
buffer = channel._listen_buffers["!r:matrix.org"]
assert len(buffer) == matrix_module._LISTEN_BUFFER_MAX_MESSAGES
assert buffer[0] == "@u10:matrix.org: m10"
channel._buffer_listen_message("!fresh:matrix.org", "@u0:matrix.org", "x" * 2000)
assert channel._listen_buffers["!fresh:matrix.org"][0] == f"@u0:matrix.org: {'x' * 500}"
for index in range(20):
channel._buffer_listen_message("!cap:matrix.org", f"@u{index}:matrix.org", "y" * 400)
capped = channel._listen_buffers["!cap:matrix.org"]
assert len(capped) < 20
assert sum(len(entry) for entry in capped) <= matrix_module._LISTEN_BUFFER_MAX_CHARS
@pytest.mark.asyncio
async def test_listen_context_block_notes_dropped_lines() -> None:
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
for index in range(34):
channel._buffer_listen_message("!r:matrix.org", f"@u{index}:matrix.org", f"m{index}")
room = SimpleNamespace(room_id="!r:matrix.org", member_count=3)
await channel._on_message(room, _listen_event("what did we decide?", mentioned=True))
question = await bus.consume_inbound()
blocks = question.metadata[RUNTIME_CONTEXT_INPUT_META]
assert len(blocks) == 1
assert "[4 earlier messages not shown]" in blocks[0].content
assert "@u0:matrix.org: m0" not in blocks[0].content
assert "@u4:matrix.org: m4" in blocks[0].content
await channel._on_message(room, _listen_event("anything else?", mentioned=True))
assert RUNTIME_CONTEXT_INPUT_META not in (await bus.consume_inbound()).metadata
@pytest.mark.asyncio
async def test_on_message_listen_policy_buffers_then_serves_context_on_mention() -> None:
channel = MatrixChannel(_make_config(group_policy="listen"), MessageBus())
client = _FakeAsyncClient("", "", "", None)
channel.client = client
calls: list[dict] = []
async def _fake_handle_message(**kwargs) -> None:
calls.append(kwargs)
channel._handle_message = _fake_handle_message # type: ignore[method-assign]
room = SimpleNamespace(room_id="!room:matrix.org", display_name="Room", member_count=3)
plain = SimpleNamespace(
sender="@alice:matrix.org",
body="we were discussing the picnic",
source={"content": {}},
)
await channel._on_message(room, plain)
assert calls == []
assert client.typing_calls == []
assert channel._listen_buffers["!room:matrix.org"][-1] == (
"@alice:matrix.org: we were discussing the picnic"
)
mention = SimpleNamespace(
sender="@bob:matrix.org",
body="what did we decide?",
source={"content": {"m.mentions": {"user_ids": ["@bot:matrix.org"]}}},
)
await channel._on_message(room, mention)
assert len(calls) == 1
blocks = calls[0]["metadata"].get(RUNTIME_CONTEXT_INPUT_META)
assert blocks is not None and len(blocks) == 1
assert isinstance(blocks[0], RuntimeContextBlock)
assert blocks[0].source == "matrix_room_transcript"
assert "we were discussing the picnic" in blocks[0].content
assert "!room:matrix.org" not in channel._listen_buffers
assert client.typing_calls == [("!room:matrix.org", True, TYPING_NOTICE_TIMEOUT_MS)]
await channel._on_message(room, mention)
assert len(calls) == 2
assert RUNTIME_CONTEXT_INPUT_META not in calls[1]["metadata"]
@pytest.mark.asyncio
async def test_on_message_listen_policy_ignores_denied_sender() -> None:
channel = MatrixChannel(
_make_config(group_policy="listen", allow_from=[]), MessageBus()
)
client = _FakeAsyncClient("", "", "", None)
channel.client = client
calls: list[dict] = []
async def _fake_handle_message(**kwargs) -> None:
calls.append(kwargs)
channel._handle_message = _fake_handle_message # type: ignore[method-assign]
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
event = SimpleNamespace(sender="@stranger:matrix.org", body="hello", source={"content": {}})
await channel._on_message(room, event)
assert calls == []
assert channel._listen_buffers == {}
@pytest.mark.asyncio
async def test_on_message_listen_policy_leaves_direct_rooms_untouched() -> None:
channel = MatrixChannel(_make_config(group_policy="listen"), MessageBus())
client = _FakeAsyncClient("", "", "", None)
channel.client = client
calls: list[dict] = []
async def _fake_handle_message(**kwargs) -> None:
calls.append(kwargs)
channel._handle_message = _fake_handle_message # type: ignore[method-assign]
room = SimpleNamespace(room_id="!dm:matrix.org", display_name="Alice & bot", member_count=2)
event = SimpleNamespace(sender="@alice:matrix.org", body="hi", source={"content": {}})
await channel._on_message(room, event)
assert len(calls) == 1
assert RUNTIME_CONTEXT_INPUT_META not in calls[0]["metadata"]
assert channel._listen_buffers == {}
@pytest.mark.asyncio
async def test_on_message_open_policy_does_not_buffer() -> None:
channel = MatrixChannel(_make_config(group_policy="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="!room:matrix.org", member_count=3)
event = SimpleNamespace(sender="@alice:matrix.org", body="hi", source={"content": {}})
await channel._on_message(room, event)
assert handled == ["@alice:matrix.org"]
assert channel._listen_buffers == {}
@pytest.mark.asyncio
async def test_on_media_message_listen_policy_buffers_caption() -> None:
channel = MatrixChannel(_make_config(group_policy="listen"), MessageBus())
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
event = SimpleNamespace(
sender="@alice:matrix.org",
body="venue floor plan",
event_id="$m1",
url="mxc://example.org/media",
source={"content": {"msgtype": "m.image", "info": {"size": 8}}},
)
await channel._on_media_message(room, event)
assert channel._listen_buffers["!room:matrix.org"][-1] == (
"@alice:matrix.org: venue floor plan"
)
def _listen_event(body: str, *, mentioned: bool = False, msgtype: str = "m.text"):
content: dict[str, object] = {"msgtype": msgtype, "body": body}
if mentioned:
content["m.mentions"] = {"user_ids": ["@bot:matrix.org"]}
if msgtype != "m.text":
content.update(url="mxc://example.org/payload", info={"size": 8})
event = matrix_module.RoomMessage.parse_event({
"type": "m.room.message",
"sender": "@alice:matrix.org",
"event_id": "$listen-review",
"origin_server_ts": 2_000_000_000_000,
"content": content,
})
assert isinstance(event, matrix_module.RoomMessage)
return event
@pytest.mark.parametrize("command", ["/status", "/model other", "/help extra", "/goal"])
@pytest.mark.asyncio
async def test_listen_control_command_preserves_context_for_next_question(command: str) -> None:
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
await channel._on_message(room, _listen_event("the picnic is on Sunday"))
await channel._on_message(room, _listen_event(command, mentioned=True))
command_input = await bus.consume_inbound()
assert command_input.content == command
assert RUNTIME_CONTEXT_INPUT_META not in command_input.metadata
await channel._on_message(room, _listen_event("what did we decide?", mentioned=True))
question = await bus.consume_inbound()
blocks = question.metadata[RUNTIME_CONTEXT_INPUT_META]
assert "the picnic is on Sunday" in blocks[0].content
assert "!room:matrix.org" not in channel._listen_buffers
@pytest.mark.asyncio
async def test_listen_help_round_trip_does_not_consume_discussion(monkeypatch, tmp_path) -> None:
from nanobot.agent.loop import AgentLoop
from nanobot.providers.base import LLMProvider
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
provider = MagicMock(spec=LLMProvider)
provider.get_default_model.return_value = "test-model"
provider.generation = SimpleNamespace(max_tokens=4096, temperature=0.1, reasoning_effort=None)
provider.estimate_prompt_tokens = MagicMock(return_value=(1000, "test"))
provider.chat_stream_with_retry = AsyncMock()
provider.aclose = AsyncMock()
loop = AgentLoop(
bus=bus, provider=provider, workspace=tmp_path / "workspace",
model="test-model", context_window_tokens=128000, session_ttl_minutes=0,
)
try:
await channel._on_message(room, _listen_event("bring lunch to the picnic"))
await channel._on_message(room, _listen_event("/help", mentioned=True))
command_input = await bus.consume_inbound()
response = await loop._process_message(command_input)
assert response is not None and "/help" in response.content
provider.chat_stream_with_retry.assert_not_awaited()
session = await loop.sessions.state.get(command_input.session_key)
assert session.get_history() == []
await channel._on_message(room, _listen_event("what should I bring?", mentioned=True))
question = await bus.consume_inbound()
blocks = question.metadata[RUNTIME_CONTEXT_INPUT_META]
assert "bring lunch to the picnic" in blocks[0].content
finally:
await loop.aclose()
@pytest.mark.parametrize("content", ["/goal prepare a picnic plan", "/tmp/notes.md"])
@pytest.mark.asyncio
async def test_listen_agent_input_keeps_context_for_goal_and_slash_prefixed_text(content: str) -> None:
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
await channel._on_message(room, _listen_event("the picnic is on Sunday"))
await channel._on_message(room, _listen_event(content, mentioned=True))
question = await bus.consume_inbound()
assert question.content == content
assert "the picnic is on Sunday" in question.metadata[RUNTIME_CONTEXT_INPUT_META][0].content
assert "!room:matrix.org" not in channel._listen_buffers
@pytest.mark.asyncio
async def test_listen_new_command_clears_discussion_without_attaching_it() -> None:
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
await channel._on_message(room, _listen_event("old discussion"))
await channel._on_message(room, _listen_event("/new", mentioned=True))
command_input = await bus.consume_inbound()
assert RUNTIME_CONTEXT_INPUT_META not in command_input.metadata
await channel._on_message(room, _listen_event("new question", mentioned=True))
question = await bus.consume_inbound()
assert RUNTIME_CONTEXT_INPUT_META not in question.metadata
@pytest.mark.asyncio
async def test_listen_media_directory_error_preserves_context_for_next_question(monkeypatch, tmp_path) -> None:
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
media_dir = tmp_path / "media"
media_dir.mkdir()
(media_dir / "matrix").write_text("blocks the media directory", encoding="utf-8")
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
channel.client = _FakeAsyncClient("", "", "", None)
monkeypatch.setattr(channel, "_download_media_bytes", AsyncMock(return_value=b"12345678"))
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
for index in range(34):
await channel._on_message(room, _listen_event(f"discussion {index}"))
with pytest.raises(OSError):
await channel._on_media_message(room, _listen_event("picnic.png", mentioned=True, msgtype="m.image"))
assert bus.inbound_size == 0
await channel._on_message(room, _listen_event("what did we decide?", mentioned=True))
question = await bus.consume_inbound()
block = question.metadata[RUNTIME_CONTEXT_INPUT_META][0]
assert "[4 earlier messages not shown]" in block.content
assert "@alice:matrix.org: discussion 4\n" in block.content
assert "@alice:matrix.org: discussion 33" in block.content
assert "!room:matrix.org" not in channel._listen_buffers
@pytest.mark.asyncio
async def test_listen_media_control_command_preserves_discussion(monkeypatch) -> None:
bus = MessageBus()
channel = MatrixChannel(_make_config(group_policy="listen"), bus)
marker = "[attachment: picture.png - download failed]"
monkeypatch.setattr(channel, "_fetch_media_attachment", AsyncMock(return_value=(None, marker)))
room = SimpleNamespace(room_id="!room:matrix.org", member_count=3)
await channel._on_message(room, _listen_event("the picnic is on Sunday"))
await channel._on_media_message(room, _listen_event("/help", mentioned=True, msgtype="m.image"))
command_input = await bus.consume_inbound()
assert command_input.content == f"/help\n{marker}"
assert RUNTIME_CONTEXT_INPUT_META not in command_input.metadata
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
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "Mentions only", "mention": "Mentions only",
"open": "All messages", "open": "All messages",
"allowlist": "Allowlist" "allowlist": "Allowlist",
"listen": "Listen (reply on mention)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "Solo menciones", "mention": "Solo menciones",
"open": "Todos los mensajes", "open": "Todos los mensajes",
"allowlist": "Lista de permitidos" "allowlist": "Lista de permitidos",
"listen": "Escuchar (responder al mencionar)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "Mentions uniquement", "mention": "Mentions uniquement",
"open": "Tous les messages", "open": "Tous les messages",
"allowlist": "Liste d’autorisation" "allowlist": "Liste d’autorisation",
"listen": "Écouter (réponse sur mention)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "Hanya mention", "mention": "Hanya mention",
"open": "Semua pesan", "open": "Semua pesan",
"allowlist": "Daftar izin" "allowlist": "Daftar izin",
"listen": "Dengar (balas saat disebut)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "メンションのみ", "mention": "メンションのみ",
"open": "全メッセージ", "open": "全メッセージ",
"allowlist": "許可リスト" "allowlist": "許可リスト",
"listen": "リッスン(メンションで返信)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "멘션만", "mention": "멘션만",
"open": "모든 메시지", "open": "모든 메시지",
"allowlist": "허용 목록" "allowlist": "허용 목록",
"listen": "경청(멘션 시 응답)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "Somente menções", "mention": "Somente menções",
"open": "Todas as mensagens", "open": "Todas as mensagens",
"allowlist": "Lista de permissão" "allowlist": "Lista de permissão",
"listen": "Ouvir (responder ao mencionar)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "Chỉ khi được nhắc", "mention": "Chỉ khi được nhắc",
"open": "Mọi tin nhắn", "open": "Mọi tin nhắn",
"allowlist": "Danh sách cho phép" "allowlist": "Danh sách cho phép",
"listen": "Lắng nghe (trả lời khi được nhắc)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "提及回复", "mention": "提及回复",
"open": "全部消息", "open": "全部消息",
"allowlist": "白名单" "allowlist": "白名单",
"listen": "旁听(被提及时回复)"
} }
}, },
"allowFrom": { "allowFrom": {
@@ -28,7 +28,8 @@
"choices": { "choices": {
"mention": "提及回覆", "mention": "提及回覆",
"open": "全部訊息", "open": "全部訊息",
"allowlist": "允許清單" "allowlist": "允許清單",
"listen": "旁聽(被提及時回覆)"
} }
}, },
"allowFrom": { "allowFrom": {