refactor(channels): move tool hint rendering out of core (#6498)
* refactor(channels): move tool hint rendering out of core * test: align progress privacy check with structured tool events
This commit is contained in:
1 parent
b1cc89e922
commit
acc3750c28
30 files changed
+530
-124
No files matched your search
@@ -3,12 +3,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.pairing import (
|
||||
@@ -19,6 +21,7 @@ from nanobot.pairing import (
|
||||
record_delivery,
|
||||
)
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.utils.tool_hints import format_tool_event_hints
|
||||
|
||||
|
||||
class BaseChannel(ABC):
|
||||
@@ -35,6 +38,7 @@ class BaseChannel(ABC):
|
||||
uses_shared_proxy: bool = False
|
||||
send_progress: bool = True
|
||||
send_tool_hints: bool = True
|
||||
tool_hint_max_length: int = 40
|
||||
show_reasoning: bool = True
|
||||
show_compaction_notices: bool = False
|
||||
|
||||
@@ -115,6 +119,19 @@ class BaseChannel(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
"""Project tool activity once before delivery; override for native UI.
|
||||
|
||||
Keep the core event unchanged and reuse the returned envelope throughout
|
||||
retries, including adapters that track already-sent multipart messages.
|
||||
"""
|
||||
event = msg.event
|
||||
if isinstance(event, ProgressEvent) and event.tool_hint and event.tool_events:
|
||||
return replace(msg, content=format_tool_event_hints(
|
||||
event.tool_events, max_length=self.tool_hint_max_length,
|
||||
))
|
||||
return msg
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
"""Whether delivery outlives an awaited ``send``/streaming call.
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.email.runtime import EmailChannel, EmailConfig
|
||||
@@ -814,7 +814,14 @@ async def test_send_uses_smtp_and_reply_subject(monkeypatch) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_skips_progress_messages_before_smtp(monkeypatch) -> None:
|
||||
@pytest.mark.parametrize("event", [
|
||||
ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "exec",
|
||||
"arguments": {"command": "git status"},
|
||||
}]),
|
||||
ProgressEvent(tool_events=[{"phase": "end", "call_id": "call-1", "name": "exec"}]),
|
||||
], ids=["tool-start", "tool-end"])
|
||||
async def test_send_skips_progress_messages_before_smtp(monkeypatch, event) -> None:
|
||||
called = {"smtp": False}
|
||||
|
||||
def _smtp_factory(*_args, **_kwargs):
|
||||
@@ -825,14 +832,12 @@ async def test_send_skips_progress_messages_before_smtp(monkeypatch) -> None:
|
||||
|
||||
channel = EmailChannel(_make_config(), MessageBus())
|
||||
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=[{"phase": "end", "name": "exec"}]),
|
||||
)
|
||||
msg = outbound_message_for_event(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
event=event,
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert called["smtp"] is False
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# ruff: noqa: E402
|
||||
|
||||
"""Tests for Feishu streaming (send_delta) via CardKit streaming API."""
|
||||
import json
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
@@ -10,9 +11,10 @@ import pytest
|
||||
pytest.importorskip("lark_oapi")
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig, _FeishuStreamBuf
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
|
||||
|
||||
def _make_channel(streaming: bool = True, reply_to_message: bool = False) -> FeishuChannel:
|
||||
@@ -536,26 +538,35 @@ class TestToolHintInlineStreaming:
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_keeps_existing_topic_when_reply_disabled(self):
|
||||
ch = _make_channel(reply_to_message=False)
|
||||
ch.tool_hint_max_length = 20
|
||||
reply_resp = MagicMock()
|
||||
reply_resp.success.return_value = True
|
||||
ch._client.im.v1.message.reply.return_value = reply_resp
|
||||
|
||||
msg = OutboundMessage(
|
||||
msg = outbound_message_for_event(
|
||||
channel="feishu", chat_id="oc_chat1",
|
||||
content='read_file("path")',
|
||||
event=ProgressEvent(content='read_file("path")', tool_hint=True),
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={
|
||||
"message_id": "om_001",
|
||||
"chat_type": "group",
|
||||
"thread_id": "ot_001",
|
||||
},
|
||||
)
|
||||
await ch.send(msg)
|
||||
await ChannelManager._send_once(ch, ch.prepare_tool_events(msg))
|
||||
|
||||
ch._client.im.v1.message.reply.assert_called_once()
|
||||
ch._client.im.v1.message.create.assert_not_called()
|
||||
request = ch._client.im.v1.message.reply.call_args[0][0]
|
||||
assert request.message_id == "om_001"
|
||||
assert request.request_body.reply_in_thread is not True
|
||||
assert request.request_body.msg_type == "interactive"
|
||||
card = json.loads(request.request_body.content)
|
||||
assert card["elements"][0]["content"] == '🔧 search "abcdefghijklmnopqrs…"'
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_group_replies_when_reply_enabled(self):
|
||||
|
||||
@@ -197,6 +197,9 @@ class LinearChannel(BaseChannel):
|
||||
key="response",
|
||||
)
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
return msg
|
||||
|
||||
async def _attachment_markdown(self, msg: OutboundMessage) -> list[str]:
|
||||
client = self._client
|
||||
if client is None:
|
||||
|
||||
@@ -36,6 +36,7 @@ from nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_url
|
||||
from nanobot.channels.linear.runtime import LinearChannel
|
||||
from nanobot.channels.linear.server import LinearServerLease, acquire_http_server
|
||||
from nanobot.channels.linear.state import LinearInstallation, LinearStateStore
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
|
||||
|
||||
def _config(port: int = 3979) -> LinearConfig:
|
||||
@@ -1148,7 +1149,7 @@ async def test_outbound_response_and_tool_progress_use_native_activity_shapes(
|
||||
}]
|
||||
),
|
||||
)
|
||||
await channel.send(tool)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(tool))
|
||||
|
||||
assert client.activities[0]["content"] == {"type": "response", "body": "Done"}
|
||||
assert client.activities[1]["activity_id"] == activity_id
|
||||
@@ -1220,19 +1221,22 @@ async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
|
||||
metadata = {
|
||||
"linear": {"organization_id": "org-1", "agent_session_id": "session-1"}
|
||||
}
|
||||
await channel.send(OutboundMessage(
|
||||
send = AsyncMock(wraps=channel.send)
|
||||
channel.send = send
|
||||
msg = OutboundMessage(
|
||||
channel="linear",
|
||||
chat_id="session-1",
|
||||
content="",
|
||||
metadata=metadata,
|
||||
event=ProgressEvent(tool_events=[{
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start",
|
||||
"call_id": "call-secret",
|
||||
"name": "call_api",
|
||||
"arguments": {"api_key": "secret-value", "query": "safe"},
|
||||
}]),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
msg = OutboundMessage(
|
||||
channel="linear",
|
||||
chat_id="session-1",
|
||||
content="",
|
||||
@@ -1243,8 +1247,9 @@ async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
|
||||
"name": "call_api",
|
||||
"error": "Authorization: Bearer plaintext-secret",
|
||||
}]),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
msg = OutboundMessage(
|
||||
channel="linear",
|
||||
chat_id="session-1",
|
||||
content="",
|
||||
@@ -1256,8 +1261,11 @@ async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
|
||||
"arguments": {"api_key": "secret-value"},
|
||||
"result": {"token": "result-secret", "status": "ok"},
|
||||
}]),
|
||||
))
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert send.await_count == 3
|
||||
assert all(call.args[0].content == "" for call in send.await_args_list)
|
||||
assert client.activities[0]["ephemeral"] is True
|
||||
assert client.activities[0]["content"]["action"] == "Call API"
|
||||
assert "secret-value" not in client.activities[0]["content"]["parameter"]
|
||||
|
||||
@@ -241,6 +241,7 @@ class ChannelManager:
|
||||
)
|
||||
kwargs["gateway"] = gateway
|
||||
channel = cls(section, self.bus, **kwargs)
|
||||
channel.tool_hint_max_length = self.config.agents.defaults.tool_hint_max_length
|
||||
if runtime_name and runtime_name != channel.name:
|
||||
channel.name = runtime_name
|
||||
progress_default, tool_hints_default = channel.progress_transport_defaults() or (
|
||||
@@ -801,6 +802,8 @@ class ChannelManager:
|
||||
"""
|
||||
if msg.delivery_id in self._scheduled_deliveries:
|
||||
return
|
||||
if isinstance(msg.event, ProgressEvent) and msg.event.tool_events:
|
||||
msg = channel.prepare_tool_events(msg)
|
||||
await self._outbound_slots.acquire()
|
||||
if msg.channel in self._stopping_channels or self.channels.get(msg.channel) is not channel:
|
||||
self._outbound_slots.release()
|
||||
|
||||
@@ -15,7 +15,9 @@ except ImportError:
|
||||
pytest.skip("Slack dependencies not installed (slack-sdk)", allow_module_level=True)
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.slack.runtime import SLACK_MAX_MESSAGE_LEN, SlackChannel, SlackConfig
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
@@ -141,6 +143,33 @@ async def test_send_uses_thread_for_channel_messages() -> None:
|
||||
assert fake_web.file_upload_calls[0]["thread_ts"] == "1700000000.000100"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_structured_tool_start_sends_text_in_thread() -> None:
|
||||
channel = SlackChannel(SlackConfig(enabled=True), MessageBus())
|
||||
fake_web = _FakeAsyncWebClient()
|
||||
channel._web_client = fake_web
|
||||
channel.tool_hint_max_length = 20
|
||||
msg = outbound_message_for_event(
|
||||
channel="slack",
|
||||
chat_id="C123",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={"slack": {"thread_ts": "1700000000.000100", "channel_type": "channel"}},
|
||||
)
|
||||
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert fake_web.chat_post_calls == [{
|
||||
"channel": "C123",
|
||||
"text": 'search "abcdefghijklmnopqrs…"',
|
||||
"thread_ts": "1700000000.000100",
|
||||
}]
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_omits_thread_for_dm_root_messages() -> None:
|
||||
"""DM root replies should not be threaded; metadata carries thread_ts=None."""
|
||||
|
||||
@@ -14,8 +14,9 @@ except ImportError:
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.telegram.runtime import (
|
||||
TELEGRAM_MAX_MESSAGE_LEN,
|
||||
TELEGRAM_REPLY_CONTEXT_MAX_LEN,
|
||||
@@ -1909,6 +1910,37 @@ async def test_send_progress_keeps_message_in_topic() -> None:
|
||||
assert channel._app.bot.sent_messages[0]["message_thread_id"] == 42
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_structured_tool_start_sends_quote_in_topic() -> None:
|
||||
config = TelegramConfig(
|
||||
enabled=True, token="123:abc", allow_from=["*"], reply_to_message=True,
|
||||
)
|
||||
channel = TelegramChannel(config, MessageBus())
|
||||
app = _install_ready_app(channel)
|
||||
channel.tool_hint_max_length = 20
|
||||
msg = outbound_message_for_event(
|
||||
channel="telegram",
|
||||
chat_id="123",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={"message_id": 10, "message_thread_id": 42},
|
||||
)
|
||||
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert len(app.bot.sent_messages) == 1
|
||||
sent = app.bot.sent_messages[0]
|
||||
assert sent["chat_id"] == 123
|
||||
assert sent["text"] == '<blockquote expandable>search "abcdefghijklmnopqrs…"</blockquote>'
|
||||
assert sent["parse_mode"] == "HTML"
|
||||
assert sent["message_thread_id"] == 42
|
||||
assert sent["reply_parameters"].message_id == 10
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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)
|
||||
|
||||
@@ -1130,6 +1130,9 @@ class WebSocketChannel(BaseChannel):
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
await self._outbound.send(msg)
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
return msg
|
||||
|
||||
async def send_reasoning_delta(
|
||||
self,
|
||||
chat_id: str,
|
||||
|
||||
@@ -40,6 +40,7 @@ from nanobot.bus.outbound_events import (
|
||||
UserInputEvent,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket import runtime as websocket_runtime
|
||||
from nanobot.channels.websocket.runtime import (
|
||||
WebSocketChannel,
|
||||
@@ -2623,18 +2624,17 @@ async def test_send_removes_connection_on_connection_closed() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_progress_includes_structured_tool_events() -> None:
|
||||
async def test_send_progress_includes_structured_tool_events(history) -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus, session_manager=history.sessions))
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-1")
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
msg = await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content='search "hermes"',
|
||||
content="",
|
||||
event=ProgressEvent(
|
||||
content='search "hermes"',
|
||||
tool_hint=True,
|
||||
tool_events=[
|
||||
{
|
||||
@@ -2653,11 +2653,13 @@ async def test_send_progress_includes_structured_tool_events() -> None:
|
||||
metadata={
|
||||
"webui_turn_id": "turn-1",
|
||||
},
|
||||
))
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
payload = json.loads(mock_ws.send.await_args.args[0])
|
||||
assert payload["event"] == "message"
|
||||
assert payload["kind"] == "tool_hint"
|
||||
assert payload["text"] == ""
|
||||
assert payload["turn_id"] == "turn-1"
|
||||
assert payload["turn_phase"] == "activity"
|
||||
assert payload["turn_seq"] == 1
|
||||
@@ -2674,6 +2676,15 @@ async def test_send_progress_includes_structured_tool_events() -> None:
|
||||
"embeds": [],
|
||||
}
|
||||
]
|
||||
[persisted] = history.read("websocket:chat-1")
|
||||
assert persisted["text"] == ""
|
||||
assert persisted["tool_events"] == payload["tool_events"]
|
||||
replay = history.build("websocket:chat-1")
|
||||
assert replay is not None
|
||||
[replayed] = replay["events"]
|
||||
assert replayed["kind"] == "tool_hint"
|
||||
assert replayed["text"] == ""
|
||||
assert replayed["tool_events"] == payload["tool_events"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -2704,14 +2715,17 @@ async def test_send_progress_omits_binary_tool_results_from_wire_and_transcript(
|
||||
}
|
||||
]
|
||||
|
||||
await channel.send(await history.message(
|
||||
msg = await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-binary-tool-result",
|
||||
content="read_file completed",
|
||||
event=ProgressEvent(content="read_file completed", tool_events=tool_events),
|
||||
))
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=tool_events),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
payload = json.loads(mock_ws.send.await_args.args[0])
|
||||
assert payload["kind"] == "progress"
|
||||
assert payload["text"] == ""
|
||||
[wire_event] = payload["tool_events"]
|
||||
assert wire_event["result"][0]["image_url"]["url"] == (
|
||||
"[binary content omitted from WebUI]"
|
||||
@@ -2719,8 +2733,14 @@ async def test_send_progress_omits_binary_tool_results_from_wire_and_transcript(
|
||||
assert len(mock_ws.send.await_args.args[0].encode("utf-8")) < 4096
|
||||
|
||||
[persisted] = history.read("websocket:chat-binary-tool-result")
|
||||
assert persisted["text"] == ""
|
||||
assert persisted["tool_events"] == payload["tool_events"]
|
||||
assert data_url not in json.dumps(persisted)
|
||||
replay = history.build("websocket:chat-binary-tool-result")
|
||||
assert replay is not None
|
||||
[replayed] = replay["events"]
|
||||
assert replayed["text"] == ""
|
||||
assert replayed["tool_events"] == payload["tool_events"]
|
||||
|
||||
# WebUI projection must not alter the result that the runner sends back to the model.
|
||||
assert tool_events[0]["result"][0]["image_url"]["url"] == data_url
|
||||
|
||||
@@ -16,6 +16,7 @@ import websockets
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
@@ -220,14 +221,32 @@ async def test_server_send_tags_tool_hint_with_kind(bus: MagicMock) -> None:
|
||||
assert plain.raw.get("kind") is None
|
||||
|
||||
# Tool-hint breadcrumb: kind == "tool_hint".
|
||||
await ch.send(OutboundMessage(
|
||||
tool_start = {
|
||||
"phase": "start", "call_id": "call-weather", "name": "weather",
|
||||
"arguments": {"action": "get"},
|
||||
}
|
||||
msg = OutboundMessage(
|
||||
channel="websocket", chat_id=ready.chat_id,
|
||||
content='weather("get")',
|
||||
event=ProgressEvent(content='weather("get")', tool_hint=True),
|
||||
))
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[tool_start]),
|
||||
)
|
||||
await ChannelManager._send_once(ch, ch.prepare_tool_events(msg))
|
||||
hint = await c.recv_message()
|
||||
assert hint.raw.get("kind") == "tool_hint"
|
||||
assert hint.text == 'weather("get")'
|
||||
assert hint.text == ""
|
||||
assert hint.raw["tool_events"] == [tool_start]
|
||||
|
||||
tool_end = {**tool_start, "phase": "end", "result": "sunny"}
|
||||
msg = OutboundMessage(
|
||||
channel="websocket", chat_id=ready.chat_id,
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=[tool_end]),
|
||||
)
|
||||
await ChannelManager._send_once(ch, ch.prepare_tool_events(msg))
|
||||
result = await c.recv_message()
|
||||
assert result.raw.get("kind") == "progress"
|
||||
assert result.text == ""
|
||||
assert result.raw["tool_events"] == [tool_end]
|
||||
|
||||
# Generic progress (non-tool-hint) gets the softer "progress" label.
|
||||
await ch.send(OutboundMessage(
|
||||
|
||||
@@ -1865,6 +1865,11 @@ class WeixinChannel(BaseChannel):
|
||||
self._raise_for_api_error("sendmessage", data)
|
||||
self._record_context_send(context_token)
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
if self.config.reply_progress_messages:
|
||||
return msg
|
||||
return super().prepare_tool_events(msg)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
event = getattr(msg, "event", None)
|
||||
if isinstance(event, ContextCompactionEvent) and not (
|
||||
|
||||
@@ -10,8 +10,10 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.weixin import runtime as weixin_mod
|
||||
from nanobot.channels.weixin.runtime import (
|
||||
ITEM_IMAGE,
|
||||
@@ -1857,19 +1859,20 @@ async def test_buffer_multiple_tool_hints_flushed_on_final_answer() -> None:
|
||||
channel._send_text = AsyncMock()
|
||||
|
||||
for hint in ["tool1", "tool2"]:
|
||||
await channel.send(
|
||||
type(
|
||||
"Msg",
|
||||
(),
|
||||
{
|
||||
"chat_id": "wx-user",
|
||||
"content": hint,
|
||||
"media": [],
|
||||
"event": ProgressEvent(content=hint, tool_hint=True),
|
||||
"metadata": {},
|
||||
},
|
||||
)()
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": f"call-{hint}", "name": hint, "arguments": {},
|
||||
}]),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
channel._send_text.assert_not_awaited()
|
||||
assert channel._pending_tool_hints["wx-user"] == ["tool1", "tool2"]
|
||||
|
||||
await channel.send(
|
||||
type(
|
||||
@@ -2050,19 +2053,16 @@ async def test_empty_progress_message_does_not_flush_tool_hints() -> None:
|
||||
)
|
||||
|
||||
# Send an empty progress message (no content, no media)
|
||||
await channel.send(
|
||||
type(
|
||||
"Msg",
|
||||
(),
|
||||
{
|
||||
"chat_id": "wx-user",
|
||||
"content": "",
|
||||
"media": [],
|
||||
"event": ProgressEvent(tool_events=[{"phase": "end"}]),
|
||||
"metadata": {},
|
||||
},
|
||||
)()
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=[{
|
||||
"phase": "end", "call_id": "call-search", "name": "web_search",
|
||||
"arguments": {"query": "foo"}, "result": "found",
|
||||
}]),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
# Nothing should have been sent yet
|
||||
channel._send_text.assert_not_awaited()
|
||||
|
||||
@@ -443,18 +443,30 @@ async def test_structured_progress_is_capped_and_uses_one_run_id() -> None:
|
||||
{"phase": "start", "call_id": "call-2", "name": "exec"},
|
||||
]
|
||||
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="read_file",
|
||||
event=ProgressEvent(content="read_file", tool_hint=True, tool_events=events),
|
||||
)
|
||||
send = AsyncMock(wraps=channel.send)
|
||||
channel.send = send
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=events),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
send.assert_awaited_once_with(msg)
|
||||
assert send.await_args.args[0] is msg
|
||||
assert msg.content == ""
|
||||
assert channel._send_message_item.await_count == 2
|
||||
first = channel._send_message_item.await_args_list[0]
|
||||
second = channel._send_message_item.await_args_list[1]
|
||||
assert first.args[1]["type"] == ITEM_TOOL_CALL_START
|
||||
assert second.args[1]["type"] == ITEM_TOOL_CALL_RESULT
|
||||
assert first.args[1]["tool_call_start_item"] == {
|
||||
"tool_name": "read_file", "tool_call_id": "call-1",
|
||||
}
|
||||
assert second.args[1]["tool_call_result_item"] == {
|
||||
"tool_name": "read_file", "tool_call_id": "call-1", "status": "completed",
|
||||
}
|
||||
assert first.args[2] == second.args[2] == "ctx-1"
|
||||
assert first.kwargs["run_id"] == second.kwargs["run_id"]
|
||||
assert first.kwargs["reserve_budget"] == second.kwargs["reserve_budget"] == 1
|
||||
@@ -21,11 +21,12 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRequest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.whatsapp_agent import runtime as runtime_module
|
||||
from nanobot.channels.whatsapp_agent.protocol import (
|
||||
TEXT_MAX_CHARS,
|
||||
APIError,
|
||||
WhatsAppAgentAPIError,
|
||||
WhatsAppAgentAuthError,
|
||||
@@ -35,6 +36,7 @@ from nanobot.channels.whatsapp_agent.runtime import (
|
||||
WhatsAppAgentChannel,
|
||||
WhatsAppAgentConfig,
|
||||
)
|
||||
from nanobot.utils.helpers import split_message
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -671,6 +673,69 @@ def test_manager_retry_resumes_after_acknowledged_parts(
|
||||
assert not channel._pending_sends
|
||||
|
||||
|
||||
async def test_manager_structured_tool_hint_retry_preserves_multipart_progress(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
config = Config.model_validate({
|
||||
"agents": {"defaults": {"toolHintMaxLength": 500}},
|
||||
"channels": {
|
||||
"websocket": {"enabled": False},
|
||||
"whatsapp_agent": {
|
||||
"enabled": True, "token": "test-token", "sendToolHints": True,
|
||||
"stateDir": str(tmp_path),
|
||||
},
|
||||
},
|
||||
})
|
||||
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
|
||||
channel = manager.channels["whatsapp_agent"]
|
||||
channel._state.note_creator("user:55")
|
||||
queries = [f"{index:02d}" + "x" * 498 for index in range(10)]
|
||||
msg = outbound_message_for_event(
|
||||
channel=channel.name,
|
||||
chat_id=CREATOR_CHAT_ID,
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": f"call-{index}", "name": "web_search",
|
||||
"arguments": {"query": query},
|
||||
} for index, query in enumerate(queries)]),
|
||||
)
|
||||
expected_hint = ", ".join(f'search "{query}"' for query in queries)
|
||||
chunks = split_message(expected_hint, TEXT_MAX_CHARS)
|
||||
assert len(chunks) == 2
|
||||
attempted: list[str] = []
|
||||
delivered: list[str] = []
|
||||
|
||||
def accept(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)["text"]["body"]
|
||||
attempted.append(body)
|
||||
if len(attempted) == 2:
|
||||
raise httpx.ConnectError("not submitted", request=request)
|
||||
delivered.append(body)
|
||||
return httpx.Response(200, json={"messages": [{"id": str(len(attempted))}]})
|
||||
|
||||
send = AsyncMock(wraps=channel.send)
|
||||
monkeypatch.setattr(channel, "send", send)
|
||||
monkeypatch.setattr("nanobot.channels.manager._SEND_RETRY_DELAYS", (0,))
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(accept)) as client:
|
||||
channel._client = client
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await asyncio.gather(*manager._outbound_tasks)
|
||||
|
||||
assert delivered == chunks
|
||||
assert attempted == [chunks[0], chunks[1], chunks[1]]
|
||||
assert send.await_count == 2
|
||||
first, retry = [call.args[0] for call in send.await_args_list]
|
||||
assert first is retry
|
||||
assert first is not msg
|
||||
assert first.content == expected_hint
|
||||
assert first.event is msg.event
|
||||
assert msg.content == msg.event.content == ""
|
||||
assert not channel._pending_sends
|
||||
|
||||
|
||||
@pytest.mark.parametrize("retry_ambiguous", [False, True])
|
||||
def test_media_failure_never_replays_accepted_text_or_attachments(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, retry_ambiguous: bool,
|
||||
|
||||
Reference in new issue
Block a user