Skip to content

Your lightweight open-source personal agent.

Merge main into pr-1482

Re-bin515b3588af1b
diff --cc nanobot/agent/tools/message.py
index 35e519a00,35e519a00..0a5242704
--- a/nanobot/agent/tools/message.py
+++ b/nanobot/agent/tools/message.py
@@@ -96,7 -96,7 +96,7 @@@ class MessageTool(Tool)
media=media or [],
metadata={
"message_id": message_id,
-- }
++ },
)
try:
diff --cc nanobot/channels/telegram.py
index 344ed0c03,2c92c2d5f..6c57288d4
--- a/nanobot/channels/telegram.py
+++ b/nanobot/channels/telegram.py
@@@ -130,6 -177,6 +177,7 @@@ class TelegramChannel(BaseChannel)
self._typing_tasks: dict[str, asyncio.Task] = {} # chat_id -> typing loop task
self._media_group_buffers: dict[str, dict] = {}
self._media_group_tasks: dict[str, asyncio.Task] = {}
++ self._message_threads: dict[tuple[str, int], int] = {}
async def start(self) -> None:
"""Start the Telegram bot with long polling."""
@@@ -232,14 -286,10 +287,16 @@@
except ValueError:
logger.error("Invalid chat_id: {}", msg.chat_id)
return
++ reply_to_message_id = msg.metadata.get("message_id")
+ message_thread_id = msg.metadata.get("message_thread_id")
++ if message_thread_id is None and reply_to_message_id is not None:
++ message_thread_id = self._message_threads.get((msg.chat_id, reply_to_message_id))
+ thread_kwargs = {}
+ if message_thread_id is not None:
+ thread_kwargs["message_thread_id"] = message_thread_id
reply_params = None
if self.config.reply_to_message:
-- reply_to_message_id = msg.metadata.get("message_id")
if reply_to_message_id:
reply_params = ReplyParameters(
message_id=reply_to_message_id,
@@@ -275,27 -323,49 +332,65 @@@
# Send text content
if msg.content and msg.content != "[empty message]":
- for chunk in _split_message(msg.content):
- try:
- html = _markdown_to_telegram_html(chunk)
- await self._app.bot.send_message(
- chat_id=chat_id,
- text=html,
- parse_mode="HTML",
- reply_parameters=reply_params,
- **thread_kwargs,
- )
- except Exception as e:
- logger.warning("HTML parse failed, falling back to plain text: {}", e)
- try:
- await self._app.bot.send_message(
- chat_id=chat_id,
- text=chunk,
- reply_parameters=reply_params,
- **thread_kwargs,
- )
- except Exception as e2:
- logger.error("Error sending Telegram message: {}", e2)
+ is_progress = msg.metadata.get("_progress", False)
+
+ for chunk in split_message(msg.content, TELEGRAM_MAX_MESSAGE_LEN):
+ # Final response: simulate streaming via draft, then persist
+ if not is_progress:
- await self._send_with_streaming(chat_id, chunk, reply_params)
++ await self._send_with_streaming(chat_id, chunk, reply_params, thread_kwargs)
+ else:
- await self._send_text(chat_id, chunk, reply_params)
++ await self._send_text(chat_id, chunk, reply_params, thread_kwargs)
+
- async def _send_text(self, chat_id: int, text: str, reply_params=None) -> None:
++ async def _send_text(
++ self,
++ chat_id: int,
++ text: str,
++ reply_params=None,
++ thread_kwargs: dict | None = None,
++ ) -> None:
+ """Send a plain text message with HTML fallback."""
+ try:
+ html = _markdown_to_telegram_html(text)
+ await self._app.bot.send_message(
+ chat_id=chat_id, text=html, parse_mode="HTML",
+ reply_parameters=reply_params,
++ **(thread_kwargs or {}),
+ )
+ except Exception as e:
+ logger.warning("HTML parse failed, falling back to plain text: {}", e)
+ try:
+ await self._app.bot.send_message(
- chat_id=chat_id, text=text, reply_parameters=reply_params,
++ chat_id=chat_id,
++ text=text,
++ reply_parameters=reply_params,
++ **(thread_kwargs or {}),
+ )
+ except Exception as e2:
+ logger.error("Error sending Telegram message: {}", e2)
+
- async def _send_with_streaming(self, chat_id: int, text: str, reply_params=None) -> None:
++ async def _send_with_streaming(
++ self,
++ chat_id: int,
++ text: str,
++ reply_params=None,
++ thread_kwargs: dict | None = None,
++ ) -> None:
+ """Simulate streaming via send_message_draft, then persist with send_message."""
+ draft_id = int(time.time() * 1000) % (2**31)
+ try:
+ step = max(len(text) // 8, 40)
+ for i in range(step, len(text), step):
+ await self._app.bot.send_message_draft(
+ chat_id=chat_id, draft_id=draft_id, text=text[:i],
+ )
+ await asyncio.sleep(0.04)
+ await self._app.bot.send_message_draft(
+ chat_id=chat_id, draft_id=draft_id, text=text,
+ )
+ await asyncio.sleep(0.15)
+ except Exception:
+ pass
- await self._send_text(chat_id, text, reply_params)
++ await self._send_text(chat_id, text, reply_params, thread_kwargs)
async def _on_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /start command."""
@@@ -326,39 -396,14 +421,50 @@@
sid = str(user.id)
return f"{sid}|{user.username}" if user.username else sid
+ @staticmethod
+ def _derive_topic_session_key(message) -> str | None:
+ """Derive topic-scoped session key for non-private Telegram chats."""
+ message_thread_id = getattr(message, "message_thread_id", None)
+ if message.chat.type == "private" or message_thread_id is None:
+ return None
+ return f"telegram:{message.chat_id}:topic:{message_thread_id}"
+
+ @staticmethod
+ def _build_message_metadata(message, user) -> dict:
+ """Build common Telegram inbound metadata payload."""
+ return {
+ "message_id": message.message_id,
+ "user_id": user.id,
+ "username": user.username,
+ "first_name": user.first_name,
+ "is_group": message.chat.type != "private",
+ "message_thread_id": getattr(message, "message_thread_id", None),
+ "is_forum": bool(getattr(message.chat, "is_forum", False)),
+ }
+
++ def _remember_thread_context(self, message) -> None:
++ """Cache topic thread id by chat/message id for follow-up replies."""
++ message_thread_id = getattr(message, "message_thread_id", None)
++ if message_thread_id is None:
++ return
++ key = (str(message.chat_id), message.message_id)
++ self._message_threads[key] = message_thread_id
++ if len(self._message_threads) > 1000:
++ self._message_threads.pop(next(iter(self._message_threads)))
++
async def _forward_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Forward slash commands to the bus for unified handling in AgentLoop."""
if not update.message or not update.effective_user:
return
+ message = update.message
+ user = update.effective_user
++ self._remember_thread_context(message)
await self._handle_message(
- sender_id=self._sender_id(update.effective_user),
- chat_id=str(update.message.chat_id),
- content=update.message.text,
+ sender_id=self._sender_id(user),
+ chat_id=str(message.chat_id),
+ content=message.text,
+ metadata=self._build_message_metadata(message, user),
+ session_key=self._derive_topic_session_key(message),
)
async def _on_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@@ -370,6 -415,6 +476,7 @@@
user = update.effective_user
chat_id = message.chat_id
sender_id = self._sender_id(user)
++ self._remember_thread_context(message)
# Store chat_id for replies
self._chat_ids[sender_id] = chat_id
diff --cc tests/test_message_tool_suppress.py
index 26b8a165e,f5e65c9dd..63b0fd1fa
--- a/tests/test_message_tool_suppress.py
+++ b/tests/test_message_tool_suppress.py
@@@ -86,6 -86,36 +86,35 @@@ class TestMessageToolSuppressLogic
assert result is not None
assert "Hello" in result.content
- @pytest.mark.asyncio
+ async def test_progress_hides_internal_reasoning(self, tmp_path: Path) -> None:
+ loop = _make_loop(tmp_path)
+ tool_call = ToolCallRequest(id="call1", name="read_file", arguments={"path": "foo.txt"})
+ calls = iter([
+ LLMResponse(
+ content="Visible<think>hidden</think>",
+ tool_calls=[tool_call],
+ reasoning_content="secret reasoning",
+ thinking_blocks=[{"signature": "sig", "thought": "secret thought"}],
+ ),
+ LLMResponse(content="Done", tool_calls=[]),
+ ])
+ loop.provider.chat = AsyncMock(side_effect=lambda *a, **kw: next(calls))
+ loop.tools.get_definitions = MagicMock(return_value=[])
+ loop.tools.execute = AsyncMock(return_value="ok")
+
+ progress: list[tuple[str, bool]] = []
+
+ async def on_progress(content: str, *, tool_hint: bool = False) -> None:
+ progress.append((content, tool_hint))
+
+ final_content, _, _ = await loop._run_agent_loop([], on_progress=on_progress)
+
+ assert final_content == "Done"
+ assert progress == [
+ ("Visible", False),
+ ('read_file("foo.txt")', True),
+ ]
+
class TestMessageToolTurnTracking:
diff --cc tests/test_telegram_channel.py
index 000000000,3bacf9692..610054978
mode 000000,100644..100644
--- a/tests/test_telegram_channel.py
+++ b/tests/test_telegram_channel.py
@@@ -1,0 -1,107 +1,162 @@@
+ from types import SimpleNamespace
+
+ import pytest
+
++from nanobot.bus.events import OutboundMessage
+ from nanobot.bus.queue import MessageBus
+ from nanobot.channels.telegram import TelegramChannel
+ from nanobot.config.schema import TelegramConfig
+
+
+ class _FakeHTTPXRequest:
+ instances: list["_FakeHTTPXRequest"] = []
+
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+ self.__class__.instances.append(self)
+
+
+ class _FakeUpdater:
+ def __init__(self, on_start_polling) -> None:
+ self._on_start_polling = on_start_polling
+
+ async def start_polling(self, **kwargs) -> None:
+ self._on_start_polling()
+
+
+ class _FakeBot:
++ def __init__(self) -> None:
++ self.sent_messages: list[dict] = []
++
+ async def get_me(self):
+ return SimpleNamespace(username="nanobot_test")
+
+ async def set_my_commands(self, commands) -> None:
+ self.commands = commands
+
++ async def send_message(self, **kwargs) -> None:
++ self.sent_messages.append(kwargs)
++
+
+ class _FakeApp:
+ def __init__(self, on_start_polling) -> None:
+ self.bot = _FakeBot()
+ self.updater = _FakeUpdater(on_start_polling)
+ self.handlers = []
+ self.error_handlers = []
+
+ def add_error_handler(self, handler) -> None:
+ self.error_handlers.append(handler)
+
+ def add_handler(self, handler) -> None:
+ self.handlers.append(handler)
+
+ async def initialize(self) -> None:
+ pass
+
+ async def start(self) -> None:
+ pass
+
+
+ class _FakeBuilder:
+ def __init__(self, app: _FakeApp) -> None:
+ self.app = app
+ self.token_value = None
+ self.request_value = None
+ self.get_updates_request_value = None
+
+ def token(self, token: str):
+ self.token_value = token
+ return self
+
+ def request(self, request):
+ self.request_value = request
+ return self
+
+ def get_updates_request(self, request):
+ self.get_updates_request_value = request
+ return self
+
+ def proxy(self, _proxy):
+ raise AssertionError("builder.proxy should not be called when request is set")
+
+ def get_updates_proxy(self, _proxy):
+ raise AssertionError("builder.get_updates_proxy should not be called when request is set")
+
+ def build(self):
+ return self.app
+
+
+ @pytest.mark.asyncio
+ async def test_start_uses_request_proxy_without_builder_proxy(monkeypatch) -> None:
+ config = TelegramConfig(
+ enabled=True,
+ token="123:abc",
+ allow_from=["*"],
+ proxy="http://127.0.0.1:7890",
+ )
+ bus = MessageBus()
+ channel = TelegramChannel(config, bus)
+ app = _FakeApp(lambda: setattr(channel, "_running", False))
+ builder = _FakeBuilder(app)
+
+ monkeypatch.setattr("nanobot.channels.telegram.HTTPXRequest", _FakeHTTPXRequest)
+ monkeypatch.setattr(
+ "nanobot.channels.telegram.Application",
+ SimpleNamespace(builder=lambda: builder),
+ )
+
+ await channel.start()
+
+ assert len(_FakeHTTPXRequest.instances) == 1
+ assert _FakeHTTPXRequest.instances[0].kwargs["proxy"] == config.proxy
+ assert builder.request_value is _FakeHTTPXRequest.instances[0]
+ assert builder.get_updates_request_value is _FakeHTTPXRequest.instances[0]
++
++
++def test_derive_topic_session_key_uses_thread_id() -> None:
++ message = SimpleNamespace(
++ chat=SimpleNamespace(type="supergroup"),
++ chat_id=-100123,
++ message_thread_id=42,
++ )
++
++ assert TelegramChannel._derive_topic_session_key(message) == "telegram:-100123:topic:42"
++
++
++async def test_send_progress_keeps_message_in_topic() -> None:
++ config = TelegramConfig(enabled=True, token="123:abc", allow_from=["*"])
++ channel = TelegramChannel(config, MessageBus())
++ channel._app = _FakeApp(lambda: None)
++
++ await channel.send(
++ OutboundMessage(
++ channel="telegram",
++ chat_id="123",
++ content="hello",
++ metadata={"_progress": True, "message_thread_id": 42},
++ )
++ )
++
++ assert channel._app.bot.sent_messages[0]["message_thread_id"] == 42
++
++
++async def test_send_reply_infers_topic_from_message_id_cache() -> None:
++ config = TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], reply_to_message=True)
++ channel = TelegramChannel(config, MessageBus())
++ channel._app = _FakeApp(lambda: None)
++ channel._message_threads[("123", 10)] = 42
++
++ await channel.send(
++ OutboundMessage(
++ channel="telegram",
++ chat_id="123",
++ content="hello",
++ metadata={"message_id": 10},
++ )
++ )
++
++ assert channel._app.bot.sent_messages[0]["message_thread_id"] == 42
++ assert channel._app.bot.sent_messages[0]["reply_parameters"].message_id == 10