refactor(commands): own trusted Shell completion outside agent loop

This commit is contained in:
chengyongru authored and chengyongru committed 2026-11-05 16:39:09 +08:00
1 parent e6127aa324
commit 2b44088413
4 files changed
+140 -83

No files matched your search

+80 -13
View File
@@ -4,12 +4,11 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.shell import ExecTool
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
from nanobot.command.builtin import cmd_user_shell
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage
from nanobot.command.router import CommandContext
from nanobot.command.user_shell import cmd_user_shell
from nanobot.session.manager import Session, SessionPolicy
@@ -38,12 +37,11 @@ def _context(loop: MagicMock, *, trusted: bool, command: str = "pwd") -> Command
@pytest.mark.asyncio
async def test_user_shell_rejects_untrusted_transport_metadata() -> None:
loop = MagicMock()
loop.execute_user_shell_command = AsyncMock()
response = await cmd_user_shell(_context(loop, trusted=False))
assert "trusted local client" in response.content
loop.execute_user_shell_command.assert_not_awaited()
loop.tools.get.assert_not_called()
@pytest.mark.asyncio
@@ -71,7 +69,7 @@ async def test_user_shell_uses_exec_tool_with_workspace_scope(
if context_session:
ctx.session = session
response = await AgentLoop.execute_user_shell_command(loop, ctx)
response = await cmd_user_shell(ctx)
tool.execute_to_completion.assert_awaited_once_with(command="pwd", working_dir=str(tmp_path))
assert response.content.endswith("Exit code: 0")
@@ -80,13 +78,82 @@ async def test_user_shell_uses_exec_tool_with_workspace_scope(
@pytest.mark.asyncio
async def test_user_shell_delegates_trusted_request_to_agent_loop() -> None:
@pytest.mark.parametrize("command, disabled", [("", False), ("pwd", True)])
async def test_user_shell_reports_missing_command_or_disabled_execution(command, disabled) -> None:
loop = MagicMock()
expected = OutboundMessage(channel="websocket", chat_id="chat", content="ok")
loop.execute_user_shell_command = AsyncMock(return_value=expected)
ctx = _context(loop, trusted=True, command="printf ok")
loop.tools.get.return_value = None
response = await cmd_user_shell(_context(loop, trusted=True, command=command))
assert ("disabled" if disabled else "Type a command") in response.content
loop.sessions.state.get.assert_not_called()
response = await cmd_user_shell(ctx)
assert response is expected
loop.execute_user_shell_command.assert_awaited_once_with(ctx)
@pytest.mark.asyncio
async def test_user_command_keeps_waiting_for_full_result_while_model_observation_is_bounded(tmp_path):
import shlex
import sys
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.bus.queue import MessageBus
from nanobot.security.workspace_access import default_workspace_scope
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), session_manager=manager)
snippet = 'import time; print("first", flush=True); time.sleep(.15); print("last")'
command = f"{shlex.quote(sys.executable)} -I -c {shlex.quote(snippet)}"
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "unused-model"
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path)
loop.tools.register(tool)
ctx = _context(loop, trusted=True, command=command)
scope = default_workspace_scope(tmp_path, False, source_channel="websocket")
ctx.session = Session(key=ctx.key, metadata={"workspace_scope": scope.metadata()})
try:
bounded = await tool.execute(command=command, yield_time_ms=0)
assert "Process running" in bounded
response = await cmd_user_shell(ctx)
assert "first" in response.content and "last" in response.content
assert "Exit code: 0" in response.content and response.metadata["render_as"] == "text"
assert current_request_context() is None
finally:
await manager.close_all()
await loop.aclose()
@pytest.mark.asyncio
async def test_shell_cancellation_unwinds_workspace_and_request_context(tmp_path):
import asyncio
from nanobot.security.workspace_access import current_workspace_scope, default_workspace_scope
entered, release = asyncio.Event(), asyncio.Event()
scope = default_workspace_scope(tmp_path, False, source_channel="websocket")
after_cancel = []
async def execute(**kwargs):
entered.set()
assert current_request_context().session_key == "websocket:chat"
assert current_workspace_scope() is scope
await release.wait()
return "not reached"
tool = MagicMock(spec=ExecTool)
tool.execute_to_completion = AsyncMock(side_effect=execute)
loop = MagicMock()
loop.tools.get.return_value = tool
loop.workspace_scopes.for_turn.return_value = scope
ctx = _context(loop, trusted=True)
ctx.session = Session(key=ctx.key)
async def run_command():
try:
await cmd_user_shell(ctx)
finally:
after_cancel.append((current_request_context(), current_workspace_scope()))
task = asyncio.create_task(run_command())
await entered.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert after_cancel == [(None, None)]