Files
nanobot/tests/command/test_user_shell_command.py
T
chengyongru 8f6a5594fb refactor(session): centralize state ownership in SQLite (#5943)
* fix(session): move persistence off event loop

* refactor(session): isolate async persistence boundary

* refactor(session): keep a single session manager

* refactor(session): use stateless async adapters

* fix(session): serialize local persistence without file-lock contention

* refactor(session): own async persistence and snapshot commits

* refactor(session): narrow persistence changes to async adapters

* refactor(session): remove redundant async forwarding helpers

* fix(command): offload compact session persistence

* fix(session): adapt idle compaction to current main

* fix(webui): offload session metadata persistence

* refactor(session): centralize state ownership in SQLite

* fix(session): skip storage for non-recoverable followups

* test(webui): honor the full gateway event deadline

* perf(session): persist incremental changes and reuse owner snapshots

* test(agent): allow durable worker shutdown in burst test

* fix(gateway): drain session storage on Windows console shutdown

* fix(session): enforce bounded ownership and lifecycle-safe persistence

* fix: reject unresolved home paths and stabilize platform tests

* fix(session): preserve request context compatibility and owner-backed tests

* docs: focus configuration guide on user-facing behavior

* fix(session): adapt goal admission to async ownership after rebase

* fix(session): integrate current gateway and subagent contracts

* fix(session): align rebased workspace admission and async tests

* fix(session): support compatible SQLite schema evolution

* test(agent): use session owner in workspace context regressions

* test: stabilize Windows lifecycle and browser checks

* refactor(session): remove premature JSONL file export

* ci: bound Windows full-suite worker concurrency

* chore: remove session state refactor notes

* fix(session): queue writes and retain worker connections

* perf(webui): read detached metadata for session and task lists

* perf(agent): bound prompt preparation and local token counting

* docs: remove internal session storage guide

* perf(session): skip archived transcripts during idle scans

* fix(session): coordinate turns and isolate legacy session data

Bind WebUI input generations to the execution session and serialize idle
and SDK compaction with turns. Keep turn drafts through preparation so the
latest channel route persists.

Move imported workspace JSONL and checkpoints to durable private backups
before gateway admission, resuming cleanup after interruptions. Remove
committed child sessions when task creation is cancelled.

Validation: focused Python and frontend regressions, Ruff, BasedPyright,
import boundaries, WebUI build, and isolated gateway/browser flows.

* fix(agent): keep cancellation hooks independent of prompt preparation

* fix(session): preserve admission, delivery, and migration contracts

* fix(agent): preserve cancellation settlement after rebase

* fix(session): preserve request attribution through async ownership
2026-10-16 17:28:47 +08:00

92 lines
3.1 KiB
Python

from pathlib import Path
from types import SimpleNamespace
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.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
from nanobot.command.builtin import cmd_user_shell
from nanobot.command.router import CommandContext
from nanobot.session.manager import Session, SessionPolicy
def _context(loop: MagicMock, *, trusted: bool, command: str = "pwd") -> CommandContext:
metadata = {
"webui": True,
**({INBOUND_META_USER_SHELL: True} if trusted else {}),
}
msg = InboundMessage(
channel="websocket",
sender_id="local-user",
chat_id="chat",
content=f"!{command}",
metadata=metadata,
)
return CommandContext(
msg=msg,
session=None,
key=msg.session_key,
raw=msg.content,
args=command,
loop=loop,
)
@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()
@pytest.mark.asyncio
@pytest.mark.parametrize("log_content", [True, False])
@pytest.mark.parametrize("context_session", [True, False])
async def test_user_shell_uses_exec_tool_with_workspace_scope(
tmp_path: Path, log_content: bool, context_session: bool,
) -> None:
async def execute(**kwargs):
request = current_request_context()
assert request is not None
assert request.log_content is log_content
assert request.workspace == tmp_path
return f"{tmp_path}\n\nExit code: 0"
tool = MagicMock()
tool.execute = AsyncMock(side_effect=execute)
session = Session(key="websocket:chat", policy=SessionPolicy(log_content=log_content))
scope = SimpleNamespace(project_path=tmp_path)
loop = MagicMock()
loop.tools.get.return_value = tool
loop.sessions.state.get = AsyncMock(return_value=session)
loop.workspace_scopes.for_turn.return_value = scope
ctx = _context(loop, trusted=True)
if context_session:
ctx.session = session
response = await AgentLoop.execute_user_shell_command(loop, ctx)
tool.execute.assert_awaited_once_with(command="pwd", working_dir=str(tmp_path))
assert response.content.endswith("Exit code: 0")
assert response.metadata["render_as"] == "text"
assert current_request_context() is None
@pytest.mark.asyncio
async def test_user_shell_delegates_trusted_request_to_agent_loop() -> 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")
response = await cmd_user_shell(ctx)
assert response is expected
loop.execute_user_shell_command.assert_awaited_once_with(ctx)