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:
chengyongru authored and GitHub committed 2026-10-29 10:37:29 +08:00
1 parent b1cc89e922
commit acc3750c28
30 files changed
+530 -124

No files matched your search

+1 -1
View File
@@ -109,7 +109,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
"embeds": [],
},
]
assert progress_text == ['search X "nanobot oauth"', ""]
assert progress_text == ["", ""]
assert timeline == [
"delta:Before search.", "end:True", "tool:start", "tool:end", "delta:done", "end:False",
]
+48 -2
View File
@@ -53,7 +53,7 @@ async def test_start_and_finish_events_emitted() -> None:
assert progress == [
("Visible", False, None),
(
'custom_tool("foo.txt")',
"",
True,
[{
"version": 1,
@@ -139,5 +139,51 @@ async def test_streamed_content_is_not_repeated_before_tool_execution() -> None:
assert result.final_content == "Done"
assert streamed == ["I will", " inspect it."]
assert progress[0][0] == 'custom_tool("foo.txt")'
assert progress[0] == ("", True, [{
"version": 1, "phase": "start", "call_id": "call1", "name": "custom_tool",
"arguments": {"path": "foo.txt"}, "result": None, "error": None,
"files": [], "embeds": [],
}])
assert all(item[0] != "I will inspect it." for item in progress)
@pytest.mark.asyncio
async def test_batched_file_reads_keep_each_call_and_complete_arguments() -> None:
provider = MagicMock()
calls = [
ToolCallRequest(
id=f"read-{offset}", name="read_file",
arguments={"path": "src/" + "very-long-directory/" * 8 + "说明.md", "offset": offset},
)
for offset in (1, 200)
]
responses = iter([
LLMResponse(content="", tool_calls=calls),
LLMResponse(content="Done", tool_calls=[]),
])
provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(responses))
tools = MagicMock()
tools.get_definitions.return_value = []
tools.prepare_call.side_effect = lambda _name, args: (None, args, None)
tools.execute = AsyncMock(return_value="file contents")
progress = []
async def on_progress(content, *, tool_hint=False, tool_events=None):
progress.append((content, tool_hint, tool_events))
result = await AgentRunner().run(make_run_spec(
provider, initial_messages=[], tools=tools, model="test-model",
max_iterations=2, max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
concurrent_tools=True, hook=AgentProgressHook(output_events(on_progress=on_progress)),
))
assert result.final_content == "Done"
assert [(content, hint) for content, hint, _events in progress] == [("", True), ("", False)]
for _content, _hint, events in progress:
assert [(item["call_id"], item["name"], item["arguments"]) for item in events] == [
(call.id, call.name, call.arguments) for call in calls
]
assert [item["phase"] for item in progress[0][2]] == ["start", "start"]
assert [(item["phase"], item["result"]) for item in progress[1][2]] == [
("end", "file contents"), ("end", "file contents"),
]
@@ -2,6 +2,7 @@
import asyncio
from contextlib import suppress
from copy import deepcopy
from unittest.mock import AsyncMock
import pytest
@@ -376,30 +377,101 @@ class TestProgressFiltering:
assert send_mock.await_args_list[0].args[0].content == "final answer"
@pytest.mark.asyncio
async def test_channel_override_can_enable_tool_hints(self, manager, bus):
manager.channels["mock"].send_tool_hints = True
await bus.publish_outbound(outbound_message_for_event(
channel="mock",
chat_id="chat1",
event=ProgressEvent(content="read_file(foo.py)", tool_hint=True),
))
@pytest.mark.parametrize(
"send_progress, send_tool_hints, expected_indices, expected_contents",
[
(False, True, [1, 3], ["read foo.py", "read missing.py", "final answer"]),
(True, False, [0, 2, 4], ["thinking", "", "", "final answer"]),
],
)
async def test_tool_starts_and_terminals_follow_separate_visibility_settings(
self, manager, bus, send_progress, send_tool_hints, expected_indices, expected_contents,
):
channel = manager._build_channel(
MockChannel, {"sendProgress": send_progress, "sendToolHints": send_tool_hints},
)
manager.channels["mock"] = channel
events = [
ProgressEvent(content="thinking"),
ProgressEvent(tool_hint=True, tool_events=[{
"phase": "start", "call_id": "call-1", "name": "read_file",
"arguments": {"path": "foo.py"},
}]),
ProgressEvent(tool_events=[{
"phase": "end", "call_id": "call-1", "name": "read_file", "result": "contents",
}]),
ProgressEvent(tool_hint=True, tool_events=[{
"phase": "start", "call_id": "call-2", "name": "read_file",
"arguments": {"path": "missing.py"},
}]),
ProgressEvent(tool_events=[{
"phase": "error", "call_id": "call-2", "name": "read_file", "error": "not found",
}]),
]
messages = [
outbound_message_for_event(channel="mock", chat_id="chat1", event=event)
for event in events
]
final = OutboundMessage(channel="mock", chat_id="chat1", content="final answer")
for msg in [*messages, final]:
await bus.publish_outbound(msg)
delivered = asyncio.Event()
def record_send(msg):
if msg is final:
delivered.set()
channel._send_mock.side_effect = record_send
task = asyncio.create_task(manager._dispatch_outbound())
try:
for _ in range(30):
if manager.channels["mock"]._send_mock.await_count >= 1:
break
await asyncio.sleep(0.05)
await asyncio.wait_for(delivered.wait(), timeout=2)
finally:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
with suppress(asyncio.CancelledError):
await asyncio.wait_for(task, timeout=2)
send_mock = manager.channels["mock"]._send_mock
assert send_mock.await_count == 1
assert send_mock.await_args_list[0].args[0].content == "read_file(foo.py)"
sent = [call.args[0] for call in channel._send_mock.await_args_list]
assert [msg.content for msg in sent] == expected_contents
assert [msg.event for msg in sent] == [events[i] for i in expected_indices] + [None]
if send_progress:
assert sent[1] is messages[2]
assert sent[2] is messages[4]
assert messages[1].content == ""
assert events[1].content == ""
class TestToolEventDelivery:
@pytest.mark.asyncio
async def test_prepared_tool_hint_propagates_failure_without_mutating_core_message(self, manager):
manager.config.agents.defaults.tool_hint_max_length = 20
channel = manager._build_channel(MockChannel, {})
msg = outbound_message_for_event(
channel="mock",
chat_id="chat1",
event=ProgressEvent(tool_hint=True, stream_id="seg-1", tool_events=[{
"phase": "start", "call_id": "call-1", "name": "web_search",
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
}]),
metadata={"message_thread_id": 42},
)
original = deepcopy(msg)
error = RuntimeError("send failed")
channel._send_mock.side_effect = error
prepared = channel.prepare_tool_events(msg)
with pytest.raises(RuntimeError, match="send failed") as raised:
await manager._send_once(channel, prepared)
assert raised.value is error
channel._send_mock.assert_awaited_once()
sent = channel._send_mock.await_args.args[0]
assert sent is prepared
assert sent is not msg
assert sent.content == 'search "abcdefghijklmnopqrs…"'
assert sent.event is msg.event
assert sent.metadata == original.metadata
assert msg == original
class TestRetryWaitFiltering:
+27
View File
@@ -1659,6 +1659,33 @@ def test_agent_uses_default_config_when_no_workspace_or_config_flags(mock_agent_
)
@pytest.mark.parametrize("enabled", [True, False])
def test_one_shot_agent_renders_structured_tool_hints(mock_agent_runtime, enabled):
config = mock_agent_runtime["config"]
config.channels.send_tool_hints = enabled
config.channels.send_progress = False
config.agents.defaults.tool_hint_max_length = 20
mock_agent_runtime["agent_loop"].channels_config = config.channels
events = [{
"phase": "start", "call_id": "search-1", "name": "web_search",
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
}]
async def process_direct(*_args, on_progress, **_kwargs):
await on_progress("", tool_hint=True, tool_events=events)
return OutboundMessage(channel="cli", chat_id="direct", content="Done")
mock_agent_runtime["agent_loop"].process_direct.side_effect = process_direct
with patch("nanobot.cli.terminal._print_cli_progress_line") as print_progress:
result = runner.invoke(app, ["agent", "-m", "search"])
assert result.exit_code == 0, result.output
if enabled:
assert print_progress.call_args.args[0] == 'search "abcdefghijklmnopqrs…"'
else:
print_progress.assert_not_called()
def test_agent_uses_explicit_config_path(mock_agent_runtime, tmp_path: Path):
config_path = tmp_path / "agent-config.json"
config_path.write_text("{}")
+23
View File
@@ -189,3 +189,26 @@ async def test_non_reasoning_progress_not_affected_by_show_reasoning():
assert handled is True
assert calls == ["working on it..."]
@pytest.mark.asyncio
@pytest.mark.parametrize("enabled", [True, False])
async def test_interactive_structured_tool_hint_uses_cli_length_and_switch(enabled):
msg = SimpleNamespace(
content="",
event=ProgressEvent(tool_hint=True, tool_events=[{
"phase": "start", "call_id": "search-1", "name": "web_search",
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
}]),
metadata={},
)
config = SimpleNamespace(send_tool_hints=enabled, send_progress=False)
with patch("nanobot.cli.terminal._print_interactive_progress_line") as print_progress:
handled = await terminal._maybe_print_interactive_progress(
msg, None, config, tool_hint_max_length=20,
)
assert handled is True
if enabled:
print_progress.assert_awaited_once_with('search "abcdefghijklmnopqrs…"', None, None)
else:
print_progress.assert_not_awaited()
+1 -1
View File
@@ -196,7 +196,7 @@ class TestMessageToolSuppressLogic:
assert result.final_content == "Done"
assert progress == [
("Visible", False),
('read foo.txt', True),
("", True),
]
class TestMessageToolSchema: