Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(matrix): add "listen" group policy (observe room, reply on mention) (#6289)
Orrin Wittb1cc89e9220f
diff --git a/docs/chat-apps.md b/docs/chat-apps.mdindex 71e8a1a30..f90f3934c 100644--- a/docs/chat-apps.md+++ b/docs/chat-apps.md@@ -388,13 +388,15 @@ nanobot plugins enable matrix| Option | Description ||--------|-------------|| `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`). || `allowRoomMentions` | Accept `@room` mentions in mention mode. || `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. || `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.+diff --git a/nanobot/channels/matrix/manifest.py b/nanobot/channels/matrix/manifest.pyindex 45546866e..902e1b883 100644--- a/nanobot/channels/matrix/manifest.py+++ b/nanobot/channels/matrix/manifest.py@@ -5,6 +5,8 @@ from nanobot.channels.contracts import ChannelSetupSpecfrom nanobot.channels.matrix.validation import validatefrom nanobot.channels.plugin import ChannelPlugin+MATRIX_GROUP_POLICIES = GROUP_POLICIES | {"listen"}+SETUP_SPEC = ChannelSetupSpec(fields={"homeserver": field(default="https://matrix.org"),@@ -12,7 +14,7 @@ SETUP_SPEC = ChannelSetupSpec("password": field("secret"),"accessToken": field("secret"),"deviceId": field(),- "groupPolicy": field("enum", choices=GROUP_POLICIES, default="open"),+ "groupPolicy": field("enum", choices=MATRIX_GROUP_POLICIES, default="open"),"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.pyindex d509f9f98..730d32e59 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -9,6 +9,7 @@ import mimetypesimport reimport sysimport time+from collections import dequefrom contextlib import suppressfrom dataclasses import dataclassfrom pathlib import Path@@ -17,6 +18,7 @@ from urllib.parse import quote, unquote, urlparsefrom pydantic import Field+from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, RuntimeContextBlockfrom nanobot.security.workspace_policy import is_path_withintry:@@ -63,6 +65,8 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel+from nanobot.command.builtin import BUILTIN_COMMAND_SPECS+from nanobot.command.router import normalize_command_textfrom nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_data_dir, get_media_dirfrom nanobot.config_base import Base@@ -218,6 +222,14 @@ class _SasVerificationRequest:device_id: strtimestamp_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:"""Render markdown to sanitized HTML; returns None for plain text."""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}"+MatrixGroupPolicy = Literal["open", "mention", "allowlist", "listen"]++class MatrixConfig(Base):"""Matrix (Element) channel configuration."""@@ -300,7 +315,7 @@ class MatrixConfig(Base):max_media_bytes: int = 20 * 1024 * 1024max_concurrent_media_downloads: int = 2allow_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)allow_room_mentions: bool = Falsestreaming: bool = False@@ -346,6 +361,8 @@ class MatrixChannel(BaseChannel):self._stream_bufs: dict[str, _StreamBuf] = {}self._sas_verification_requests: dict[str, _SasVerificationRequest] = {}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(max(1, int(self.config.max_concurrent_media_downloads)))@@ -1142,6 +1159,63 @@ class MatrixChannel(BaseChannel):ts = getattr(event, "server_timestamp", None)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:"""Apply sender and room policy checks."""if not self.is_allowed(event.sender):@@ -1153,7 +1227,7 @@ class MatrixChannel(BaseChannel):return Trueif policy == "allowlist":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 False@@ -1412,30 +1486,50 @@ class MatrixChannel(BaseChannel):return metaasync def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None:- if (- event.sender == self.config.user_id- or self._is_pre_startup_event(event)- or not self._should_process_message(room, event)- ):+ 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"+ 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):returnawait self._start_typing_keepalive(room.room_id)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_contextawait self._handle_message(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),is_dm=self._is_direct_room(room),)+ if listen_mode:+ self._consume_listen_context(room.room_id, event.body, listen_context)except Exception:await self._stop_typing_keepalive(room.room_id, clear_typing=True)raiseasync def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None:- if (- event.sender == self.config.user_id- or self._is_pre_startup_event(event)- or not self._should_process_message(room, event)- ):+ 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"+ 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):returnattachment, marker = await self._fetch_media_attachment(event)parts: list[str] = []@@ -1451,20 +1545,26 @@ class MatrixChannel(BaseChannel):elif marker:parts.append(marker)+ content = "\n".join(parts)await self._start_typing_keepalive(room.room_id)try:meta = self._base_metadata(room, event)meta["attachments"] = []if 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_contextawait self._handle_message(sender_id=event.sender, chat_id=room.room_id,- content="\n".join(parts),+ content=content,media=[attachment["path"]] if attachment else [],metadata=meta,session_key=self._thread_session_key(room.room_id, event),is_dm=self._is_direct_room(room),)+ if listen_mode:+ self._consume_listen_context(room.room_id, content, listen_context)except Exception:await self._stop_typing_keepalive(room.room_id, clear_typing=True)raisediff --git a/nanobot/channels/matrix/tests/test_matrix_channel.py b/nanobot/channels/matrix/tests/test_matrix_channel.pyindex c105d6f63..72080ec7f 100644--- a/nanobot/channels/matrix/tests/test_matrix_channel.py+++ b/nanobot/channels/matrix/tests/test_matrix_channel.py@@ -4,7 +4,7 @@ import asyncioimport sysfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockfrom urllib.parse import unquoteimport pytest@@ -13,6 +13,7 @@ pytest.importorskip("nio")pytest.importorskip("nh3")pytest.importorskip("mistune")from nio import JoinResponse, RoomSendResponse, SyncError+from pydantic import ValidationErrorimport nanobot.channels.matrix.runtime as matrix_modulefrom nanobot.bus.events import OutboundMessage@@ -26,6 +27,7 @@ from nanobot.channels.matrix.runtime import (_build_matrix_text_content,)from nanobot.config.network import NetworkConfig+from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, RuntimeContextBlock_ROOM_SEND_UNSET = object()@@ -2868,3 +2870,325 @@ async def test_fetch_media_maps_streaming_cap_to_too_large(monkeypatch, tmp_pathassert attachment is Noneassert marker == "[attachment: payload.bin - too large]"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+++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+++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"]+++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 == {}+++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 == {}+++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 == {}+++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++[email protected]("command", ["/status", "/model other", "/help extra", "/goal"])+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+++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()++[email protected]("content", ["/goal prepare a picnic plan", "/tmp/notes.md"])+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+++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+++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+++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].contentdiff --git a/nanobot/channels/matrix/webui/locales/en.json b/nanobot/channels/matrix/webui/locales/en.jsonindex 7f0c79dd1..629953e9d 100644--- a/nanobot/channels/matrix/webui/locales/en.json+++ b/nanobot/channels/matrix/webui/locales/en.json@@ -28,7 +28,8 @@"choices": {"mention": "Mentions only","open": "All messages",- "allowlist": "Allowlist"+ "allowlist": "Allowlist",+ "listen": "Listen (reply on mention)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/es.json b/nanobot/channels/matrix/webui/locales/es.jsonindex 9551b70ef..e9d6695f6 100644--- a/nanobot/channels/matrix/webui/locales/es.json+++ b/nanobot/channels/matrix/webui/locales/es.json@@ -28,7 +28,8 @@"choices": {"mention": "Solo menciones","open": "Todos los mensajes",- "allowlist": "Lista de permitidos"+ "allowlist": "Lista de permitidos",+ "listen": "Escuchar (responder al mencionar)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/fr.json b/nanobot/channels/matrix/webui/locales/fr.jsonindex 82c60ce48..231ad3234 100644--- a/nanobot/channels/matrix/webui/locales/fr.json+++ b/nanobot/channels/matrix/webui/locales/fr.json@@ -28,7 +28,8 @@"choices": {"mention": "Mentions uniquement","open": "Tous les messages",- "allowlist": "Liste d’autorisation"+ "allowlist": "Liste d’autorisation",+ "listen": "Écouter (réponse sur mention)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/id.json b/nanobot/channels/matrix/webui/locales/id.jsonindex c409eb5da..a5f00ee4e 100644--- a/nanobot/channels/matrix/webui/locales/id.json+++ b/nanobot/channels/matrix/webui/locales/id.json@@ -28,7 +28,8 @@"choices": {"mention": "Hanya mention","open": "Semua pesan",- "allowlist": "Daftar izin"+ "allowlist": "Daftar izin",+ "listen": "Dengar (balas saat disebut)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/ja.json b/nanobot/channels/matrix/webui/locales/ja.jsonindex 665b0056a..94087132e 100644--- a/nanobot/channels/matrix/webui/locales/ja.json+++ b/nanobot/channels/matrix/webui/locales/ja.json@@ -28,7 +28,8 @@"choices": {"mention": "メンションのみ","open": "全メッセージ",- "allowlist": "許可リスト"+ "allowlist": "許可リスト",+ "listen": "リッスン(メンションで返信)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/ko.json b/nanobot/channels/matrix/webui/locales/ko.jsonindex c72483054..f49752d02 100644--- a/nanobot/channels/matrix/webui/locales/ko.json+++ b/nanobot/channels/matrix/webui/locales/ko.json@@ -28,7 +28,8 @@"choices": {"mention": "멘션만","open": "모든 메시지",- "allowlist": "허용 목록"+ "allowlist": "허용 목록",+ "listen": "경청(멘션 시 응답)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/pt-BR.json b/nanobot/channels/matrix/webui/locales/pt-BR.jsonindex 841304b13..0bf0a55a5 100644--- a/nanobot/channels/matrix/webui/locales/pt-BR.json+++ b/nanobot/channels/matrix/webui/locales/pt-BR.json@@ -28,7 +28,8 @@"choices": {"mention": "Somente menções","open": "Todas as mensagens",- "allowlist": "Lista de permissão"+ "allowlist": "Lista de permissão",+ "listen": "Ouvir (responder ao mencionar)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/vi.json b/nanobot/channels/matrix/webui/locales/vi.jsonindex 715f4a623..d4b07854a 100644--- a/nanobot/channels/matrix/webui/locales/vi.json+++ b/nanobot/channels/matrix/webui/locales/vi.json@@ -28,7 +28,8 @@"choices": {"mention": "Chỉ khi được nhắc","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": {diff --git a/nanobot/channels/matrix/webui/locales/zh-CN.json b/nanobot/channels/matrix/webui/locales/zh-CN.jsonindex 13b601166..b4a7799fa 100644--- a/nanobot/channels/matrix/webui/locales/zh-CN.json+++ b/nanobot/channels/matrix/webui/locales/zh-CN.json@@ -28,7 +28,8 @@"choices": {"mention": "提及回复","open": "全部消息",- "allowlist": "白名单"+ "allowlist": "白名单",+ "listen": "旁听(被提及时回复)"}},"allowFrom": {diff --git a/nanobot/channels/matrix/webui/locales/zh-TW.json b/nanobot/channels/matrix/webui/locales/zh-TW.jsonindex 9ebd4b7dc..0334b56bb 100644--- a/nanobot/channels/matrix/webui/locales/zh-TW.json+++ b/nanobot/channels/matrix/webui/locales/zh-TW.json@@ -28,7 +28,8 @@"choices": {"mention": "提及回覆","open": "全部訊息",- "allowlist": "允許清單"+ "allowlist": "允許清單",+ "listen": "旁聽(被提及時回覆)"}},"allowFrom": {