test: replace false-green checks with behavioral coverage (#6282)

* test: replace false-green checks with behavioral coverage

* test: complete behavior-focused audit coverage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-18 03:16:25 +08:00
1 parent c7ab7aa6da
commit 74942bd190
91 files changed
+1891 -1391

No files matched your search

+4 -13
View File
@@ -507,26 +507,17 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_empty(self):
ac = _make_autocompact()
mock_sm = _mock_sessions()
ac.sessions = mock_sm
mock_sm.get_or_create.return_value = _make_session(metadata={
"_last_summary": {"text": "Previous checkpoint.", "last_active": "2026-05-13T10:00:00"},
})
ac = _make_autocompact(sessions=mock_sm)
ac.consolidator.compact_idle_session = AsyncMock(return_value="")
await ac._archive("cli:test", runtime=_runtime())
assert "cli:test" not in ac._summaries
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_nothing(self):
ac = _make_autocompact()
mock_sm = _mock_sessions()
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)")
await ac._archive("cli:test", runtime=_runtime())
assert "cli:test" not in ac._summaries
@pytest.mark.asyncio
async def test_exception_still_removes_from_archiving(self):
ac = _make_autocompact()
+20 -5
View File
@@ -1,21 +1,36 @@
from __future__ import annotations
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.context import ContextAware, RequestContext, request_context
from nanobot.agent.tools.registry import ToolRegistry
class _ContextTool:
class _ContextTool(Tool):
name = "legacy_context"
description = "External-style tool using the legacy context setter."
parameters = {"type": "object", "properties": {}}
def __init__(self):
self.last_ctx = None
def set_context(self, ctx: RequestContext) -> None:
self.last_ctx = ctx
async def execute(self, **kwargs):
return self.last_ctx
def test_context_aware_sets_request_context():
async def test_registry_injects_request_context_into_legacy_tool():
tool = _ContextTool()
registry = ToolRegistry()
registry.register(tool)
ctx = RequestContext(channel="test", chat_id="123", session_key="test:123")
tool.set_context(ctx)
assert tool.last_ctx.channel == "test"
with request_context(ctx):
result = await registry.execute(tool.name, {})
assert result is ctx
assert tool.last_ctx is ctx
def test_context_tool_is_instance_of_context_aware():
+4 -7
View File
@@ -281,16 +281,13 @@ class TestBuildUserContent:
class TestBuildSystemPrompt:
def test_returns_nonempty_string(self, tmp_path):
builder = _builder(tmp_path)
result = builder.build_system_prompt()
assert isinstance(result, str)
assert len(result) > 0
def test_includes_identity_section(self, tmp_path):
builder = _builder(tmp_path)
result = builder.build_system_prompt()
assert "workspace" in result.lower() or "python" in result.lower()
assert "## Runtime\n" in result
assert "Agent profile: SOUL.md and USER.md" in result
assert "History log: memory/history.jsonl" in result
def test_default_identity_uses_relative_agent_paths(self, tmp_path):
result = ContextBuilder(tmp_path)._get_identity()
-14
View File
@@ -289,20 +289,6 @@ async def test_composite_error_isolation_all_async():
# ---------------------------------------------------------------------------
def test_composite_finalize_content_pipeline():
class Upper(AgentHook):
def finalize_content(self, context, content):
return content.upper() if content else content
class Suffix(AgentHook):
def finalize_content(self, context, content):
return (content + "!") if content else content
hook = CompositeHook([Upper(), Suffix()])
result = hook.finalize_content(_ctx(), "hello")
assert result == "HELLO!"
def test_composite_finalize_content_none_passthrough():
hook = CompositeHook([AgentHook()])
assert hook.finalize_content(_ctx(), None) is None
+32 -15
View File
@@ -64,8 +64,8 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
release = threading.Event()
captured = []
finalized = []
ticks = []
ticking = True
heartbeat_requested = asyncio.Event()
heartbeat_progress = asyncio.Event()
class Lifecycle(AgentHook):
async def on_finally(self, context):
@@ -77,15 +77,16 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
context.messages[0]["content"] = "hook-only"
async def heartbeat():
while ticking:
ticks.append(runtime_loop.time())
await asyncio.sleep(0.01)
while True:
await heartbeat_requested.wait()
heartbeat_requested.clear()
heartbeat_progress.set()
def blocked(operation, *args, **kwargs):
captured.append((current_request_context(), current_workspace_scope(), threading.get_ident()))
runtime_loop.call_soon_threadsafe(entered.set)
try:
assert release.wait(5), "test did not release prompt preparation"
assert release.wait(10), "test did not release prompt preparation"
return operation(*args, **kwargs)
finally:
runtime_loop.call_soon_threadsafe(finished.set)
@@ -127,11 +128,11 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
tasks = [task, pulse]
try:
await asyncio.wait_for(entered.wait(), timeout=5)
before = len(ticks)
status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 0.5)
status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 5)
assert status is not None and "test-model" in status.content
await asyncio.sleep(0.04)
assert len(ticks) >= before + 2
heartbeat_requested.set()
await asyncio.wait_for(heartbeat_progress.wait(), 5)
assert not release.is_set()
assert not finished.is_set()
assert captured[0][2] != threading.get_ident()
if phase != "history":
@@ -145,7 +146,7 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
if cancel:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(task, 0.5)
await asyncio.wait_for(task, 5)
assert not finished.is_set()
if phase != "history":
assert len(finalized) == 1
@@ -155,15 +156,32 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
assert final_loop is runtime_loop
if phase != "prompt":
assert snapshot
# A new session queues behind the physical worker, even after its caller exits.
# Observe the new session entering the real semaphore, not a settling delay.
slots = loop.runner.context_governor._preparation_slots
acquire_slot = slots.acquire
queued = asyncio.Event()
acquired = asyncio.Event()
async def acquire():
# History preparation queues before RequestContext is bound.
is_waiting = asyncio.current_task() is waiting
if is_waiting:
queued.set()
result = await acquire_slot()
if is_waiting:
acquired.set()
return result
monkeypatch.setattr(slots, "acquire", acquire)
waiting = asyncio.create_task(loop.process_direct("Queued", session_key="cli:waiting"))
tasks.append(waiting)
await asyncio.sleep(0.04)
await asyncio.wait_for(queued.wait(), 5)
assert not acquired.is_set()
assert len(provider.requests) == expected_requests
assert not waiting.done()
waiting.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(waiting, 0.5)
await asyncio.wait_for(waiting, 5)
elif phase == "history":
# The live nested payload may change after capture; the worker owns its copy.
live.messages[0]["content"][0]["text"] = "Changed after capture"
@@ -184,7 +202,6 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
assert current_request_context() is None
assert current_workspace_scope() is None
finally:
ticking = False
release.set()
for pending in tasks:
if not pending.done():
-34
View File
@@ -1487,40 +1487,6 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(
]
def test_governance_repairs_orphans_after_history_rewrite():
"""A rewritten history drops tool results whose calls are no longer present."""
rewritten = [
{"role": "system", "content": "system"},
{"role": "tool", "tool_call_id": "tc_old", "name": "search",
"content": "old result"},
{"role": "assistant", "content": "old answer"},
{"role": "user", "content": "new msg"},
]
cleaned = ContextGovernor.drop_orphan_tool_results(rewritten)
# The orphan tool result should be removed.
assert not any(
m.get("role") == "tool" and m.get("tool_call_id") == "tc_old"
for m in cleaned
)
def test_governance_fallback_still_repairs_orphans():
"""When full governance fails, the fallback must still repair orphans."""
# Messages with an orphan tool result (no matching assistant tool_call).
messages = [
{"role": "user", "content": "hello"},
{"role": "tool", "tool_call_id": "orphan_tc", "name": "read",
"content": "stale"},
{"role": "assistant", "content": "hi"},
]
repaired = ContextGovernor.drop_orphan_tool_results(messages)
repaired = ContextGovernor.backfill_missing_tool_results(repaired)
# Orphan tool result should be gone.
assert not any(m.get("tool_call_id") == "orphan_tc" for m in repaired)
# ---------------------------------------------------------------------------
# Malformed tool_call name guard (missing/non-string name wedges the session
# upstream: messages.content.N.tool_use.name: Input should be a valid string)
+15
View File
@@ -182,6 +182,21 @@ async def test_runner_lets_llm_recover_from_shell_guard_path_outside():
assert result.tool_events and result.tool_events[0]["status"] == "error"
# v2: detail keeps the breadcrumb but the runner did not raise.
assert "workspace_violation" in result.tool_events[0]["detail"]
calls = [
call
for message in captured_second_call if message.get("role") == "assistant"
for call in message.get("tool_calls", []) if call["id"] == "call_blocked"
]
assert len(calls) == 1
assert calls[0]["function"]["name"] == "exec"
rejections = [
message for message in captured_second_call
if message.get("role") == "tool" and message.get("tool_call_id") == "call_blocked"
]
assert len(rejections) == 1
assert rejections[0]["name"] == "exec"
assert "Command blocked by safety guard (path outside working dir)" in rejections[0]["content"]
assert "Consider this result in the context of the user's goal" in rejections[0]["content"]
@pytest.mark.asyncio
+1 -61
View File
@@ -147,6 +147,7 @@ class TestInspectPathNavigation:
@pytest.mark.asyncio
async def test_inspect_config_subfield(self):
"""Positive control for sensitive-field blocking: ordinary config stays inspectable."""
loop = _make_mock_loop()
tool = _make_tool(loop=loop)
result = await tool.execute(action="check", key="web_config.enable")
@@ -649,60 +650,6 @@ class TestSubagentHookStatus:
assert context.iteration == 1
# ---------------------------------------------------------------------------
# Checkpoint callback updates status
# ---------------------------------------------------------------------------
class TestCheckpointCallback:
@pytest.mark.asyncio
async def test_checkpoint_updates_phase_and_iteration(self):
"""The _on_checkpoint callback should update status.phase and iteration."""
from nanobot.agent.subagent import SubagentStatus
status = SubagentStatus(
task_id="cp",
label="test",
task_description="test",
started_at=time.monotonic(),
)
# Simulate the checkpoint callback as defined in _run_subagent
async def _on_checkpoint(payload: dict) -> None:
status.phase = payload.get("phase", status.phase)
status.iteration = payload.get("iteration", status.iteration)
await _on_checkpoint({"phase": "awaiting_tools", "iteration": 2})
assert status.phase == "awaiting_tools"
assert status.iteration == 2
await _on_checkpoint({"phase": "tools_completed", "iteration": 3})
assert status.phase == "tools_completed"
assert status.iteration == 3
@pytest.mark.asyncio
async def test_checkpoint_preserves_phase_on_missing_key(self):
"""If payload doesn't have 'phase', status.phase should stay unchanged."""
from nanobot.agent.subagent import SubagentStatus
status = SubagentStatus(
task_id="cp",
label="test",
task_description="test",
started_at=time.monotonic(),
phase="initializing",
)
async def _on_checkpoint(payload: dict) -> None:
status.phase = payload.get("phase", status.phase)
status.iteration = payload.get("iteration", status.iteration)
await _on_checkpoint({"iteration": 1})
assert status.phase == "initializing"
assert status.iteration == 1
# ---------------------------------------------------------------------------
# read-only mode (tools.my.allow_set=False)
# ---------------------------------------------------------------------------
@@ -819,13 +766,6 @@ class TestSensitiveSubFieldBlocking:
result = await tool.execute(action="set", key="some_config.password", value="evil")
assert "not accessible" in result
@pytest.mark.asyncio
async def test_inspect_non_sensitive_subfield_allowed(self):
"""web_config.enable should still be inspectable."""
tool = _make_tool()
result = await tool.execute(action="check", key="web_config.enable")
assert "True" in result
@pytest.mark.asyncio
async def test_modify_sensitive_top_level_blocked(self):
"""Top-level key matching sensitive name must be blocked for set."""
+68 -24
View File
@@ -110,19 +110,13 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
)
mgr._announce_result = AsyncMock()
async def fake_run(spec):
exec_tool = spec.tools.get("exec")
assert exec_tool is not None
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
return AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
)
mgr.runner.run = AsyncMock(side_effect=fake_run)
mgr.runner.run = AsyncMock(return_value=AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
))
await mgr.spawn(
task="do task",
@@ -134,6 +128,11 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
spec = mgr.runner.run.await_args.args[0]
exec_tool = spec.tools.get("exec")
assert exec_tool is not None
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio
@@ -154,17 +153,13 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
)
mgr._announce_result = AsyncMock()
async def fake_run(spec):
assert spec.max_iterations == 37
return AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
)
mgr.runner.run = AsyncMock(side_effect=fake_run)
mgr.runner.run = AsyncMock(return_value=AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
))
await mgr.spawn(
task="do task",
@@ -176,6 +171,55 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
spec = mgr.runner.run.await_args.args[0]
assert spec.max_iterations == 37
assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio
async def test_subagent_checkpoint_updates_status_and_preserves_omitted_fields(tmp_path):
"""Runner checkpoints update detached task snapshots without resetting omitted fields."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
mgr = SubagentManager(
consolidator=MagicMock(spec=Consolidator),
workspace=tmp_path,
bus=MessageBus(),
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
)
mgr._announce_result = AsyncMock()
snapshots = []
async def fake_run(spec):
for payload in [
{"phase": "awaiting_tools", "iteration": 2},
{"phase": "tools_completed", "iteration": 3},
{"iteration": 4},
{"phase": "final_response"},
]:
await spec.checkpoint_callback(payload)
snapshots.extend(mgr.statuses_for_session("test:c1").values())
return AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
)
mgr.runner.run = AsyncMock(side_effect=fake_run)
await mgr.spawn(task="do task", session_key="test:c1", runtime=_runtime(MagicMock()))
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
assert [(s.state, s.phase, s.iteration) for s in snapshots] == [
("running", "awaiting_tools", 2),
("running", "tools_completed", 3),
("running", "tools_completed", 4),
("running", "final_response", 4),
]
assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio
-54
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import json
import subprocess
import sys
import pytest
@@ -53,59 +52,6 @@ def test_subprocess_env_excludes_api_keys_on_windows(monkeypatch, tmp_path) -> N
assert all(isinstance(value, str) for value in env.values())
def test_run_passes_filtered_env(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "sk-should-not-leak")
manager = CliAppManager(workspace=tmp_path, data_dir=tmp_path / "cli-apps")
captured: dict[str, object] = {}
def fake_run(*args, **kwargs):
captured.update(kwargs)
class Result:
returncode = 0
stdout = "ok"
stderr = ""
return Result()
monkeypatch.setattr("nanobot.apps.cli.service.subprocess.run", fake_run)
monkeypatch.setattr(manager, "get_app", lambda name: {"name": name, "entry_point": "echo"})
monkeypatch.setattr(
manager,
"_load_installed",
lambda: {"echo": {"entry_point": "echo"}},
)
monkeypatch.setattr("nanobot.apps.cli.service.shutil.which", lambda entry: "/bin/echo")
monkeypatch.setattr(manager, "_resolve_cwd", lambda *a, **k: tmp_path)
monkeypatch.setattr(manager, "_artifact_snapshot", lambda cwd: {})
monkeypatch.setattr(manager, "_changed_artifacts", lambda cwd, snap: [])
manager.run("echo", ["hi"])
env = captured.get("env")
assert isinstance(env, dict)
assert "OPENAI_API_KEY" not in env
def test_management_subprocesses_use_filtered_env(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "sk-should-not-leak")
captured: dict[str, object] = {}
def fake_run(*args, **kwargs):
captured.update(kwargs)
return subprocess.CompletedProcess(args[0], 0, stdout="ok", stderr="")
monkeypatch.setattr("nanobot.apps.cli.service.subprocess.run", fake_run)
manager = CliAppManager(workspace=tmp_path, data_dir=tmp_path / "cli-apps")
manager._run_argv(["example-cli", "--help"], timeout=5)
env = captured.get("env")
assert isinstance(env, dict)
assert "OPENAI_API_KEY" not in env
assert env["PYTHONUNBUFFERED"] == "1"
@pytest.mark.parametrize("operation", ["run", "management"])
@pytest.mark.parametrize("runtime_dir", ["/run/user/1000", None])
def test_child_process_receives_runtime_dir_without_api_keys(
@@ -3,10 +3,12 @@
from __future__ import annotations
import asyncio
from contextlib import suppress
from unittest.mock import AsyncMock
import pytest
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import (
ContextCompactionEvent,
ProgressEvent,
@@ -33,84 +35,77 @@ class _MockChannel(BaseChannel):
pass
async def send(self, msg):
if isinstance(msg.event, ContextCompactionEvent) and not (
msg.event.notify or self.show_compaction_notices
):
return
return await self._send_mock(msg)
@pytest.fixture
def manager() -> ChannelManager:
def manager(tmp_path) -> ChannelManager:
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
mgr = ChannelManager(config, MessageBus())
mgr = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
mgr.channels["mock"] = _MockChannel({}, mgr.bus)
return mgr
async def _dispatch_until(manager: ChannelManager, expected: int) -> None:
task = asyncio.create_task(manager._dispatch_outbound())
try:
for _ in range(40):
if manager.channels["mock"]._send_mock.await_count >= expected:
break
await asyncio.sleep(0.05)
finally:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
def _sent_contents(manager: ChannelManager) -> list[str]:
return [call.args[0].content for call in manager.channels["mock"]._send_mock.await_args_list]
@pytest.mark.asyncio
async def test_channel_receives_automatic_compaction_but_does_not_render_it(
async def test_dispatch_forwards_all_compaction_phases_before_adapter_filtering(
manager: ChannelManager,
) -> None:
manager.channels["mock"].send_progress = False
for event in (
ProgressEvent(content="ordinary progress"),
channel = manager.channels["mock"]
channel.send_progress = False
channel.show_compaction_notices = False
events = [
ContextCompactionEvent(compaction_id="auto", phase="started"),
ContextCompactionEvent(compaction_id="auto", phase="succeeded"),
ContextCompactionEvent(compaction_id="auto-failed", phase="failed"),
ContextCompactionEvent(compaction_id="auto-cancelled", phase="cancelled"),
ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),
ContextCompactionEvent(compaction_id="c1", phase="succeeded", notify=True),
):
await manager.bus.publish_outbound(
outbound_message_for_event(channel="mock", chat_id="chat", event=event)
)
]
await manager.bus.publish_outbound(outbound_message_for_event(
channel="mock", chat_id="chat", event=ProgressEvent(content="ordinary progress"),
))
messages = [
outbound_message_for_event(channel="mock", chat_id="chat", event=event)
for event in events
]
for msg in messages:
await manager.bus.publish_outbound(msg)
final = OutboundMessage(channel="mock", chat_id="chat", content="Final")
await manager.bus.publish_outbound(final)
delivered = asyncio.Event()
await _dispatch_until(manager, 2)
def record_send(msg):
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat", "Final", None):
delivered.set()
contents = _sent_contents(manager)
assert "ordinary progress" not in contents
assert contents == ["Compressing context…", "Context compacted."]
channel._send_mock.side_effect = record_send
task = asyncio.create_task(manager._dispatch_outbound())
try:
await asyncio.wait_for(delivered.wait(), timeout=2)
finally:
task.cancel()
with suppress(asyncio.CancelledError):
await asyncio.wait_for(task, timeout=2)
# The recorder sees the manager -> adapter boundary, not a fake presentation rule.
received = [call.args[0] for call in channel._send_mock.await_args_list]
assert received == [*messages, final]
assert [msg.event for msg in received] == [*events, None]
assert [msg.content for msg in received[-3:]] == [
"Compressing context…", "Context compacted.", "Final",
]
assert not manager._outbound_tasks
assert not manager._outbound_tails
@pytest.mark.parametrize("global_value", [False, True])
@pytest.mark.parametrize("override", [None, False, True])
@pytest.mark.parametrize("key", ["show_compaction_notices", "showCompactionNotices"])
async def test_global_notice_policy_and_channel_override(manager, global_value, override, key):
def test_global_notice_policy_and_channel_override(manager, global_value, override, key):
manager.config.channels.show_compaction_notices = global_value
section = {} if override is None else {key: override}
channel = manager._build_channel("mock", _MockChannel, section)
assert channel.show_compaction_notices is (global_value if override is None else override)
channel.send_progress = False # Ordinary progress and compaction are independent policies.
manager.channels["mock"] = channel
for phase in ("started", "succeeded", "failed", "cancelled"):
for notify in (False, True):
await channel.send(outbound_message_for_event(
channel="mock", chat_id="chat",
event=ContextCompactionEvent("compact", phase, notify=notify),
))
assert channel._send_mock.await_count == (8 if channel.show_compaction_notices else 4)
def test_global_notice_config_round_trip_and_rebuild(manager):
@@ -1,6 +1,7 @@
"""Tests for ChannelManager delta coalescing to reduce streaming latency."""
import asyncio
from contextlib import suppress
from unittest.mock import AsyncMock
import pytest
@@ -74,8 +75,8 @@ def bus():
@pytest.fixture
def manager(config, bus):
manager = ChannelManager(config, bus)
def manager(config, bus, tmp_path):
manager = ChannelManager(config, bus, config_path=tmp_path / "config.json")
manager.channels["mock"] = manager._build_channel("mock", MockChannel, {})
return manager
@@ -121,43 +122,6 @@ class TestDeltaCoalescing:
assert merged.metadata == first.metadata
assert pending == [second]
@pytest.mark.asyncio
async def test_single_delta_not_coalesced(self, manager, bus):
msg = _delta("Hello")
await bus.publish_outbound(msg)
async def process_one():
try:
m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)
event = m.event
if isinstance(event, StreamDeltaEvent):
m, pending = manager._coalesce_stream_deltas(m)
for p in pending:
await bus.publish_outbound(p)
channel = manager.channels.get(m.channel)
event = m.event
if channel and isinstance(event, StreamDeltaEvent):
await channel.send_delta(
m.chat_id,
m.content,
m.metadata,
stream_id=event.stream_id,
)
except asyncio.TimeoutError:
pass
await process_one()
manager.channels["mock"]._send_delta_mock.assert_called_once_with(
"chat1",
"Hello",
{},
stream_id=None,
stream_end=False,
resuming=False,
merge_next=False,
)
@pytest.mark.asyncio
async def test_multiple_deltas_coalesced(self, manager, bus):
for text in ["Hello", " ", "world", "!"]:
@@ -270,38 +234,49 @@ class TestDispatchOutboundWithCoalescing:
"""Tests for the full _dispatch_outbound flow with coalescing."""
@pytest.mark.asyncio
async def test_dispatch_coalesces_and_processes_pending(self, manager, bus):
await bus.publish_outbound(_delta("A"))
await bus.publish_outbound(_delta("B"))
await bus.publish_outbound(OutboundMessage(
channel="mock",
chat_id="chat1",
content="Final",
))
@pytest.mark.parametrize("end_stream", [False, True])
async def test_dispatch_coalesces_and_delivers_final(self, manager, bus, end_stream):
await bus.publish_outbound(_delta("A", stream_id="seg-1"))
await bus.publish_outbound(_delta("B", stream_id="seg-1"))
if end_stream:
await bus.publish_outbound(_end(
"C", stream_id="seg-1", resuming=True, merge_next=True,
))
final = OutboundMessage(channel="mock", chat_id="chat1", content="Final")
await bus.publish_outbound(final)
delivered = asyncio.Event()
received = []
pending = []
processed = []
def record_delta(chat_id, delta, metadata, **flags):
received.append(("delta", chat_id, delta, metadata, flags))
msg = pending.pop(0) if pending else await bus.consume_outbound()
event = msg.event
if isinstance(event, StreamDeltaEvent):
msg, extra_pending = manager._coalesce_stream_deltas(msg)
pending.extend(extra_pending)
def record_send(msg):
received.append(("send", msg.channel, msg.chat_id, msg.content, msg.event))
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat1", "Final", None):
delivered.set()
channel = manager.channels.get(msg.channel)
event = msg.event
if channel and isinstance(event, StreamDeltaEvent):
await channel.send_delta(
msg.chat_id,
msg.content,
msg.metadata,
stream_id=event.stream_id,
)
processed.append(("delta", msg.content))
channel = manager.channels["mock"]
channel._send_delta_mock.side_effect = record_delta
channel._send_mock.side_effect = record_send
task = asyncio.create_task(manager._dispatch_outbound())
try:
await asyncio.wait_for(delivered.wait(), timeout=2)
finally:
task.cancel()
with suppress(asyncio.CancelledError):
await asyncio.wait_for(task, timeout=2)
assert processed == [("delta", "AB")]
assert len(pending) == 1
assert pending[0].content == "Final"
assert received == [
("delta", "chat1", "ABC" if end_stream else "AB", {}, {
"stream_id": "seg-1",
"stream_end": end_stream,
"resuming": end_stream,
"merge_next": end_stream,
}),
("send", "mock", "chat1", "Final", None),
]
assert not manager._outbound_tasks
assert not manager._outbound_tails
class TestProgressFiltering:
@@ -16,6 +16,7 @@ plugins only implement the streaming primitives.
from __future__ import annotations
import asyncio
from contextlib import suppress
from unittest.mock import AsyncMock
import pytest
@@ -41,6 +42,7 @@ class _MockChannel(BaseChannel):
self._delta_mock = AsyncMock()
self._end_mock = AsyncMock()
self._file_edit_mock = AsyncMock()
self.received = []
async def start(self): # pragma: no cover - not exercised
pass
@@ -49,27 +51,31 @@ class _MockChannel(BaseChannel):
pass
async def send(self, msg):
return await self._send_mock(msg)
await self._send_mock(msg)
self.received.append(("send", msg))
async def send_reasoning_delta(self, chat_id, delta, metadata=None, *, stream_id=None):
return await self._delta_mock(chat_id, delta, metadata, stream_id=stream_id)
await self._delta_mock(chat_id, delta, metadata, stream_id=stream_id)
self.received.append(("delta", chat_id, delta, metadata, stream_id))
async def send_reasoning_end(self, chat_id, metadata=None, *, stream_id=None):
return await self._end_mock(chat_id, metadata, stream_id=stream_id)
await self._end_mock(chat_id, metadata, stream_id=stream_id)
self.received.append(("end", chat_id, metadata, stream_id))
async def send_file_edit_events(self, chat_id, edits, metadata=None):
return await self._file_edit_mock(chat_id, edits, metadata)
@pytest.fixture
def manager() -> ChannelManager:
def manager(tmp_path) -> ChannelManager:
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
mgr = ChannelManager(config, MessageBus())
mgr = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
mgr.channels["mock"] = _MockChannel({}, mgr.bus)
return mgr
def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
monkeypatch.setattr(
"nanobot.webui.workspaces.read_webui_default_access_mode",
lambda: "default",
@@ -87,7 +93,9 @@ def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monke
}
)
mgr = ChannelManager(config, MessageBus(), webui_static_dist=False)
mgr = ChannelManager(
config, MessageBus(), webui_static_dist=False, config_path=tmp_path / "config.json",
)
channel = mgr.channels["websocket"]
scope = channel.gateway.workspaces.default_scope()
@@ -142,58 +150,58 @@ async def test_one_shot_reasoning_expands_to_delta_plus_end(manager):
@pytest.mark.asyncio
async def test_dispatch_drops_reasoning_when_channel_opts_out(manager):
@pytest.mark.parametrize("show_reasoning", [False, True])
@pytest.mark.parametrize("send_progress", [False, True])
async def test_dispatch_reasoning_visibility_is_independent_of_progress(
manager, show_reasoning, send_progress,
):
channel = manager.channels["mock"]
channel.show_reasoning = False
msg = outbound_message_for_event(
channel="mock",
chat_id="c1",
event=ProgressEvent(content="hidden thinking", reasoning_delta=True),
)
await manager.bus.publish_outbound(msg)
channel.show_reasoning = show_reasoning
channel.send_progress = send_progress
events = [
ProgressEvent(content="first ", reasoning_delta=True, stream_id="r1"),
ProgressEvent(content="second", reasoning_delta=True, stream_id="r1"),
ProgressEvent(reasoning_end=True, stream_id="r1"),
ProgressEvent(content="one-shot reasoning", reasoning=True, stream_id="r2"),
ProgressEvent(content="ordinary progress"),
]
messages = [
outbound_message_for_event(channel="mock", chat_id="c1", event=event)
for event in events
]
for msg in messages:
await manager.bus.publish_outbound(msg)
await _pump_one(manager)
final = await _dispatch_through_final(manager)
channel._delta_mock.assert_not_awaited()
channel._end_mock.assert_not_awaited()
channel._send_mock.assert_not_awaited()
@pytest.mark.asyncio
async def test_dispatch_delivers_reasoning_when_channel_opts_in(manager):
channel = manager.channels["mock"]
channel.show_reasoning = True
for chunk in ("first ", "second"):
await manager.bus.publish_outbound(outbound_message_for_event(
channel="mock",
chat_id="c1",
event=ProgressEvent(content=chunk, reasoning_delta=True, stream_id="r1"),
))
await manager.bus.publish_outbound(outbound_message_for_event(
channel="mock",
chat_id="c1",
event=ProgressEvent(reasoning_end=True, stream_id="r1"),
))
await _pump_one(manager)
assert channel._delta_mock.await_count == 2
channel._end_mock.assert_awaited_once()
expected = []
if show_reasoning:
expected.extend([
("delta", "c1", "first ", messages[0].metadata, "r1"),
("delta", "c1", "second", messages[1].metadata, "r1"),
("end", "c1", messages[2].metadata, "r1"),
("delta", "c1", "one-shot reasoning", messages[3].metadata, "r2"),
("end", "c1", messages[3].metadata, "r2"),
])
if send_progress:
expected.append(("send", messages[-1]))
assert channel.received == [*expected, ("send", final)]
@pytest.mark.asyncio
async def test_dispatch_silently_drops_reasoning_for_unknown_channel(manager):
msg = outbound_message_for_event(
await manager.bus.publish_outbound(outbound_message_for_event(
channel="ghost",
chat_id="c1",
event=ProgressEvent(content="nobody home", reasoning_delta=True),
)
await manager.bus.publish_outbound(msg)
event=ProgressEvent(content="nobody home", reasoning_delta=True, stream_id="ghost-r1"),
))
await _pump_one(manager)
final = await _dispatch_through_final(manager)
manager.channels["mock"]._delta_mock.assert_not_awaited()
manager.channels["mock"]._send_mock.assert_not_awaited()
channel = manager.channels["mock"]
assert channel.received == [("send", final)]
channel._delta_mock.assert_not_awaited()
channel._end_mock.assert_not_awaited()
@pytest.mark.asyncio
@@ -259,41 +267,24 @@ async def test_base_channel_file_edit_events_are_noop_safe():
assert await channel.send_file_edit_events("c", [{"path": "a.py"}]) is None
@pytest.mark.asyncio
async def test_reasoning_routing_does_not_consult_send_progress(manager):
"""`show_reasoning` is orthogonal to `send_progress` — turning off
progress streaming must not silence reasoning."""
channel = manager.channels["mock"]
channel.send_progress = False
channel.show_reasoning = True
await manager.bus.publish_outbound(outbound_message_for_event(
channel="mock",
chat_id="c1",
event=ProgressEvent(content="still surfaces", reasoning_delta=True),
))
async def _dispatch_through_final(manager: ChannelManager) -> OutboundMessage:
"""A same-destination send acknowledges completion of earlier callbacks."""
final = OutboundMessage(channel="mock", chat_id="c1", content="Final")
delivered = asyncio.Event()
await _pump_one(manager)
def record_send(msg):
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "c1", "Final", None):
delivered.set()
channel._delta_mock.assert_awaited_once()
async def _pump_one(manager: ChannelManager) -> None:
"""Process currently queued messages through the reasoning dispatch branch."""
async def dispatch_one(msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, ProgressEvent) and (
event.reasoning_delta
or event.reasoning_end
or event.reasoning
):
channel = manager.channels.get(msg.channel)
if channel is not None and channel.show_reasoning:
await manager._send_with_retry(channel, msg)
await dispatch_one(await asyncio.wait_for(manager.bus.consume_outbound(), timeout=1.0))
while True:
try:
await dispatch_one(manager.bus.outbound.get_nowait())
except asyncio.QueueEmpty:
break
manager.channels["mock"]._send_mock.side_effect = record_send
await manager.bus.publish_outbound(final)
task = asyncio.create_task(manager._dispatch_outbound())
try:
await asyncio.wait_for(delivered.wait(), timeout=2)
finally:
task.cancel()
with suppress(asyncio.CancelledError):
await asyncio.wait_for(task, timeout=2)
assert not manager._outbound_tasks
assert not manager._outbound_tails
return final
@@ -1,67 +1,150 @@
"""Executable architecture constraints for the WebSocket transport adapter."""
"""Behavioral delegation and executable ownership boundaries for WebSocket."""
from __future__ import annotations
import ast
import asyncio
from pathlib import Path
from unittest.mock import AsyncMock
import pytest
from websockets.datastructures import Headers
from websockets.http11 import Request, Response
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket import runtime
from nanobot.webui.gateway_services import build_gateway_services
_REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
_RUNTIME_PATH = _REPOSITORY_ROOT / "nanobot" / "channels" / "websocket" / "runtime.py"
_SESSION_IDENTITY_PATH = _REPOSITORY_ROOT / "nanobot" / "webui" / "session_identity.py"
def _channel_method(name: str) -> ast.AsyncFunctionDef:
tree = ast.parse(_RUNTIME_PATH.read_text(encoding="utf-8"))
channel = next(
node
for node in tree.body
if isinstance(node, ast.ClassDef) and node.name == "WebSocketChannel"
@pytest.fixture
async def channel(tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
config = runtime.WebSocketConfig(allow_from=["client-1"], websocket_requires_token=False)
bus = MessageBus()
gateway = build_gateway_services(
config=config,
bus=bus,
session_manager=None,
static_dist_path=None,
workspace_path=tmp_path,
default_restrict_to_workspace=True,
config_path=tmp_path / "config.json",
runtime_model_name=None,
runtime_surface="browser",
runtime_capabilities_overrides=None,
)
return next(
node
for node in channel.body
if isinstance(node, ast.AsyncFunctionDef) and node.name == name
channel = runtime.WebSocketChannel(config, bus, gateway=gateway)
try:
yield channel
finally:
async with asyncio.timeout(2):
await channel.stop()
assert channel._server_task is None
assert not channel._connection_outbound
assert not channel._outbound_retire_tasks
assert not channel._commands.request_tasks
async def test_send_delegates_the_outbound_message_to_the_projector(channel, monkeypatch):
send = AsyncMock()
hydrate = AsyncMock()
monkeypatch.setattr(channel._outbound, "send", send)
monkeypatch.setattr(channel._outbound, "hydrate", hydrate)
msg = OutboundMessage(
channel="websocket", chat_id="chat-1", content="hello", reply_to="m1",
media=["/example/image.png"], metadata={"turn_id": "turn-1"},
)
await channel.send(msg)
def _statements_without_docstring(node: ast.AsyncFunctionDef) -> list[ast.stmt]:
body = list(node.body)
if (
body
and isinstance(body[0], ast.Expr)
and isinstance(body[0].value, ast.Constant)
and isinstance(body[0].value.value, str)
):
body.pop(0)
return body
send.assert_awaited_once_with(msg)
hydrate.assert_not_awaited()
def test_business_entrypoints_are_thin_transport_delegations() -> None:
for method_name in ("_dispatch_envelope", "_hydrate_after_subscribe", "send"):
statements = _statements_without_docstring(_channel_method(method_name))
assert len(statements) == 1, method_name
assert isinstance(statements[0], ast.Expr), method_name
assert isinstance(statements[0].value, ast.Await), method_name
async def test_subscribe_hydration_delegates_the_requested_chat(channel, monkeypatch):
hydrate = AsyncMock()
send = AsyncMock()
monkeypatch.setattr(channel._outbound, "hydrate", hydrate)
monkeypatch.setattr(channel._outbound, "send", send)
statements = _statements_without_docstring(_channel_method("_dispatch_http"))
assert len(statements) == 1
assert isinstance(statements[0], ast.Return)
assert isinstance(statements[0].value, ast.Await)
await channel._hydrate_after_subscribe("chat-2")
hydrate.assert_awaited_once_with("chat-2")
send.assert_not_awaited()
async def test_envelope_delegates_connection_client_and_payload_to_application(channel, monkeypatch):
dispatch = AsyncMock()
monkeypatch.setattr(channel._commands, "dispatch", dispatch)
connection = AsyncMock()
envelope = {"type": "subscribe", "chat_id": "chat-2"}
await channel._dispatch_envelope(connection, "client-1", envelope)
dispatch.assert_awaited_once_with(connection, "client-1", envelope)
@pytest.mark.parametrize("allow_upgrade", [False, True])
async def test_http_delegates_authorization_and_preserves_endpoint_result(
channel, monkeypatch, allow_upgrade,
):
response = None if allow_upgrade else Response(
403, "Forbidden", Headers({"Content-Type": "text/plain"}), b"access denied",
)
process_request = AsyncMock(return_value=response)
monkeypatch.setattr(channel.gateway.endpoint, "process_request", process_request)
connection = AsyncMock()
request = Request("/webui/thread?chat_id=chat-2", Headers())
result = await channel._dispatch_http(connection, request)
assert result is response
process_request.assert_awaited_once_with(connection, request, is_allowed=channel.is_allowed)
authorize = process_request.await_args.kwargs["is_allowed"]
assert authorize("client-1") is True
assert authorize("other-client") is False
def _session_namespace_literal_lines(source: str) -> list[int]:
"""Locate executable namespace literals, not prose or type annotations."""
tree = ast.parse(source)
ignored = set()
for node in ast.walk(tree):
annotation = None
if isinstance(node, ast.AnnAssign | ast.arg):
annotation = node.annotation
elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
annotation = node.returns
if annotation is not None:
ignored.update(ast.walk(annotation))
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
# A standalone string (including a docstring) does not define runtime policy.
ignored.add(node.value)
return [
node.lineno
for node in ast.walk(tree)
if isinstance(node, ast.Constant)
and isinstance(node.value, str)
and node.value.startswith("websocket:")
and node not in ignored
]
def test_persisted_webui_session_prefix_has_one_production_owner() -> None:
owners = []
# Consumers import session_identity; independent literal keys/prefixes fork its policy.
# Exact persisted values and mapping round trips live in test_session_identity.py.
owners = {}
for path in (_REPOSITORY_ROOT / "nanobot").rglob("*.py"):
if "tests" in path.parts or path == _SESSION_IDENTITY_PATH:
if "tests" in path.parts:
continue
if "websocket:" in path.read_text(encoding="utf-8"):
owners.append(path.relative_to(_REPOSITORY_ROOT).as_posix())
assert owners == []
assert 'WEBUI_SESSION_STORAGE_PREFIX = "websocket:"' in _SESSION_IDENTITY_PATH.read_text(
encoding="utf-8"
)
lines = _session_namespace_literal_lines(path.read_text(encoding="utf-8"))
if lines:
owners[path.relative_to(_REPOSITORY_ROOT).as_posix()] = lines
assert set(owners) == {_SESSION_IDENTITY_PATH.relative_to(_REPOSITORY_ROOT).as_posix()}, owners
def test_runtime_exports_compatibility_protocol_helpers() -> None:
+1 -1
View File
@@ -2593,7 +2593,7 @@ def test_webui_missing_runtime_env_fails_before_starting_gateway(
assert result.exit_code == 1
assert missing_env in result.stdout
assert "nanobot status --config" in result.stdout
assert config_file.name in result.stdout
assert config_file.name in _without_rendered_line_breaks(result.stdout)
assert "Traceback" not in result.stdout
assert f"${{{missing_env}}}" in config_file.read_text(encoding="utf-8")
+9 -10
View File
@@ -12,11 +12,6 @@ def test_commands_keeps_safe_file_history_import_compatible() -> None:
class TestSanitizeSurrogates:
def test_paired_surrogates_reconstructed(self):
"""Windows console produces \\ud83d\\udc08 for U+1F408 — must be restored."""
result = _sanitize_surrogates("你为什么会用 🐈")
assert result == "你为什么会用 🐈"
def test_lone_surrogates_replaced(self):
result = _sanitize_surrogates("hello \udce9 world")
assert "\udce9" not in result
@@ -56,11 +51,15 @@ class TestSafeFileHistory:
entries = list(hist.load_history_strings())
assert entries[0] == "normal ascii text"
def test_emoji_preserved(self, tmp_path):
hist = SafeFileHistory(str(tmp_path / "history"))
hist.store_string("hello 🐈 nanobot")
entries = list(hist.load_history_strings())
assert entries[0] == "hello 🐈 nanobot"
def test_windows_surrogate_pair_round_trips_as_emoji(self, tmp_path):
"""Raw UTF-16 console input must survive a UTF-8 history write and reload."""
history_path = tmp_path / "history"
hist = SafeFileHistory(str(history_path))
hist.store_string("hello \ud83d\udc08 nanobot")
history_path.read_bytes().decode("utf-8") # Strict decoding must not raise.
reloaded = SafeFileHistory(str(history_path))
assert list(reloaded.load_history_strings()) == ["hello 🐈 nanobot"]
def test_mixed_unicode_preserved(self, tmp_path):
"""CJK + emoji + latin should all pass through cleanly."""
+14 -2
View File
@@ -174,9 +174,15 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:
store = _FakeStore(_FakeGit(initialized=False), dream_prompt_result=("dream prompt", 123))
bus = _FakeBus()
calls = []
progress_sentinel = "private Dream progress sentinel"
async def process_direct(*args, **kwargs):
calls.append((args, kwargs))
await kwargs["on_progress"](progress_sentinel)
await kwargs["on_progress"](
"",
tool_events=[{"phase": "start", "name": "edit_file", "hint": progress_sentinel}],
)
return OutboundMessage(
channel="cli",
chat_id="direct",
@@ -194,11 +200,17 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:
)
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
await _run_dream_command(ctx)
immediate = await _run_dream_command(ctx)
assert immediate.content == "Dreaming..."
assert (immediate.channel, immediate.chat_id) == ("feishu", "chat1")
assert len(calls) == 1
assert callable(calls[0][1]["on_progress"])
assert calls[0][1]["runtime"] is dream_runtime
assert len(bus.outbound) == 1
completion = bus.outbound[0]
assert (completion.channel, completion.chat_id) == ("feishu", "chat1")
assert completion.content.startswith("Dream completed")
assert progress_sentinel not in completion.content
def _build_runnable_dream(
+1 -10
View File
@@ -92,6 +92,7 @@ async def test_model_command_lists_current_and_available_presets(tmp_path) -> No
@pytest.mark.asyncio
async def test_model_command_switches_preset(tmp_path) -> None:
loop = _make_loop(tmp_path)
assert loop.tools_config.my.allow_set is False
out = await cmd_model(_ctx(loop, "/model fast", args="fast"))
@@ -172,16 +173,6 @@ async def test_model_command_reports_provider_configuration_errors(tmp_path) ->
assert "No API key configured for provider 'openai'." in status.content
@pytest.mark.asyncio
async def test_model_command_does_not_depend_on_my_allow_set(tmp_path) -> None:
loop = _make_loop(tmp_path)
assert loop.tools_config.my.allow_set is False
await cmd_model(_ctx(loop, "/model fast", args="fast"))
assert _saved_model_preset(loop) == "fast"
@pytest.mark.asyncio
async def test_model_command_registered_as_exact_and_prefix(tmp_path) -> None:
router = CommandRouter()
+75 -51
View File
@@ -1,11 +1,14 @@
"""Test Azure OpenAI provider (Responses API via OpenAI SDK)."""
import json
import sys
import time
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, call, patch
import httpx
import pytest
from openai import AsyncOpenAI
from nanobot.providers.azure_openai_provider import (
AzureOpenAIProvider,
@@ -79,79 +82,100 @@ def _install_fake_azure_identity(monkeypatch, credential_factory):
monkeypatch.setitem(sys.modules, "azure.identity.aio", aio_mod)
def test_init_missing_key_uses_aad_token_provider(monkeypatch):
"""Empty api_key falls back to DefaultAzureCredential via _AzureTokenProvider."""
credential_instance = MagicMock()
credential_factory = MagicMock(return_value=credential_instance)
_install_fake_azure_identity(monkeypatch, credential_factory)
@pytest.fixture
async def azure_wire_requests(monkeypatch):
"""Inject only the HTTP transport; keep the SDK's request/auth path real."""
requests: list[httpx.Request] = []
provider = AzureOpenAIProvider(
api_key="", api_base="https://res.openai.azure.com",
)
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
body = json.loads(request.content)
return httpx.Response(200, json={
"id": f"resp_{len(requests)}", "object": "response", "created_at": 1,
"status": "completed", "model": body["model"],
"output": [{
"type": "message", "id": f"msg_{len(requests)}",
"role": "assistant", "status": "completed",
"content": [{
"type": "output_text", "text": f"reply {len(requests)}", "annotations": [],
}],
}],
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
})
assert provider._token_provider is not None
assert isinstance(provider._token_provider, _AzureTokenProvider)
# DefaultAzureCredential must have been instantiated exactly once
credential_factory.assert_called_once_with()
assert provider._token_provider._credential is credential_instance
# The token provider must be wired into the OpenAI SDK as its
# ``_api_key_provider`` callable — that's what the SDK invokes per
# request to refresh the bearer token.
assert provider._client._api_key_provider is provider._token_provider
# Static api_key starts empty until the first refresh.
assert provider._client.api_key == ""
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
def create_client(**kwargs):
return AsyncOpenAI(http_client=http_client, **kwargs)
monkeypatch.setattr("nanobot.providers.azure_openai_provider.AsyncOpenAI", create_client)
yield requests
@pytest.mark.asyncio
async def test_aad_token_provider_wires_into_sdk_auth_headers(monkeypatch):
"""Regression guard: the token provider must be wired into the
OpenAI SDK so ``_refresh_api_key`` pulls a fresh token and the
bearer ends up in ``auth_headers``. Without this, a refactor that
constructs ``_AzureTokenProvider`` but forgets to pass it to
``AsyncOpenAI`` would silently send unauthenticated requests.
"""
access_token = SimpleNamespace(token="token-A", expires_on=time.time() + 3600)
async def test_aad_token_provider_sends_rotating_bearer_tokens_on_chat_requests(
monkeypatch, azure_wire_requests,
):
credential_instance = MagicMock()
credential_instance.get_token = AsyncMock(return_value=access_token)
credential_instance.get_token = AsyncMock(side_effect=[
SimpleNamespace(token="token-A", expires_on=time.time() + 3600),
SimpleNamespace(token="token-B", expires_on=time.time() + 3600),
])
credential_instance.close = AsyncMock()
credential_factory = MagicMock(return_value=credential_instance)
_install_fake_azure_identity(monkeypatch, credential_factory)
provider = AzureOpenAIProvider(
api_key="", api_base="https://res.openai.azure.com",
api_key="", api_base="https://res.openai.azure.com", default_model="gpt-4o-deployment",
)
try:
responses = [
await provider.chat([{"role": "user", "content": f"turn {turn}"}])
for turn in (1, 2)
]
finally:
await provider.aclose()
assert provider._client.api_key == ""
assert provider._client.auth_headers == {}
await provider._client._refresh_api_key()
assert provider._client.api_key == "token-A"
assert provider._client.auth_headers == {"Authorization": "Bearer token-A"}
credential_instance.get_token.assert_awaited_with(
"https://cognitiveservices.azure.com/.default"
assert [response.content for response in responses] == ["reply 1", "reply 2"]
assert all(response.finish_reason == "stop" for response in responses)
assert len(azure_wire_requests) == 2
assert [request.headers.get("Authorization") for request in azure_wire_requests] == [
"Bearer token-A", "Bearer token-B",
]
assert all(request.method == "POST" for request in azure_wire_requests)
assert all(
str(request.url) == "https://res.openai.azure.com/openai/v1/responses"
for request in azure_wire_requests
)
# Rotated token on second refresh proves per-request delegation (no client-side caching).
credential_instance.get_token = AsyncMock(
return_value=SimpleNamespace(token="token-B", expires_on=time.time() + 3600)
)
await provider._client._refresh_api_key()
assert provider._client.auth_headers == {"Authorization": "Bearer token-B"}
bodies = [json.loads(request.content) for request in azure_wire_requests]
assert [body["model"] for body in bodies] == ["gpt-4o-deployment", "gpt-4o-deployment"]
assert [body["input"][0]["content"][0]["text"] for body in bodies] == ["turn 1", "turn 2"]
credential_factory.assert_called_once_with()
assert credential_instance.get_token.await_args_list == [
call("https://cognitiveservices.azure.com/.default"),
call("https://cognitiveservices.azure.com/.default"),
]
def test_init_explicit_key_does_not_construct_credential(monkeypatch):
"""Explicit api_key wins; DefaultAzureCredential must never be touched."""
@pytest.mark.asyncio
async def test_explicit_key_sends_bearer_without_constructing_credential(
monkeypatch, azure_wire_requests,
):
"""Explicit api_key wins through chat(), without invoking Azure credentials."""
credential_factory = MagicMock(side_effect=AssertionError(
"DefaultAzureCredential must not be constructed when api_key is set"
))
_install_fake_azure_identity(monkeypatch, credential_factory)
provider = AzureOpenAIProvider(
api_key="real-key", api_base="https://res.openai.azure.com",
)
try:
response = await provider.chat([{"role": "user", "content": "hello"}])
finally:
await provider.aclose()
assert provider._token_provider is None
assert response.content == "reply 1"
assert response.finish_reason == "stop"
assert len(azure_wire_requests) == 1
assert azure_wire_requests[0].headers["Authorization"] == "Bearer real-key"
credential_factory.assert_not_called()
-16
View File
@@ -168,22 +168,6 @@ class TestBuildKwargsExtraBody:
assert body.get("custom_param") == "value"
assert body["thinking"] == {"type": "enabled"}
def test_nested_extra_body_does_not_clobber_siblings(self) -> None:
"""Nested dict merge should preserve sibling keys."""
provider = _make_provider({
"chat_template_kwargs": {"enable_thinking": False},
})
# Simulate internal code having set a sibling key
# by manually calling _build_kwargs — the internal logic
# doesn't set chat_template_kwargs, so we test the merge path
# by having extra_body itself contain nested keys
kwargs = provider._build_kwargs(
messages=_simple_messages(),
tools=None, model=None, max_tokens=100,
temperature=0.1, reasoning_effort=None, tool_choice=None,
)
assert kwargs["extra_body"]["chat_template_kwargs"]["enable_thinking"] is False
def test_guided_json_injection(self) -> None:
"""Real-world use case: vLLM guided decoding."""
schema = {"type": "object", "properties": {"name": {"type": "string"}}}
@@ -12,11 +12,13 @@ from nanobot.providers import github_copilot_provider as gc
@pytest.mark.asyncio
async def test_concurrent_token_refresh_fetches_once(monkeypatch):
"""Two concurrent _get_copilot_access_token calls should trigger only one
HTTP fetch when the token is expired, not two."""
"""A competing caller waits for the in-flight exchange and reuses its token."""
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
fetch_count = 0
entered = asyncio.Event()
release = asyncio.Event()
competing_started = asyncio.Event()
class FakeResponse:
def raise_for_status(self):
@@ -38,82 +40,37 @@ async def test_concurrent_token_refresh_fetches_once(monkeypatch):
async def get(self, url, *, headers):
nonlocal fetch_count
fetch_count += 1
# Simulate network latency so both coroutines overlap before the
# lock serializes them.
await asyncio.sleep(0.05)
entered.set()
await release.wait()
return FakeResponse()
monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)
provider = gc.GitHubCopilotProvider()
# Force token expiry.
provider._copilot_access_token = None
provider._copilot_expires_at = 0.0
token_a, token_b = await asyncio.gather(
provider._get_copilot_access_token(),
provider._get_copilot_access_token(),
)
async def competing_call():
# No suspension between this signal and entering the token path.
competing_started.set()
return await provider._get_copilot_access_token()
assert token_a == "copilot-token"
assert token_b == "copilot-token"
assert fetch_count == 1, (
f"Expected exactly 1 token fetch under concurrency, got {fetch_count}"
)
@pytest.mark.asyncio
async def test_second_call_returns_cached_token_while_first_in_flight(monkeypatch):
"""If task A is mid-fetch inside the lock, task B should wait, then find
the cached token and skip the HTTP call entirely."""
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
fetch_count = 0
class FakeResponse:
def raise_for_status(self):
pass
def json(self):
return {"token": "cached-token", "refresh_in": 1500}
class FakeAsyncClient:
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def get(self, url, *, headers):
nonlocal fetch_count
fetch_count += 1
await asyncio.sleep(0.1)
return FakeResponse()
monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)
provider = gc.GitHubCopilotProvider()
provider._copilot_access_token = None
provider._copilot_expires_at = 0.0
# Start task A, let it acquire the lock and begin the HTTP fetch.
task_a = asyncio.create_task(provider._get_copilot_access_token())
await asyncio.sleep(0.02) # task A is now inside the lock, mid-fetch
tasks = [task_a]
try:
await asyncio.wait_for(entered.wait(), timeout=5)
task_b = asyncio.create_task(competing_call())
tasks.append(task_b)
await asyncio.wait_for(competing_started.wait(), timeout=5)
assert not task_a.done()
assert not task_b.done()
assert fetch_count == 1
# Task B starts while A is still in flight.
token_b = await provider._get_copilot_access_token()
token_a = await task_a
assert token_a == "cached-token"
assert token_b == "cached-token"
assert fetch_count == 1
@pytest.mark.asyncio
async def test_copilot_token_lock_exists():
"""Provider should have an asyncio.Lock for token refresh."""
provider = gc.GitHubCopilotProvider()
assert isinstance(provider._copilot_token_lock, asyncio.Lock)
release.set()
tokens = await asyncio.wait_for(asyncio.gather(*tasks), timeout=5)
assert tokens == ["copilot-token", "copilot-token"]
assert fetch_count == 1
finally:
release.set()
for task in tasks:
if not task.done():
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await provider.aclose()
+38 -8
View File
@@ -1,8 +1,12 @@
from __future__ import annotations
import asyncio
import json
import sqlite3
import threading
from collections.abc import Callable, Iterator
from contextlib import closing
from dataclasses import asdict
from types import SimpleNamespace
import pytest
@@ -127,18 +131,30 @@ async def test_observer_receives_every_retry_attempt(stream: bool) -> None:
@pytest.mark.asyncio
async def test_observer_estimates_missing_success_usage_without_storing_content() -> None:
provider = _SequenceProvider(iter([LLMResponse(content="hello")]))
prompt = "observer-prompt-canary-38a7cf"
reply = "observer-response-canary-92b6de"
provider = _SequenceProvider(iter([LLMResponse(content=reply)]))
events: list[LLMCallRecord] = []
provider.set_llm_call_observer(events.append)
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}],
messages=[{"role": "user", "content": prompt}],
)
assert response.content == reply
assert response.finish_reason == "stop"
assert provider.calls == 1
assert len(events) == 1
assert events[0].finish_reason == "stop"
assert response.usage is not None
assert response.usage.source == "estimated"
assert response.usage.input_tokens > 0
assert response.usage.output_tokens > 0
assert response.usage.estimated_tokens == response.usage.total_tokens > 0
assert events[0].usage == response.usage
assert "content" not in LLMCallRecord.__dataclass_fields__
serialized = json.dumps(asdict(events[0]))
assert prompt not in serialized
assert reply not in serialized
@pytest.mark.asyncio
@@ -342,26 +358,40 @@ async def test_usage_fast_paths_skip_local_estimation(stream: bool, kind: str) -
async def test_gateway_usage_observer_records_missing_usage_and_retry(
monkeypatch, tmp_path, stream: bool,
) -> None:
prompt = "gateway-prompt-canary-f6d5a4"
reply = "gateway-response-canary-27be91"
error = "gateway-error-canary-64a8cd"
store = LLMUsageStore(tmp_path / "usage.sqlite3")
monkeypatch.setattr("nanobot.llm_usage.service.get_llm_usage_store", lambda: store)
provider = _SequenceProvider(iter([
LLMResponse(content="temporary failure", finish_reason="error", error_kind="timeout"),
LLMResponse(content="hello"),
LLMResponse(content=error, finish_reason="error", error_kind="timeout"),
LLMResponse(content=reply),
]))
provider.set_llm_call_observer(record_llm_call)
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
try:
with llm_usage_source("api"):
response = await call(messages=[{"role": "user", "content": "hello"}])
assert response.content == "hello"
response = await call(messages=[{"role": "user", "content": prompt}])
assert response.content == reply
assert response.usage is not None and response.usage.source == "estimated"
assert response.usage.input_tokens > 0
assert response.usage.output_tokens > 0
assert response.usage.estimated_tokens == response.usage.total_tokens > 0
assert provider.calls == 2
records = list(reversed(store.recent_calls()))
with closing(sqlite3.connect(store.path)) as connection:
connection.row_factory = sqlite3.Row
records = [dict(row) for row in connection.execute("SELECT * FROM llm_calls ORDER BY id")]
assert len(records) == 2
assert [record["finish_reason"] for record in records] == ["error", "stop"]
assert records[0]["error_kind"] == "timeout"
assert all(record["source"] == "api" for record in records)
assert all(record["stream"] == int(stream) for record in records)
assert records[0]["total_tokens"] is None
assert records[1]["total_tokens"] == response.usage.total_tokens
assert records[1]["estimated_tokens"] == response.usage.estimated_tokens
serialized = json.dumps(records)
for canary in (prompt, reply, error):
assert canary not in serialized
finally:
store.close()
+88 -99
View File
@@ -88,33 +88,19 @@ async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeyp
assert request_contexts == [context, context, context]
class _WarningCaptureLogger:
def __init__(self) -> None:
self.calls: list[tuple[str, tuple[Any, ...]]] = []
def warning(self, *args: Any, **kwargs: Any) -> None:
self.calls.append((args[0], args[1:]))
def exception(self, message: str, *args: Any, **kwargs: Any) -> None:
raise AssertionError("Codex diagnostics must not log exception tracebacks")
def _capture_codex_warnings(monkeypatch: pytest.MonkeyPatch) -> _WarningCaptureLogger:
capture = _WarningCaptureLogger()
monkeypatch.setattr("nanobot.providers.openai_codex_provider.logger", capture)
return capture
def test_codex_blank_timeout_root_cause_reproduction() -> None:
"""Document why upstream produced a bare ``Error calling Codex:`` message."""
exc = httpx.ReadTimeout("")
legacy_content = f"Error calling Codex: {exc}"
assert str(exc) == ""
assert legacy_content == "Error calling Codex: "
legacy_response = provider_base.LLMResponse(content=legacy_content, finish_reason="error")
assert legacy_response.error_kind is None
assert legacy_response.error_should_retry is None
@pytest.fixture
def codex_warning_log(monkeypatch):
monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)
sink = io.StringIO()
logger.enable("nanobot")
handler_id = logger.add(
sink, format="{message}", level="WARNING",
filter="nanobot.providers.openai_codex_provider", backtrace=True, diagnose=True,
)
try:
yield sink
finally:
logger.remove(handler_id)
def test_codex_http_friendly_error_omits_raw_body() -> None:
@@ -245,10 +231,9 @@ async def test_codex_title_failure_logs_request_purpose_and_safe_upstream_detail
@pytest.mark.asyncio
@pytest.mark.parametrize("failed_stage", ["codex_compaction", "codex_request"])
async def test_codex_diagnostics_distinguish_compaction_from_following_request(
monkeypatch, failed_stage,
monkeypatch, codex_warning_log, failed_stage,
) -> None:
_mock_codex_token(monkeypatch)
capture = _capture_codex_warnings(monkeypatch)
state_provider = "openai_codex:https://chatgpt.com/backend-api/codex/responses"
state = build_responses_state(
provider=state_provider, model="gpt-5.6-sol",
@@ -278,14 +263,17 @@ async def test_codex_diagnostics_distinguish_compaction_from_following_request(
),
)
assert response.finish_reason == "error"
template, args = capture.calls[-1]
log = template.format(*args)
logs = codex_warning_log.getvalue().splitlines()
assert len(logs) == 1
log = logs[0]
assert f"stage={failed_stage}" in log
assert f"compaction_applied={failed_stage == 'codex_request'}" in log
assert "replayed=True" in log
assert "reasoning_effort=low" in log
assert "error_param=input[1].type" in log
assert "request_id=req-compaction-test" in log
assert "PRIVATE STATE" not in log
assert "Traceback" not in log
@pytest.mark.asyncio
@@ -623,47 +611,38 @@ async def test_codex_provider_passes_proxy_to_oauth_and_response_request(monkeyp
@pytest.mark.asyncio
async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch) -> None:
log_capture = _capture_codex_warnings(monkeypatch)
async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch, codex_warning_log) -> None:
_mock_codex_token(monkeypatch)
prompt = "timeout-prompt-canary-38bc7a"
async def fake_request(*args: Any, **kwargs: Any):
async def fake_request(_url, _headers, body, **_kwargs):
assert body["input"][0]["content"][0]["text"] == prompt
raise httpx.ReadTimeout("")
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
provider = OpenAICodexProvider()
response = await provider.chat([{"role": "user", "content": "hello"}])
response = await provider.chat(
[{"role": "user", "content": prompt}],
model="openai-codex/gpt-5.6-sol", reasoning_effort="high",
)
assert response.content == (
"Error calling Codex (ReadTimeout): timed out waiting for response"
)
assert log_capture.calls == [
(
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
"error_type={} error_code={} retry_after={} summary={} "
"model={} reasoning_effort={} replayed={} compaction_applied={} "
"error_param={} error_message={} request_id={}",
(
"codex_request",
"ReadTimeout",
"timeout",
True,
None,
None,
None,
None,
"ReadTimeout timeout",
"gpt-5.6-sol",
None,
False,
False,
None,
None,
None,
),
)
]
logs = codex_warning_log.getvalue().splitlines()
assert len(logs) == 1
log = logs[0]
for field in (
"Codex API request failed", "stage=codex_request", "type=ReadTimeout",
"kind=timeout", "retryable=True", "status=None", "error_type=None",
"error_code=None", "retry_after=None", "summary=ReadTimeout timeout",
"model=gpt-5.6-sol", "reasoning_effort=high", "replayed=False",
"compaction_applied=False", "error_param=None", "error_message=None", "request_id=None",
):
assert field in log
assert prompt not in log
assert "Traceback" not in log
@pytest.mark.asyncio
@@ -751,50 +730,60 @@ async def test_codex_http_error_preserves_status_and_retry_after(monkeypatch) ->
@pytest.mark.asyncio
async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch) -> None:
log_capture = _capture_codex_warnings(monkeypatch)
async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch, codex_warning_log) -> None:
_mock_codex_token(monkeypatch)
original_client = httpx.AsyncClient
prompt = "http-prompt-canary-471fde"
upstream_body = "http-upstream-body-canary-639ca2"
requests: list[httpx.Request] = []
async def fake_request(*args: Any, **kwargs: Any):
raise _CodexHTTPError(
_friendly_error(500, "raw upstream body with PRIVATE PROMPT MUST NOT APPEAR"),
status_code=500,
error_type="server_error",
error_code="overloaded",
)
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
assert prompt.encode() in request.content
return httpx.Response(500, headers={
"retry-after": "2.5", "x-request-id": "req-http-diagnostic",
}, json={
"error": {
"type": "server_error", "code": "overloaded",
"param": "input[0].content", "message": upstream_body,
},
"private": upstream_body,
})
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
def fake_client(**kwargs):
return original_client(transport=httpx.MockTransport(handler))
monkeypatch.setattr("nanobot.providers.openai_codex_provider.httpx.AsyncClient", fake_client)
provider = OpenAICodexProvider()
response = await provider.chat([{"role": "user", "content": "hello"}])
assert response.content == "Error calling Codex (CodexHTTPError): HTTP 500: Codex API request failed"
assert log_capture.calls == [
(
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
"error_type={} error_code={} retry_after={} summary={} "
"model={} reasoning_effort={} replayed={} compaction_applied={} "
"error_param={} error_message={} request_id={}",
(
"codex_request",
"CodexHTTPError",
"http",
True,
500,
"server_error",
"overloaded",
None,
"HTTP 500 type=server_error code=overloaded",
"gpt-5.6-sol",
None,
False,
False,
None,
None,
None,
),
try:
response = await provider.chat(
[{"role": "user", "content": prompt}],
model="openai-codex/gpt-5.6-sol", reasoning_effort="high",
)
]
finally:
await provider.aclose()
assert len(requests) == 1
assert response.finish_reason == "error"
assert response.content == "Error calling Codex (CodexHTTPError): HTTP 500: Codex API request failed"
assert response.error_status_code == 500
assert response.error_should_retry is True
logs = codex_warning_log.getvalue().splitlines()
assert len(logs) == 1
log = logs[0]
for field in (
"Codex API request failed", "stage=codex_request", "type=CodexHTTPError",
"kind=http", "retryable=True", "status=500", "error_type=server_error",
"error_code=overloaded", "retry_after=2.5",
"summary=HTTP 500 type=server_error code=overloaded", "model=gpt-5.6-sol",
"reasoning_effort=high", "replayed=False", "compaction_applied=False",
"error_param=input[0].content", "error_message=None", "request_id=req-http-diagnostic",
):
assert field in log
for secret in (prompt, upstream_body):
assert secret not in log
assert secret not in response.content
assert "Traceback" not in log
@pytest.mark.asyncio
+8 -4
View File
@@ -62,17 +62,18 @@ class TestSanitizeSurrogatesDeep:
"role": "user",
"content": [
{"type": "text", "text": "hello \ud83e world"},
{"type": "text", "text": "normal"},
{"type": "text", "text": "normal 🤖"},
],
}
cleaned = sanitize_surrogates_deep(dirty)
assert cleaned is not dirty # rebuilt
first = cleaned["content"][0]["text"]
assert "\ud83e" not in first
assert cleaned["content"][1]["text"] == "normal 🤖"
# Full payload must be UTF-8 encodable.
import json
json.dumps(cleaned).encode("utf-8")
json.dumps(cleaned, ensure_ascii=False).encode("utf-8")
def test_paired_surrogates_in_list_collapse_to_emoji(self):
dirty = ["a", "b \ud83e\udd16", "c"]
@@ -150,13 +151,16 @@ class TestProviderSanitizeEmptyContent:
{
"role": "assistant",
"content": [
{"type": "text", "text": "answer with a lone \ud83e half"},
{"type": "text", "text": "answer with a lone \ud83e half and paired \ud83e\udd16"},
],
},
]
cleaned = LLMProvider._sanitize_empty_content(messages)
# This is the operation that previously raised UnicodeEncodeError.
json.dumps({"model": "x", "messages": cleaned}).encode("utf-8")
json.dumps({"model": "x", "messages": cleaned}, ensure_ascii=False).encode("utf-8")
assert cleaned[0]["content"] == "You are a 🐱 assistant."
assert cleaned[1]["content"] == "🤖 fixed?"
assert cleaned[2]["content"][0]["text"] == "answer with a lone \ufffd half and paired 🤖"
class TestBackwardCompatReExport:
-32
View File
@@ -418,38 +418,6 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_openai_retries_on_5xx_then_succeeds(audio_file: Path) -> None:
"""Transient 503 is retried; a subsequent 200 yields the text."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(side_effect=[_response(503), _response(200, {"text": "hello"})])
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
result = await provider.transcribe(audio_file)
assert result == "hello"
assert post.await_count == 2
@pytest.mark.asyncio
async def test_openai_retries_on_429_then_succeeds(audio_file: Path) -> None:
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(side_effect=[_response(429), _response(200, {"text": "rate ok"})])
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
result = await provider.transcribe(audio_file)
assert result == "rate ok"
assert post.await_count == 2
@pytest.mark.asyncio
async def test_openai_retries_on_connect_error(audio_file: Path) -> None:
"""Network-level transient errors are retried."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(side_effect=[httpx.ConnectError("boom"), _response(200, {"text": "ok"})])
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
result = await provider.transcribe(audio_file)
assert result == "ok"
assert post.await_count == 2
@pytest.mark.asyncio
async def test_openai_does_not_retry_on_auth_error(audio_file: Path) -> None:
"""401 is the user's misconfiguration — retrying wastes time and rate-limit quota."""
+58 -16
View File
@@ -22,6 +22,15 @@ from nanobot.webui import session_list_index, transcript
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
@pytest.fixture(autouse=True)
def _isolate_webui_transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Recovery scans must discover only test-owned transcripts, not active user chats."""
webui_dir = tmp_path / "isolated-webui"
webui_dir.mkdir()
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
monkeypatch.setattr(transcript, "get_webui_dir", lambda: webui_dir)
def _persist(manager: SessionManager, session: Session) -> None:
session.metadata["webui"] = True
manager.save(session)
@@ -732,26 +741,59 @@ async def test_scan_failure_is_visible_instead_of_aborting_other_sessions(
monkeypatch: pytest.MonkeyPatch,
) -> None:
coordinator, bus, sessions = _coordinator(tmp_path)
session = sessions.get_or_create("websocket:chat")
session.metadata[PENDING_USER_TURN_KEY] = True
_persist(sessions, session)
keys = {"websocket:first", "websocket:second"}
for key in sorted(keys):
session = sessions.get_or_create(key)
session.add_message("user", f"finish {key}")
session.metadata[PENDING_USER_TURN_KEY] = True
_persist(sessions, session)
recover_session = RecoveryCoordinator._recover_session
attempted = []
async def fail(*_args: object, **_kwargs: object) -> None:
raise RuntimeError("boom")
async def fail_first(self, session: Session, chat_id: str) -> None:
attempted.append((session.key, chat_id))
if len(attempted) == 1:
raise RuntimeError("boom")
await recover_session(self, session, chat_id)
monkeypatch.setattr(RecoveryCoordinator, "_recover_session", fail)
await coordinator.scan()
monkeypatch.setattr(RecoveryCoordinator, "_recover_session", fail_first)
try:
await coordinator.scan()
state = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]
assert state["status"] == "failed"
assert state["can_continue"] is False
assert isinstance(bus.outbound.get_nowait().event, RecoveryStateEvent)
assert len(attempted) == 2
assert {key for key, _ in attempted} == keys
failed_key, failed_chat = attempted[0]
healthy_key, healthy_chat = attempted[1]
state = sessions.read_session_snapshot(failed_key).metadata[RECOVERY_METADATA_KEY]
assert state["status"] == "failed"
assert state["reason"] == "recovery_failed"
assert state["can_continue"] is False
healthy = sessions.read_session_snapshot(healthy_key)
healthy_state = healthy.metadata[RECOVERY_METADATA_KEY]
assert healthy_state["status"] == "awaiting_user"
assert healthy_state["reason"] == "restart_requires_confirmation"
assert healthy.metadata[PENDING_USER_TURN_KEY] is True
assert [message["content"] for message in healthy.messages] == [f"finish {healthy_key}"]
assert bus.inbound.empty()
messages = []
while not bus.outbound.empty():
messages.append(bus.outbound.get_nowait())
recovery_messages = [message for message in messages if isinstance(message.event, RecoveryStateEvent)]
assert [(message.channel, message.chat_id, message.event.status, message.event.recovery_id)
for message in recovery_messages] == [
("websocket", failed_chat, "failed", state["recovery_id"]),
("websocket", healthy_chat, "awaiting_user", healthy_state["recovery_id"]),
]
assert recovery_messages[0].event.can_continue is False
assert recovery_messages[1].event.reason == "restart_requires_confirmation"
with pytest.raises(RecoveryActionError, match="context is unavailable"):
await coordinator.handle_action(
"continue",
{"chat_id": "chat", "recovery_id": state["recovery_id"]},
)
with pytest.raises(RecoveryActionError, match="context is unavailable"):
await coordinator.handle_action(
"continue",
{"chat_id": failed_chat, "recovery_id": state["recovery_id"]},
)
finally:
await sessions.state.aclose()
@pytest.mark.asyncio
+21 -9
View File
@@ -293,15 +293,27 @@ async def test_detached_reads_do_not_publish_mutations(tmp_path):
async def test_checkpoint_does_not_rewrite_messages(tmp_path):
manager = SessionManager(tmp_path)
state = manager.state
draft = await state.get("chat:a")
draft.add_message("user", "hello")
await state.prepare_input(draft)
path = manager.sessions_dir / "sessions.sqlite3"
with sqlite3.connect(path) as db:
db.execute("CREATE TRIGGER prohibit_rewrite BEFORE UPDATE ON messages BEGIN SELECT RAISE(ABORT, 'rewritten'); END")
await state.checkpoint_view(draft, {"step": 1})
assert (await state.get(draft.key)).metadata["runtime_checkpoint"] == {"step": 1}
await state.aclose()
try:
draft = await state.import_messages("chat:a", [
{"role": "user", "content": "earlier question"},
{"role": "assistant", "content": "earlier answer"},
])
draft.add_message("user", "hello")
await state.prepare_input(draft)
accepted = manager.read_session_snapshot(draft.key).messages
assert accepted == draft.messages
path = manager.sessions_dir / "sessions.sqlite3"
with sqlite3.connect(path) as db:
for operation in ("INSERT", "UPDATE", "DELETE"):
db.execute(f"""CREATE TRIGGER prohibit_{operation.lower()} BEFORE {operation} ON messages
BEGIN SELECT RAISE(ABORT, 'rewritten'); END""")
await state.checkpoint_view(draft, {"step": 1})
finally:
await state.aclose()
stored = manager.read_session_snapshot(draft.key)
assert stored.messages == accepted
assert stored.metadata["runtime_checkpoint"] == {"step": 1}
async def test_database_lock_does_not_block_event_loop(tmp_path):
-9
View File
@@ -156,15 +156,6 @@ def test_internal_continuation_requires_budget_boundary_and_queue():
)
def test_save_skip_matches_prefix_when_current_message_was_persisted():
skip = _save_skip_for_turn(
message_metadata=None,
initial_message_count=3, # [system, history user, current user]
input_persisted_early=True,
)
assert skip == 3
def test_save_skip_unchanged_for_standalone_current_message():
# [system, history user, current user] with the current user already saved.
assert _save_skip_for_turn(
+26 -19
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import base64
from io import BytesIO
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -235,29 +236,35 @@ async def test_multipart_upload_saves_file(aiohttp_client, mock_agent, tmp_path)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multipart_multiple_files(aiohttp_client, mock_agent, tmp_path) -> None:
async def test_multipart_multiple_files(aiohttp_client, mock_agent, tmp_path, monkeypatch) -> None:
"""Multipart upload with multiple files saves all and passes paths."""
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
import aiohttp
try:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
media_dir = tmp_path / "media"
media_dir.mkdir()
monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: media_dir)
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
# Note: aiohttp test client has limited multipart support
# This test verifies the basic flow
file_data = b"test content"
data = BytesIO(file_data)
files = [("first.txt", b"first file content"), ("second.bin", b"\x00second file\xff")]
data = aiohttp.FormData()
data.add_field("message", "analyze both files")
for filename, payload in files:
data.add_field("files", payload, filename=filename, content_type="application/octet-stream")
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
data={"message": "analyze", "files": data},
)
assert resp.status == 200
finally:
os.chdir(original_cwd)
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)
assert resp.status == 200
mock_agent.process_direct.assert_called_once()
mock_agent.process_direct.assert_awaited_once()
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "analyze both files"
saved_paths = [Path(path) for path in call_kwargs["media"]]
assert len(saved_paths) == 2
assert saved_paths[0] != saved_paths[1]
for path, (_, payload) in zip(saved_paths, files, strict=True):
assert path.parent == media_dir
assert path.read_bytes() == payload
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
-29
View File
@@ -243,35 +243,6 @@ async def test_stream_sse_chunk_ids_are_consistent(aiohttp_client) -> None:
assert chunk_ids.pop().startswith("chatcmpl-")
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_passes_on_stream_callbacks(aiohttp_client) -> None:
"""process_direct should be called with on_stream and on_stream_end when streaming."""
captured_kwargs: dict = {}
async def fake_process_direct(**kwargs):
captured_kwargs.update(kwargs)
if kwargs.get("on_stream_end"):
await kwargs["on_stream_end"]()
return "done"
agent = MagicMock()
agent.process_direct = fake_process_direct
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
)
assert resp.status == 200
assert captured_kwargs.get("on_stream") is not None
assert captured_kwargs.get("on_stream_end") is not None
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_segment_end_does_not_close_sse(aiohttp_client) -> None:
+24 -12
View File
@@ -2,21 +2,39 @@
set -euo pipefail
cd "$(dirname "$0")/.." || exit 1
IMAGE_NAME="nanobot-test"
RUN_ID="$$-${RANDOM}"
IMAGE_NAME="nanobot-test-${RUN_ID}"
CONTAINER_NAME="nanobot-test-run-${RUN_ID}"
ONBOARDED_IMAGE="nanobot-test-onboarded-${RUN_ID}"
cleanup() {
result=$?
trap - EXIT
echo ""
echo "=== Cleanup ==="
docker rm -f "$CONTAINER_NAME" > /dev/null 2>&1 || true
docker rmi -f "$ONBOARDED_IMAGE" "$IMAGE_NAME" > /dev/null 2>&1 || true
exit "$result"
}
trap cleanup EXIT
echo "=== Building Docker image ==="
docker build -t "$IMAGE_NAME" .
echo ""
echo "=== Running 'nanobot onboard' ==="
docker run --name nanobot-test-run "$IMAGE_NAME" onboard
docker run --name "$CONTAINER_NAME" "$IMAGE_NAME" onboard
echo ""
echo "=== Running 'nanobot status' ==="
STATUS_OUTPUT=$(docker commit nanobot-test-run nanobot-test-onboarded > /dev/null && \
docker run --rm nanobot-test-onboarded status 2>&1) || true
echo "$STATUS_OUTPUT"
docker commit "$CONTAINER_NAME" "$ONBOARDED_IMAGE" > /dev/null
if STATUS_OUTPUT=$(docker run --rm "$ONBOARDED_IMAGE" status 2>&1); then
echo "$STATUS_OUTPUT"
else
result=$?
echo "$STATUS_OUTPUT"
exit "$result"
fi
echo ""
echo "=== Validating output ==="
@@ -47,10 +65,4 @@ else
exit 1
fi
# Cleanup
echo ""
echo "=== Cleanup ==="
docker rm -f nanobot-test-run 2>/dev/null || true
docker rmi -f nanobot-test-onboarded 2>/dev/null || true
docker rmi -f "$IMAGE_NAME" 2>/dev/null || true
echo "Done."
+99
View File
@@ -0,0 +1,99 @@
"""Exercise the Docker smoke script's failure and resource-ownership contract."""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pytest
pytestmark = pytest.mark.skipif(
sys.platform == "win32" or shutil.which("bash") is None,
reason="the Docker smoke script runs under Unix Bash",
)
SCRIPT = Path(__file__).with_name("test_docker.sh")
@pytest.fixture
def docker_boundary(tmp_path):
executable = tmp_path / "bin" / "docker"
executable.parent.mkdir()
executable.write_text(
f"#!{sys.executable}\n"
"import json, os, sys\n"
"args = sys.argv[1:]\n"
"with open(os.environ['DOCKER_CALLS'], 'a') as log:\n"
" log.write(json.dumps(args) + '\\n')\n"
"stage = args[0]\n"
"if stage == 'run': stage = args[-1]\n"
"if stage == 'status':\n"
" print('nanobot Status\\nConfig: configured\\nWorkspace: ready\\nModel: test\\n'\n"
" 'OpenRouter API: unset\\nAnthropic API: unset\\nOpenAI API: unset')\n"
"if stage == os.environ.get('DOCKER_FAIL_STAGE'): sys.exit(23)\n",
encoding="utf-8",
)
executable.chmod(0o755)
def run(name, *, fail_stage=""):
log = tmp_path / f"{name}.jsonl"
result = subprocess.run(
["bash", str(SCRIPT)],
env={
**os.environ,
"PATH": f"{executable.parent}{os.pathsep}{os.environ.get('PATH', '')}",
"DOCKER_CALLS": str(log),
"DOCKER_FAIL_STAGE": fail_stage,
},
capture_output=True,
text=True,
timeout=20,
check=False,
)
calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]
return result, calls
return run
def _assert_owned_cleanup(calls):
image = calls[0][2]
suffix = image.removeprefix("nanobot-test-")
assert suffix and suffix != image
container = f"nanobot-test-run-{suffix}"
onboarded = f"nanobot-test-onboarded-{suffix}"
assert calls[-2:] == [["rm", "-f", container], ["rmi", "-f", onboarded, image]]
for call in calls:
if call[0] == "run" and call[-1] == "onboard":
assert call == ["run", "--name", container, image, "onboard"]
elif call[0] == "commit":
assert call == ["commit", container, onboarded]
elif call[0] == "run" and call[-1] == "status":
assert call == ["run", "--rm", onboarded, "status"]
return {image, container, onboarded}
@pytest.mark.parametrize("stage", ["build", "onboard", "commit", "status"])
def test_smoke_failure_preserves_exit_and_cleans_only_owned_resources(docker_boundary, stage):
result, calls = docker_boundary(stage, fail_stage=stage)
assert result.returncode == 23, result.stdout + result.stderr
assert "All checks passed" not in result.stdout
_assert_owned_cleanup(calls)
if stage == "status":
# Valid-looking output must never turn a failed status process green.
assert "nanobot Status" in result.stdout
def test_concurrent_smoke_runs_use_distinct_resources_and_cleanup(docker_boundary):
with ThreadPoolExecutor(max_workers=2) as executor:
runs = list(executor.map(docker_boundary, ["first", "second"]))
resources = []
for result, calls in runs:
assert result.returncode == 0, result.stdout + result.stderr
assert "All checks passed" in result.stdout
resources.append(_assert_owned_cleanup(calls))
assert resources[0].isdisjoint(resources[1])
-13
View File
@@ -240,19 +240,6 @@ async def test_no_user_message_returns_400(aiohttp_client, app) -> None:
assert resp.status == 400
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_true_returns_sse(aiohttp_client, app) -> None:
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hello"}], "stream": True},
)
assert resp.status == 200
assert resp.content_type == "text/event-stream"
@pytest.mark.asyncio
async def test_model_mismatch_returns_400() -> None:
request = MagicMock()
-12
View File
@@ -1,12 +0,0 @@
from types import SimpleNamespace
def test_sanitize_persisted_blocks_preserves_tool_text() -> None:
from nanobot.agent.loop import AgentLoop
dummy = SimpleNamespace()
content = [{"type": "text", "text": "0123456789"}]
out = AgentLoop._sanitize_persisted_blocks(dummy, content)
assert out == content
+50 -1
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
@@ -415,7 +416,7 @@ def test_apply_patch_edits_reports_invalid_edit_shapes(tmp_path):
assert "each edit must be an object" in non_object
def test_apply_patch_edits_rolls_back_when_late_operation_fails(tmp_path):
def test_apply_patch_preflight_rejects_missing_later_file_without_partial_write(tmp_path):
first = tmp_path / "first.txt"
first.write_text("before\n")
tool = ApplyPatchTool(workspace=tmp_path)
@@ -441,3 +442,51 @@ def test_apply_patch_edits_rolls_back_when_late_operation_fails(tmp_path):
assert "file to update does not exist: missing.txt" in result
assert first.read_text() == "before\n"
@pytest.mark.parametrize("first_exists", [True, False], ids=["existing-file", "added-file"])
def test_apply_patch_edits_rolls_back_when_later_write_fails(tmp_path, monkeypatch, first_exists):
first = tmp_path / "first.txt"
first_original = b"before\r\nfirst tail"
if first_exists:
first.write_bytes(first_original)
second = tmp_path / "second.txt"
second_original = b"before\r\nsecond tail"
second.write_bytes(second_original)
tool = ApplyPatchTool(workspace=tmp_path)
write_text = Path.write_text
failed = False
def _fail_second_write(path, *args, **kwargs):
nonlocal failed
written = write_text(path, *args, **kwargs)
if path == second and not failed:
failed = True
# A persistence error can occur after the file has already changed.
raise OSError("injected second write failure")
return written
monkeypatch.setattr(Path, "write_text", _fail_second_write)
result = asyncio.run(
tool.execute(
edits=[
{"path": "first.txt", "action": "add", "new_text": "after"},
{
"path": "second.txt",
"action": "replace",
"old_text": "before",
"new_text": "after",
},
]
)
)
assert failed
assert getattr(result, "is_error", False)
assert "Error applying patch: injected second write failure" in result
if first_exists:
assert first.read_bytes() == first_original
else:
assert not first.exists()
assert second.read_bytes() == second_original
+1 -1
View File
@@ -136,7 +136,7 @@ class TestEditIpynbFiles:
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
)
assert "Patch applied:" in result
assert '"source": "hi"' in f.read_text(encoding="utf-8")
assert f.read_text(encoding="utf-8") == '{"cells": [{"cell_type": "markdown", "source": "hi"}]}'
# ---------------------------------------------------------------------------
+45 -37
View File
@@ -1,22 +1,61 @@
"""Tests for exec tool environment isolation."""
import json
import shlex
import sys
import pytest
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.shell import ExecTool
_UNIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="Unix shell commands")
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_does_not_leak_parent_env(monkeypatch):
"""Env vars from the parent process must not be visible to commands."""
@pytest.mark.parametrize(
"allowed_env_keys, expected_allowed",
[
pytest.param(None, None, id="default-filtering"),
pytest.param(
["MY_CUSTOM_VAR", "NONEXISTENT_VAR_12345"],
"hello-from-config",
id="configured-passthrough",
),
],
)
@pytest.mark.parametrize(
"command_mode", [pytest.param("shell", marks=_UNIX_ONLY), "argv"],
)
async def test_exec_child_receives_filtered_env(monkeypatch, allowed_env_keys, expected_allowed, command_mode):
"""A successful child receives allowed values, but not secrets or unset keys."""
monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")
monkeypatch.setenv("NANOBOT_SECRET_TOKEN", "super-secret-value")
tool = ExecTool()
result = await tool.execute(command="printenv NANOBOT_SECRET_TOKEN")
assert "super-secret-value" not in result
monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)
marker = "ENV_PROBE_COMPLETE "
script = (
"import json, os; "
"keys = ['MY_CUSTOM_VAR', 'NANOBOT_SECRET_TOKEN', 'NONEXISTENT_VAR_12345']; "
f"print({marker!r} + json.dumps({{key: os.environ.get(key) for key in keys}}))"
)
argv = [sys.executable, "-c", script]
command = shlex.join(argv) if command_mode == "shell" else argv
manager = ExecSessionManager()
tool = ExecTool(allowed_env_keys=allowed_env_keys, session_manager=manager)
try:
result = await tool.execute(command=command)
finally:
await manager.close_all()
assert not getattr(result, "is_error", False), result
assert "Exit code: 0" in result
completed = [line.removeprefix(marker) for line in result.splitlines() if line.startswith(marker)]
assert len(completed) == 1, result
assert json.loads(completed[0]) == {
"MY_CUSTOM_VAR": expected_allowed,
"NANOBOT_SECRET_TOKEN": None,
"NONEXISTENT_VAR_12345": None,
}
@pytest.mark.asyncio
@@ -67,37 +106,6 @@ async def test_exec_path_prepend_takes_lookup_precedence(tmp_path):
assert "fallback" not in result
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_allowed_env_keys_passthrough(monkeypatch):
"""Env vars listed in allowed_env_keys should be visible to commands."""
monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")
tool = ExecTool(allowed_env_keys=["MY_CUSTOM_VAR"])
result = await tool.execute(command="printenv MY_CUSTOM_VAR")
assert "hello-from-config" in result
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_allowed_env_keys_does_not_leak_others(monkeypatch):
"""Env vars NOT in allowed_env_keys should still be blocked."""
monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")
monkeypatch.setenv("MY_SECRET_VAR", "secret-value")
tool = ExecTool(allowed_env_keys=["MY_CUSTOM_VAR"])
result = await tool.execute(command="printenv MY_SECRET_VAR")
assert "secret-value" not in result
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_allowed_env_keys_missing_var_ignored(monkeypatch):
"""If an allowed key is not set in the parent process, it should be silently skipped."""
monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)
tool = ExecTool(allowed_env_keys=["NONEXISTENT_VAR_12345"])
result = await tool.execute(command="printenv NONEXISTENT_VAR_12345")
assert "Exit code: 1" in result
# --- path_append injection prevention ------------------------------------
+27 -12
View File
@@ -149,22 +149,37 @@ def test_exec_returns_completed_session_output_when_yield_time_ms_is_used(tmp_pa
def test_exec_session_yield_returns_when_process_finishes_early(tmp_path):
async def run() -> tuple[str, str, float]:
async def run() -> str:
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), timeout=5, session_manager=manager)
stdin_tool = ExecSessionTool(manager=manager)
command = _python_command("import time; time.sleep(0.1); print('done')")
started = time.monotonic()
initial = await tool.execute(command=command, yield_time_ms=1200)
result, final = await _poll_if_running(initial, stdin_tool)
return result, final, time.monotonic() - started
tool = ExecTool(working_dir=str(tmp_path), timeout=20, session_manager=manager)
ready, release = tmp_path / "ready", tmp_path / "release"
command = _python_command(
"from pathlib import Path\nimport time\n"
"Path('ready').write_text('ready')\n"
"while not Path('release').exists(): time.sleep(0.01)\n"
"print('done')"
)
pending = asyncio.create_task(tool.execute(command=command, yield_time_ms=15000))
try:
async with asyncio.timeout(10):
while not ready.exists():
if pending.done():
pytest.fail(f"child exited before readiness: {await pending}")
await asyncio.sleep(0.01)
# Measure responsiveness only after the actual child is ready to exit.
release.touch()
return await asyncio.wait_for(pending, timeout=3)
finally:
release.touch()
pending.cancel()
await asyncio.gather(pending, return_exceptions=True)
await manager.close_all()
result, final, elapsed = asyncio.run(run())
result = asyncio.run(run())
assert "done" in result
assert "Exit code: 0" in final
assert "session_id:" not in final
assert elapsed < 4.0
assert "Exit code: 0" in result
assert "session_id:" not in result
def test_bounded_output_buffer_keeps_head_tail_and_exact_drop_count():
@@ -122,21 +122,6 @@ def test_edit_file_line_hint_can_cover_multiline_match(tmp_path):
assert target.read_text() == "before\nstart\nchanged\nend\nafter\n"
def test_edit_file_can_edit_ipynb_as_json(tmp_path):
target = tmp_path / "analysis.ipynb"
target.write_text('{"cells": []}')
tool = EditFileTool(workspace=tmp_path)
result = asyncio.run(tool.execute(
path=str(target),
old_text='"cells": []',
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
))
assert "Patch applied:" in result
assert '"source": "hi"' in target.read_text()
def test_edit_file_multiple_match_hint_mentions_occurrence(tmp_path):
target = tmp_path / "duplicate.txt"
target.write_text("same\nsame\n")
+18 -11
View File
@@ -50,14 +50,17 @@ async def test_probe_returns_true_for_open_port(tmp_path):
@pytest.mark.asyncio
async def test_probe_returns_false_for_closed_port():
"""Port 19999 is almost certainly not listening."""
assert await _probe_http_url("http://127.0.0.1:19999/mcp") is False
@pytest.mark.asyncio
async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch):
"""When no port is present, probe the validated address on port 80."""
@pytest.mark.parametrize(
"url, expected_port",
[
("http://unreachable-host.test/mcp", 80),
("http://unreachable-host.test:19999/mcp", 19999),
],
)
async def test_probe_returns_false_when_validated_target_refuses_connection(
monkeypatch: pytest.MonkeyPatch, url: str, expected_port: int,
):
"""Connection refusal on a validated address must fail on the selected port."""
attempts: list[tuple[str, int]] = []
monkeypatch.setattr(
@@ -71,8 +74,8 @@ async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch)
monkeypatch.setattr("nanobot.agent.tools.mcp.asyncio.open_connection", _open_connection)
assert await _probe_http_url("http://unreachable-host.test/mcp") is False
assert attempts == [("93.184.216.34", 80)]
assert await _probe_http_url(url) is False
assert attempts == [("93.184.216.34", expected_port)]
@pytest.mark.asyncio
@@ -80,8 +83,12 @@ async def test_probe_rejects_public_name_resolving_to_loopback():
def _resolver(hostname, port, family=0, type_=0):
return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))]
with patch("nanobot.security.network.socket.getaddrinfo", _resolver):
with (
patch("nanobot.security.network.socket.getaddrinfo", _resolver),
patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection,
):
assert await _probe_http_url("http://example.com:8765/mcp") is False
open_connection.assert_not_called()
@pytest.mark.asyncio
@@ -0,0 +1,41 @@
[
"agents.defaults.timezone",
"agents.defaults.timezone_mode",
"agents.defaults.unified_session",
"agents.defaults.max_tool_iterations",
"agents.defaults.max_concurrent_subagents",
"agents.defaults.max_tool_result_chars",
"agents.defaults.provider_retry_mode",
"agents.defaults.tool_hint_max_length",
"agents.defaults.dream.enabled",
"gateway.host",
"gateway.port",
"gateway.restart_mode",
"tools.exec.enable",
"tools.exec.timeout",
"tools.exec.path_prepend",
"tools.exec.path_append",
"tools.exec.sandbox",
"tools.exec.sandbox_ro_binds",
"tools.exec.sandbox_rw_binds",
"tools.exec.allowed_env_keys",
"tools.exec.allow_patterns",
"tools.exec.deny_patterns",
"tools.file.enable",
"tools.my.enable",
"tools.my.allow_set",
"tools.cli_apps.enable",
"tools.cli_apps.install_timeout",
"tools.cli_apps.run_timeout",
"tools.cli_apps.catalog_ttl_seconds",
"tools.restrict_to_workspace",
"tools.ssrf_whitelist",
"tools.max_session_messages_per_minute",
"tools.webui_allow_remote_package_install",
"tools.web.enable",
"tools.web.proxy",
"tools.web.user_agent",
"tools.image_generation.save_dir",
"api.host",
"api.timeout"
]
-8
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import os
import tomllib
from pathlib import Path
from nanobot.webui.build import (
@@ -88,13 +87,6 @@ def test_shared_notifications_make_existing_bundle_stale(tmp_path: Path) -> None
assert status.newest_source == shared
def test_channel_owned_ui_sources_are_included_in_distributions() -> None:
project_root = Path(__file__).resolve().parents[2]
pyproject = tomllib.loads((project_root / "pyproject.toml").read_text(encoding="utf-8"))
assert "nanobot/channels/*/webui/**/*" in pyproject["tool"]["hatch"]["build"]["include"]
def test_inspect_webui_bundle_accepts_fresh_dist(tmp_path: Path) -> None:
source = tmp_path / "webui"
dist = tmp_path / "nanobot" / "web" / "dist"
+19 -9
View File
@@ -61,7 +61,7 @@ def test_json_presets_reject_invalid_configuration(preset_data: dict, invalid_pa
@pytest.mark.parametrize("target", ["wheel", "sdist"])
def test_distributions_bundle_mcp_preset_resource(tmp_path: Path, target: str) -> None:
def test_distributions_bundle_webui_and_channel_resources(tmp_path: Path, target: str) -> None:
repository = Path(__file__).resolve().parents[2]
for name in ("pyproject.toml", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md"):
shutil.copyfile(repository / name, tmp_path / name)
@@ -70,8 +70,15 @@ def test_distributions_bundle_mcp_preset_resource(tmp_path: Path, target: str) -
(tmp_path / "nanobot/__init__.py").write_text("", encoding="utf-8")
(package / "__init__.py").write_text("", encoding="utf-8")
resource = "nanobot/webui/mcp_presets.json"
expected = (repository / resource).read_bytes()
(tmp_path / resource).write_bytes(expected)
resources = {
resource: (repository / resource).read_bytes(),
"nanobot/channels/example/webui/index.tsx": b"export const channel = 'example';\n",
"nanobot/channels/example/webui/assets/icon.svg": b'<svg id="channel-icon"/>\n',
}
for name, content in resources.items():
destination = tmp_path / name
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(content)
result = subprocess.run(
[sys.executable, "-c", f"import hatchling.build; hatchling.build.build_{target}('dist')"],
@@ -85,11 +92,14 @@ def test_distributions_bundle_mcp_preset_resource(tmp_path: Path, target: str) -
if target == "wheel":
with ZipFile(next((tmp_path / "dist").glob("*.whl"))) as wheel:
assert wheel.read(resource) == expected
for name, content in resources.items():
assert wheel.read(name) == content
else:
with tarfile.open(next((tmp_path / "dist").glob("*.tar.gz"))) as sdist:
member = next(name for name in sdist.getnames() if name.endswith(f"/{resource}"))
bundled = sdist.extractfile(member)
assert bundled is not None
with bundled:
assert bundled.read() == expected
for name, content in resources.items():
member = next((member for member in sdist.getnames() if member.endswith(f"/{name}")), None)
assert member is not None, f"Missing bundled resource: {name}"
bundled = sdist.extractfile(member)
assert bundled is not None
with bundled:
assert bundled.read() == content
+16 -6
View File
@@ -237,16 +237,26 @@ def test_webui_session_list_surfaces_pending_recovery_state(tmp_path: Path) -> N
def test_webui_session_index_uses_unique_temp_file(tmp_path: Path) -> None:
key = "websocket:unique-index-temp"
transcript = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
transcript.write_text(
'{"event":"user","chat_id":"unique-index-temp","text":"hello"}\n',
encoding="utf-8",
)
manager = SessionManager(tmp_path)
session = manager.get_or_create("websocket:unique-index-temp")
session.add_message("user", "hello")
manager.save(session)
stale_shared_tmp = manager.sessions_dir / ".webui_session_index.json.tmp"
stale_shared_tmp.write_text("stale", encoding="utf-8")
stale_bytes = b"pre-existing shared temp\x00\xff"
stale_shared_tmp.write_bytes(stale_bytes)
assert list_webui_sessions(manager)[0]["preview"] == "hello"
row, = list_webui_sessions(manager)
assert stale_shared_tmp.read_text(encoding="utf-8") == "stale"
assert row["key"] == key
assert row["preview"] == "hello"
cache = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))
cached_row, = cache["sessions"]
assert cached_row["key"] == key
assert cached_row["preview"] == "hello"
assert stale_shared_tmp.read_bytes() == stale_bytes
assert not list(manager.sessions_dir.glob(".webui_session_index.json.*.tmp"))
-9
View File
@@ -2725,15 +2725,6 @@ def test_create_model_configuration_accepts_azure_openai_aad_mode(
assert saved.model_presets["azure-aad"].model == "my-deployment"
def test_azure_openai_spec_no_longer_requires_api_key() -> None:
"""Contract guard: api_key is optional for azure_openai (AAD fallback)."""
from nanobot.webui.settings_api import _provider_requires_api_key
spec = find_by_name("azure_openai")
assert spec is not None
assert _provider_requires_api_key(spec) is False
@pytest.mark.parametrize("protocol", ["chat_completions", "responses", "anthropic_messages"])
def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypatch, protocol):
config_path = tmp_path / "config.json"
+26 -4
View File
@@ -649,13 +649,35 @@ async def test_reverting_runtime_switch_clears_restart_but_preserves_other_chang
async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path):
router = _router(config_path=tmp_path / "config.json")
original = router.settings.config.load().tools.web.fetch.use_jina_reader
config = router.settings.config.load()
original_reader = config.tools.web.fetch.use_jina_reader
original_timeout = config.api.timeout
path = "/api/settings/web-search/update"
first = await router.dispatch(None, _mutation_request(path, {"provider": "duckduckgo", "use_jina_reader": not original}), path)
first = await router.dispatch(None, _mutation_request(path, {
"provider": "duckduckgo", "use_jina_reader": not original_reader,
}), path)
assert first.status_code == 200
assert json.loads(first.body)["restart_required_sections"] == ["browser"]
router._restart_sections.add("runtime")
restored = await router.dispatch(None, _mutation_request(path, {"provider": "duckduckgo", "use_jina_reader": original}), path)
runtime_path = "/api/settings/runtime-config/update"
changed = await router.dispatch(None, _mutation_request(runtime_path, {
"values": {"api.timeout": original_timeout + 1},
}), runtime_path)
assert changed.status_code == 200
assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"}
restored = await router.dispatch(None, _mutation_request(path, {
"provider": "duckduckgo", "use_jina_reader": original_reader,
}), path)
assert restored.status_code == 200
assert json.loads(restored.body)["restart_required_sections"] == ["runtime"]
refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]
reverted = await router.dispatch(None, _mutation_request(runtime_path, {
"values": {"api.timeout": original_timeout},
}), runtime_path)
assert reverted.status_code == 200
assert json.loads(reverted.body)["restart_required_sections"] == []
@pytest.mark.parametrize("enabled", [False, True])
+4 -8
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import json
import re
from pathlib import Path
import pytest
@@ -11,7 +10,6 @@ from nanobot.config.schema import Config
from nanobot.webui.settings_api import update_runtime_config_settings
from nanobot.webui.settings_contracts import WebUISettingsError
from nanobot.webui.settings_runtime import (
RUNTIME_CONFIG_PATHS,
runtime_config_payload,
update_runtime_config,
)
@@ -166,13 +164,11 @@ def test_api_changes_require_explicit_restart(tmp_path):
assert payload["requires_restart"]
def test_every_exposed_runtime_setting_has_a_frontend_use():
fields = Path(__file__).parents[2] / "webui/src/components/settings/system/runtime-config-fields.ts"
paths = re.findall(r'group: "[^"]+", path: "([^"]+)"', fields.read_text(encoding="utf-8"))
def test_runtime_payload_matches_shared_catalogue_contract():
fixture = Path(__file__).with_name("fixtures") / "runtime-config-keys.json"
paths = json.loads(fixture.read_text(encoding="utf-8"))
assert len(paths) == len(set(paths))
# The CLI enable flag controls visibility of its advanced fields, without an editor.
visibility_only = {"tools.cli_apps.enable"}
assert set(paths) | visibility_only == set(RUNTIME_CONFIG_PATHS)
assert set(runtime_config_payload(Config())) == set(paths)
def test_disabling_memory_consolidation_preserves_other_memory_settings():