feat(webui): guide sandbox launcher recovery from chat

This commit is contained in:
Xubin Ren committed 2026-11-08 14:29:46 +08:00
1 parent 16250540d3
commit f5e5bd6ea0
47 files changed
+613 -32

No files matched your search

@@ -7,6 +7,8 @@ import pytest
from agent.runner_helpers import make_run_spec
from nanobot.agent.progress_hook import AgentProgressHook
from nanobot.agent.runner import AgentRunner
from nanobot.agent.tools.base import ToolResult
from nanobot.agent.tools.registry import with_tool_error_hint
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, ToolCallRequest
from nanobot.utils.progress_events import output_events
@@ -14,6 +16,40 @@ from nanobot.utils.progress_events import output_events
_DEFAULTS = AgentDefaults()
@pytest.mark.asyncio
async def test_tool_error_code_is_display_metadata_not_model_content() -> None:
provider, tools = MagicMock(), MagicMock()
tool_call = ToolCallRequest(id="sandbox-call", name="exec", arguments={"command": "printf test"})
responses = iter([
LLMResponse(content="", tool_calls=[tool_call]),
LLMResponse(content="Please check the installation.", tool_calls=[]),
])
provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(responses))
tools.get_definitions.return_value = []
tools.prepare_call.return_value = (None, tool_call.arguments, None)
text = "Error: sandbox launcher not found: bwrap"
tools.execute = AsyncMock(return_value=ToolResult.error(text, error_code="sandbox_launcher_missing"))
events: list[dict] = []
async def on_progress(content: str, *, tool_hint: bool = False, tool_events: list[dict] | None = None) -> None:
events.extend(tool_events or [])
await AgentRunner().run(make_run_spec(
provider, tools=tools, model="test", initial_messages=[{"role": "user", "content": "Run a command"}],
max_iterations=3, max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
hook=AgentProgressHook(output_events(on_progress=on_progress)),
))
finished = events[-1]
assert finished["phase"] == "error"
assert finished["error_code"] == "sandbox_launcher_missing"
assert finished["error"] == with_tool_error_hint(text)
request = provider.chat_stream_with_retry.call_args.kwargs
tool_message = next(message for message in request["messages"] if message["role"] == "tool")
assert tool_message["content"] == with_tool_error_hint(text)
assert "error_code" not in tool_message
@pytest.mark.asyncio
async def test_start_and_finish_events_emitted() -> None:
provider = MagicMock()
@@ -10,6 +10,8 @@ from types import SimpleNamespace
import pytest
from nanobot.agent.tools.base import ToolResult
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.sandbox_check import check_sandbox, sandbox_settings_status
from nanobot.agent.tools.sandbox_launcher import SandboxLauncherError, resolve_sandbox_launcher
from nanobot.agent.tools.shell import ExecTool
@@ -38,6 +40,7 @@ async def test_nonstandard_bwrap_is_not_silently_run_without_sandbox(tmp_path, m
result = await tool.execute(command="printf ran > command-ran")
assert "sandbox launcher not found: bwrap" in result
assert isinstance(result, ToolResult) and result.error_code == "sandbox_launcher_missing"
assert not marker.exists()
@@ -57,6 +60,9 @@ async def test_writable_custom_launcher_is_rejected_before_execution(tmp_path, l
tool = ExecTool(working_dir=str(workspace), sandbox="bwrap", sandbox_launcher=str(launcher))
response = await tool.execute(command="echo command-ran", shell="/bin/sh", login=True)
assert "sandbox launcher rejected" in response
assert isinstance(response, ToolResult) and response.error_code in {
"sandbox_agent_writable", "sandbox_unprotected_installation",
}
assert not marker.exists()
if sys.platform.startswith("linux"):
status = await check_sandbox(config, workspace)
@@ -149,6 +155,26 @@ async def test_native_probe_checks_isolation_without_touching_workspace(tmp_path
# The same resolver and backend must work for actual command execution.
tool = ExecTool(working_dir=str(tmp_path), sandbox=backend, sandbox_launcher=result["launcher"])
assert "actual-command" in await tool.execute(command="printf actual-command")
failed_command = await tool.execute(command="printf 'sandbox launcher not found: bwrap'; exit 1")
assert "Exit code: 1" in failed_command
assert (failed_command.error_code if isinstance(failed_command, ToolResult) else None) is None
@pytest.mark.skipif(os.name != "posix", reason="Unix launch boundary")
@pytest.mark.parametrize("failure_target", ["launcher", "cwd"])
async def test_only_an_os_error_for_the_launcher_is_classified_as_a_sandbox_failure(tmp_path, monkeypatch, failure_target):
backend = "seatbelt" if sys.platform == "darwin" else "bwrap"
launcher = "/usr/bin/sandbox-exec" if backend == "seatbelt" else "/bin/sh"
async def start(*, command, cwd, **kwargs):
raise PermissionError(13, "launch rejected", command[0] if failure_target == "launcher" else cwd)
manager = ExecSessionManager()
monkeypatch.setattr(manager, "start", start)
tool = ExecTool(working_dir=str(tmp_path), sandbox=backend, sandbox_launcher=launcher, session_manager=manager)
result = await tool.execute(command="printf not-run")
assert isinstance(result, ToolResult) and result.is_error
assert result.error_code == ("sandbox_start_failed" if failure_target == "launcher" else None)
async def test_missing_environment_launcher_does_not_fall_back_or_launch(tmp_path, monkeypatch):
+3 -1
View File
@@ -425,14 +425,16 @@ async def test_registry_uses_structured_tool_result_for_errors(already_hinted: b
)
error_content = "Error: real failure" + (error_hint if already_hinted else "")
failing_tool = _FakeTool("failing_tool")
failing_tool.execute = AsyncMock(return_value=ToolResult.error(error_content))
failing_tool.execute = AsyncMock(return_value=ToolResult.error(error_content, error_code="sandbox_launcher_missing"))
registry.register(failing_tool)
error_result = await registry.execute("failing_tool", {})
assert isinstance(error_result, ToolResult)
assert error_result.is_error
assert error_result.error_code == "sandbox_launcher_missing"
assert error_result == "Error: real failure" + error_hint
assert json.dumps({"content": error_result}) == json.dumps({"content": "Error: real failure" + error_hint})
def test_get_definitions_returns_cached_result() -> None: