refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

-2
View File
@@ -1,5 +1,3 @@
"""Shared fixtures and helpers for agent tests."""
from __future__ import annotations
import os
-2
View File
@@ -1,5 +1,3 @@
"""Compatibility helpers while runner tests migrate to immutable runtimes."""
from __future__ import annotations
from typing import Any
-2
View File
@@ -1,5 +1,3 @@
"""Session-worker completion helpers for integration tests."""
import asyncio
import faulthandler
import time
-2
View File
@@ -186,8 +186,6 @@ async def test_prompt_snapshot_uses_approved_plugin_bytes_after_replacement(
pause_for_replacement()
return content
# Both boundaries retain the approved bytes: after discovery returns,
# and while the fingerprint scan still holds bytes read before an edit.
with monkeypatch.context() as race:
if boundary == "after-verification":
race.setattr(Path, "iterdir", iterdir)
+5 -108
View File
@@ -1,5 +1,3 @@
"""Tests for auto compact (idle TTL) feature."""
import asyncio
import time
from datetime import datetime, timedelta
@@ -120,7 +118,6 @@ def _make_fake_compact(
await loop.sessions.state.commit_summary(session, s, archive_end=archive_end)
return s
# Attach state for count access
_fake_compact.state = state # type: ignore[attr-defined]
return _fake_compact
@@ -296,7 +293,6 @@ async def test_turn_resuming_during_archive_commits_reply(tmp_path, monkeypatch,
await asyncio.wait_for(entered.wait(), 5)
turn = asyncio.create_task(loop.process_direct("new input", session_key=session.key))
# The pending archive only holds its own conversation's execution slot.
other = await asyncio.wait_for(
loop.process_direct("other input", session_key="cli:other"), 5,
)
@@ -328,57 +324,46 @@ async def test_turn_resuming_during_archive_commits_reply(tmp_path, monkeypatch,
class TestSessionTTLConfig:
"""Test session TTL configuration."""
def test_default_ttl_is_fifteen_minutes(self):
"""Default TTL should proactively compact stale sessions."""
defaults = AgentDefaults()
assert defaults.session_ttl_minutes == 15
def test_explicit_zero_disables_ttl(self):
"""Explicit 0 should still disable idle auto-compact."""
defaults = AgentDefaults(session_ttl_minutes=0)
assert defaults.session_ttl_minutes == 0
def test_custom_ttl(self):
"""Custom TTL should be stored correctly."""
defaults = AgentDefaults(session_ttl_minutes=30)
assert defaults.session_ttl_minutes == 30
def test_user_friendly_alias_is_supported(self):
"""Config should accept idleCompactAfterMinutes as the preferred JSON key."""
defaults = AgentDefaults.model_validate({"idleCompactAfterMinutes": 30})
assert defaults.session_ttl_minutes == 30
def test_legacy_alias_is_still_supported(self):
"""Config should still accept the old sessionTtlMinutes key for compatibility."""
defaults = AgentDefaults.model_validate({"sessionTtlMinutes": 30})
assert defaults.session_ttl_minutes == 30
def test_serializes_with_user_friendly_alias(self):
"""Config dumps should use idleCompactAfterMinutes for JSON output."""
defaults = AgentDefaults(session_ttl_minutes=30)
data = defaults.model_dump(mode="json", by_alias=True)
assert data["idleCompactAfterMinutes"] == 30
assert "sessionTtlMinutes" not in data
def test_idle_scan_interval_defaults_to_sixty_seconds(self):
"""The config default should avoid scanning all sessions every idle tick."""
defaults = AgentDefaults()
assert defaults.idle_compact_check_interval_seconds == 60
def test_idle_scan_interval_uses_camel_case_config_key(self):
"""The JSON config should use the standard camelCase alias."""
defaults = AgentDefaults.model_validate({"idleCompactCheckIntervalSeconds": 10})
assert defaults.idle_compact_check_interval_seconds == 10
data = defaults.model_dump(mode="json", by_alias=True)
assert data["idleCompactCheckIntervalSeconds"] == 10
class TestIdleScanThrottling:
"""Test scheduling of full idle-session scans."""
async def test_configured_idle_scan_interval_throttles_checks(self, tmp_path, monkeypatch):
"""The configured interval should reach the loop and gate session scans."""
ticks = iter((1_000.0, 1_000.0, 1_009.999, 1_010.0))
monkeypatch.setattr("nanobot.agent.loop.time", SimpleNamespace(time=time.time, monotonic=lambda: next(ticks)))
config = Config.model_validate({
@@ -407,7 +392,6 @@ class TestIdleScanThrottling:
assert loop.auto_compact.check_expired.call_count == 2
async def test_zero_idle_scan_interval_checks_every_tick(self, tmp_path, monkeypatch):
"""An explicit zero should leave each idle tick eligible to scan."""
monkeypatch.setattr("nanobot.agent.loop.time", SimpleNamespace(time=time.time, monotonic=lambda: 1_000.0))
loop = _make_loop(tmp_path)
loop.auto_compact.check_expired = AsyncMock()
@@ -419,31 +403,24 @@ class TestIdleScanThrottling:
class TestAgentLoopTTLParam:
"""Test that AutoCompact receives and stores session_ttl_minutes."""
def test_loop_stores_ttl(self, tmp_path):
"""AutoCompact should store the TTL value."""
loop = _make_loop(tmp_path, session_ttl_minutes=25)
assert loop.auto_compact._ttl == 25
def test_explicit_zero_ttl_disables_loop_compaction(self, tmp_path):
"""An explicit zero TTL disables idle compaction in the loop."""
loop = _make_loop(tmp_path, session_ttl_minutes=0)
assert loop.auto_compact._ttl == 0
class TestAutoCompact:
"""Test the _archive method."""
@pytest.mark.asyncio
async def test_check_expired_only_archives_expired_sessions(self, tmp_path):
"""With multiple sessions, only the expired one should be archived."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
# Expired session
s1 = loop.sessions.get_or_create("cli:expired")
s1.add_message("user", "old")
s1.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(s1)
# Active session
s2 = loop.sessions.get_or_create("cli:active")
s2.add_message("user", "recent")
loop.sessions.save(s2)
@@ -502,7 +479,6 @@ class TestAutoCompact:
@pytest.mark.asyncio
async def test_auto_compact_stores_summary_in_cache_and_metadata(self, tmp_path):
"""_archive caches and persists the summary without exposing archived history."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
@@ -531,7 +507,6 @@ class TestAutoCompact:
@pytest.mark.asyncio
async def test_auto_compact_empty_session(self, tmp_path):
"""_archive on empty session should not store a summary."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
loop.consolidator.compact_idle_session = _make_fake_compact(loop)
@@ -545,7 +520,6 @@ class TestAutoCompact:
@pytest.mark.asyncio
async def test_auto_compact_respects_last_archived(self, tmp_path):
"""_archive should process only unarchived messages."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 14)
@@ -565,7 +539,6 @@ class TestAutoCompact:
class TestAutoCompactIdleDetection:
"""Idle detection tests."""
@pytest.mark.asyncio
async def test_no_auto_compact_when_ttl_disabled(self, tmp_path):
@@ -595,7 +568,6 @@ class TestAutoCompactIdleDetection:
loop, track_archived=archived_messages,
)
# Simulate proactive archive completing before message arrives
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="new msg")
@@ -627,15 +599,12 @@ class TestAutoCompactIdleDetection:
@pytest.mark.asyncio
async def test_auto_compact_does_not_affect_priority_commands(self, tmp_path):
"""Priority commands (/stop, /restart) bypass _process_message entirely via run()."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
session.add_message("user", "old message")
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
# Priority commands are dispatched in run() before _process_message is called.
# Simulate that path directly via dispatch_priority.
raw = "/stop"
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content=raw)
ctx = CommandContext(msg=msg, session=session, key="cli:test", raw=raw, loop=loop)
@@ -643,7 +612,6 @@ class TestAutoCompactIdleDetection:
assert result is not None
assert "stopped" in result.content.lower() or "no active task" in result.content.lower()
# Session should be untouched since priority commands skip _process_message
session_after = loop.sessions.get_or_create("cli:test")
assert any(m["content"] == "old message" for m in session_after.messages)
await loop.aclose()
@@ -691,7 +659,6 @@ class TestAutoCompactIdleDetection:
@pytest.mark.asyncio
async def test_shortcut_command_excluded_from_get_history(self, tmp_path):
"""Messages marked _command are invisible to get_history (LLM context)."""
loop = _make_loop(tmp_path)
session = loop.sessions.get_or_create("cli:test")
session.add_message("user", "real question")
@@ -707,7 +674,6 @@ class TestAutoCompactIdleDetection:
class TestAutoCompactSystemMessages:
"""System-message idle compaction tests."""
@pytest.mark.asyncio
async def test_auto_compact_triggers_for_system_messages(self, tmp_path):
@@ -719,7 +685,6 @@ class TestAutoCompactSystemMessages:
loop.consolidator.compact_idle_session = _make_fake_compact(loop)
# Simulate proactive archive completing before system message arrives
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
msg = InboundMessage(
@@ -738,7 +703,6 @@ class TestAutoCompactSystemMessages:
class TestAutoCompactEdgeCases:
"""Edge cases for auto session new."""
@pytest.mark.asyncio
async def test_auto_compact_with_nothing_summary(self, tmp_path):
@@ -772,7 +736,6 @@ class TestAutoCompactEdgeCases:
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=Exception("API down"))
# Should not raise
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
session_after = loop.sessions.get_or_create("cli:test")
@@ -783,7 +746,6 @@ class TestAutoCompactEdgeCases:
@pytest.mark.asyncio
async def test_auto_compact_preserves_runtime_checkpoint_before_check(self, tmp_path):
"""Short expired sessions keep recent messages; checkpoint restore still works on resume."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
session.metadata[AgentLoop._RUNTIME_CHECKPOINT_KEY] = {
@@ -800,7 +762,6 @@ class TestAutoCompactEdgeCases:
loop, track_archived=archived_messages,
)
# Simulate proactive archive completing before message arrives
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="continue")
@@ -815,7 +776,6 @@ class TestAutoCompactEdgeCases:
class TestAutoCompactIntegration:
"""Idle compaction integration tests."""
@pytest.mark.asyncio
async def test_full_lifecycle(self, tmp_path):
@@ -826,7 +786,6 @@ class TestAutoCompactIntegration:
"Example: 'I walked to the store yesterday.'"
)
# Phase 1: User has an extended conversation before compaction
session.add_message("user", "I'm learning English, teach me past tense")
session.add_message("assistant", "Past tense is used for actions completed in the past...")
session.add_message("user", "Give me an example")
@@ -839,11 +798,9 @@ class TestAutoCompactIntegration:
session.add_message("assistant", "Correct.")
loop.sessions.save(session)
# Phase 2: Time passes (simulate idle)
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
# Phase 3: User returns with a new message
loop.provider.chat_stream_with_retry = AsyncMock(
return_value=LLMResponse(
content=overview,
@@ -858,7 +815,6 @@ class TestAutoCompactIntegration:
)
response = await loop._process_message(msg)
# Phase 4: Verify
session_after = loop.sessions.get_or_create("cli:test")
resumed_system_prompt = loop.provider.chat_stream_with_retry.await_args_list[-1].kwargs[
"messages"
@@ -873,28 +829,23 @@ class TestAutoCompactIntegration:
for m in session_after.get_history(max_messages=len(session_after.messages))
)
# Summary should NOT be persisted in session (ephemeral, one-shot)
assert not any(
"[Resumed Session]" in str(m.get("content", "")) for m in session_after.messages
)
assert resumed_system_prompt.count(overview) == 1
# Persisted model-only context must not leak into the public history.
assert not any(
"[/Runtime Context]" in str(public_history_message(m).get("content", ""))
for m in session_after.messages
)
# Pending summary should be consumed (one-shot)
assert "cli:test" not in loop.auto_compact._summaries
# The new message should be processed (response exists)
assert response is not None
await loop.aclose()
@pytest.mark.asyncio
async def test_runtime_context_markers_hidden_for_multi_paragraph_turn(self, tmp_path):
"""Auto-compact resume context must not leak runtime markers into public history."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
session.add_message("user", "old message")
@@ -903,7 +854,6 @@ class TestAutoCompactIntegration:
loop.consolidator.compact_idle_session = _make_fake_compact(loop)
# Simulate proactive archive completing before message arrives
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
msg = InboundMessage(
@@ -922,7 +872,6 @@ class TestAutoCompactIntegration:
class TestProactiveAutoCompact:
"""Proactive idle compaction tests."""
@staticmethod
async def _run_check_expired(loop, active_session_keys=()):
@@ -967,7 +916,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_no_check_when_ttl_disabled(self, tmp_path):
"""check_expired should be a no-op when TTL is 0."""
loop = _make_loop(tmp_path, session_ttl_minutes=0)
session = loop.sessions.get_or_create("cli:test")
session.add_message("user", "old message")
@@ -982,7 +930,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_proactive_archive_on_idle_tick(self, tmp_path):
"""Expired session should be archived during idle tick."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 5, prefix="old")
@@ -1007,7 +954,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_proactive_archive_skips_dream_sessions(self, tmp_path):
"""Internal Dream sessions should be left to Dream retention, not idle compact."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("dream:20260602-155256")
_add_turns(session, 6, prefix="dream")
@@ -1028,7 +974,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_no_proactive_archive_when_active(self, tmp_path):
"""Recently active session should NOT be archived on idle tick."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
session.add_message("user", "recent message")
@@ -1042,7 +987,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_no_duplicate_archive(self, tmp_path):
"""Should not archive the same session twice if already in progress."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="old")
@@ -1062,23 +1006,19 @@ class TestProactiveAutoCompact:
loop.consolidator.compact_idle_session = _slow_compact
# First call starts archiving via callback
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await started.wait()
assert archive_count == 1
# Second call should skip (key is in _archiving)
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
assert archive_count == 1
# Clean up
block_forever.set()
await _drain_background_tasks(loop)
await loop.aclose()
@pytest.mark.asyncio
async def test_proactive_archive_error_does_not_block(self, tmp_path):
"""Proactive archive failure should be caught and not block future ticks."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="old")
@@ -1090,16 +1030,13 @@ class TestProactiveAutoCompact:
loop.consolidator.compact_idle_session = _failing_compact
# Should not raise
await self._run_check_expired(loop)
# Key should be removed from _archiving (finally block)
assert "cli:test" not in loop.auto_compact._archiving
await loop.aclose()
@pytest.mark.asyncio
async def test_proactive_archive_skips_empty_sessions(self, tmp_path):
"""Proactive archive should not produce a summary for sessions with no messages."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
session.updated_at = datetime.now() - timedelta(minutes=20)
@@ -1109,13 +1046,11 @@ class TestProactiveAutoCompact:
await self._run_check_expired(loop)
# Empty session should not produce a summary
assert "cli:test" not in loop.auto_compact._summaries
await loop.aclose()
@pytest.mark.asyncio
async def test_skip_expired_session_with_active_agent_task(self, tmp_path):
"""Expired session with an active agent task should NOT be archived."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="old")
@@ -1125,18 +1060,16 @@ class TestProactiveAutoCompact:
_fake_compact = _make_fake_compact(loop)
loop.consolidator.compact_idle_session = _fake_compact
# Simulate an active agent task for this session
await self._run_check_expired(loop, active_session_keys={"cli:test"})
assert _fake_compact.state["count"] == 0
session_after = loop.sessions.get_or_create("cli:test")
assert len(session_after.messages) == 12 # All messages preserved
assert len(session_after.messages) == 12
await loop.aclose()
@pytest.mark.asyncio
async def test_archive_after_active_task_completes(self, tmp_path):
"""Session should be archived on next tick after active task completes."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="old")
@@ -1146,30 +1079,24 @@ class TestProactiveAutoCompact:
_fake_compact = _make_fake_compact(loop)
loop.consolidator.compact_idle_session = _fake_compact
# First tick: active task, skip
await self._run_check_expired(loop, active_session_keys={"cli:test"})
assert _fake_compact.state["count"] == 0
# Second tick: task completed, should archive
await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 1
await loop.aclose()
@pytest.mark.asyncio
async def test_partial_active_set_only_archives_inactive_expired(self, tmp_path):
"""With multiple sessions, only the expired+inactive one should be archived."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
# Session A: expired, no active task -> should be archived
s1 = loop.sessions.get_or_create("cli:expired_idle")
_add_turns(s1, 6, prefix="old_a")
s1.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(s1)
# Session B: expired, has active task -> should be skipped
s2 = loop.sessions.get_or_create("cli:expired_active")
_add_turns(s2, 6, prefix="old_b")
s2.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(s2)
# Session C: recent, no active task -> should be skipped
s3 = loop.sessions.get_or_create("cli:recent")
s3.add_message("user", "recent")
loop.sessions.save(s3)
@@ -1184,15 +1111,14 @@ class TestProactiveAutoCompact:
assert len(s1_after.messages) == 13
assert s1_after.get_history(max_messages=12) == []
s2_after = loop.sessions.get_or_create("cli:expired_active")
assert len(s2_after.messages) == 12 # Preserved
assert len(s2_after.messages) == 12
s3_after = loop.sessions.get_or_create("cli:recent")
assert len(s3_after.messages) == 1 # Preserved
assert len(s3_after.messages) == 1
await loop.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize("command_tail", [False, True])
async def test_no_reschedule_after_successful_archive(self, tmp_path, monkeypatch, command_tail):
"""Idle scans skip archived history until another ordinary message arrives."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 5, prefix="old")
@@ -1232,7 +1158,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_empty_session_does_not_schedule_idle_compact(self, tmp_path):
"""Empty expired sessions have no removable tail and should not schedule."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
session.updated_at = datetime.now() - timedelta(minutes=20)
@@ -1252,7 +1177,6 @@ class TestProactiveAutoCompact:
@pytest.mark.asyncio
async def test_session_can_be_compacted_again_after_new_messages(self, tmp_path, monkeypatch):
"""After successful compact + user sends new messages + idle again, should compact again."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 5, prefix="first")
@@ -1262,15 +1186,12 @@ class TestProactiveAutoCompact:
_fake_compact = _make_fake_compact(loop)
loop.consolidator.compact_idle_session = _fake_compact
# First compact cycle
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
assert _fake_compact.state["count"] == 1
# User returns, sends new messages
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="second topic")
await loop._process_message(msg)
# New messages have now been idle for a fresh TTL interval.
monkeypatch.setattr("nanobot.agent.autocompact.datetime", SimpleNamespace(
now=lambda: datetime.now() + timedelta(minutes=20),
fromisoformat=datetime.fromisoformat,
@@ -1281,11 +1202,9 @@ class TestProactiveAutoCompact:
class TestSummaryPersistence:
"""Test that summary survives restart via session metadata."""
@pytest.mark.asyncio
async def test_summary_recovered_after_restart(self, tmp_path):
"""Summary should be recovered from metadata when _summaries is empty (simulates restart)."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
@@ -1297,14 +1216,11 @@ class TestSummaryPersistence:
loop, summary="User said hello.",
)
# Archive
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Simulate restart: clear in-memory state
loop.auto_compact._summaries.clear()
loop.sessions.invalidate("cli:test")
# prepare_session should recover summary from metadata
reloaded = loop.sessions.get_or_create("cli:test")
assert len(reloaded.messages) == 13
assert reloaded.get_history(max_messages=12) == []
@@ -1312,13 +1228,11 @@ class TestSummaryPersistence:
assert summary is not None
assert summary["text"] == "User said hello."
# _last_summary persists in metadata for restart survival.
assert "_last_summary" in reloaded.metadata
await loop.aclose()
@pytest.mark.asyncio
async def test_metadata_persists_for_restart(self, tmp_path):
"""_last_summary stays in metadata so it survives process restarts."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
@@ -1329,24 +1243,20 @@ class TestSummaryPersistence:
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Clear in-memory to force metadata path
loop.auto_compact._summaries.clear()
loop.sessions.invalidate("cli:test")
reloaded = loop.sessions.get_or_create("cli:test")
# Every call returns the persisted summary.
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary is not None
_, summary2 = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary2 is not None
assert summary2["text"] == "Summary."
# _last_summary persists in metadata for restart survival.
assert "_last_summary" in reloaded.metadata
await loop.aclose()
@pytest.mark.asyncio
async def test_inmemory_summary_preserves_metadata_for_restart(self, tmp_path):
"""The in-memory summary path preserves _last_summary for restart recovery."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
@@ -1357,22 +1267,18 @@ class TestSummaryPersistence:
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Both _summaries and metadata have the summary
assert "cli:test" in loop.auto_compact._summaries
loop.sessions.invalidate("cli:test")
reloaded = loop.sessions.get_or_create("cli:test")
assert "_last_summary" in reloaded.metadata
# In-memory path is taken (no restart)
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary is not None
# _last_summary persists in metadata for restart survival.
assert "_last_summary" in reloaded.metadata
await loop.aclose()
@pytest.mark.asyncio
async def test_new_summary_overrides_old(self, tmp_path, monkeypatch):
"""A fresh archive writes a new summary that replaces the old one."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
@@ -1384,15 +1290,13 @@ class TestSummaryPersistence:
)
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Consume the first summary via hot path
_, summary1 = await loop.auto_compact.prepare_session(
loop.sessions.get_or_create("cli:test"), "cli:test"
)
assert summary1 is not None
assert summary1["text"] == "First summary."
assert "cli:test" not in loop.auto_compact._summaries # popped by hot path
assert "cli:test" not in loop.auto_compact._summaries
# Read the committed snapshot before starting the next edit.
session = await loop.sessions.state.get("cli:test")
_add_turns(session, 4, prefix="world")
await loop.sessions.state.finish_turn(session)
@@ -1400,17 +1304,14 @@ class TestSummaryPersistence:
loop.consolidator.compact_idle_session = _make_fake_compact(
loop, summary="Second summary.",
)
# New messages have now been idle for a fresh TTL interval.
monkeypatch.setattr("nanobot.agent.autocompact.datetime", SimpleNamespace(
now=lambda: datetime.now() + timedelta(minutes=20),
fromisoformat=datetime.fromisoformat,
))
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# The second archive writes a new summary
assert "cli:test" in loop.auto_compact._summaries
# prepare_session must return the new summary
reloaded = loop.sessions.get_or_create("cli:test")
_, summary2 = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary2 is not None
@@ -1419,7 +1320,6 @@ class TestSummaryPersistence:
@pytest.mark.asyncio
async def test_new_command_clears_last_summary(self, tmp_path):
"""/new should clear _last_summary so the new session starts fresh."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
@@ -1431,14 +1331,11 @@ class TestSummaryPersistence:
)
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Verify summary exists before /new
reloaded = loop.sessions.get_or_create("cli:test")
assert "_last_summary" in reloaded.metadata
# Simulate /new command
await loop.sessions.state.reset(reloaded.key)
# After /new, metadata should no longer contain _last_summary
fresh = loop.sessions.get_or_create("cli:test")
assert "_last_summary" not in fresh.metadata
await loop.aclose()
@@ -1490,7 +1387,7 @@ async def test_idle_compaction_rechecks_settled_activity(tmp_path, monkeypatch,
other_responses.append(await asyncio.wait_for(
loop.process_direct("other input", session_key="cli:other"), 5,
))
assert archived == [] # The real turn still holds its session lock.
assert archived == []
finally:
release.set()
-53
View File
@@ -1,5 +1,3 @@
"""Direct unit tests for AutoCompact class methods in isolation."""
import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
@@ -96,59 +94,44 @@ async def test_default_ttl_disables_idle_compaction():
assert schedule.call_count == 0
# ---------------------------------------------------------------------------
# _is_expired
# ---------------------------------------------------------------------------
class TestIsExpired:
"""Test AutoCompact._is_expired edge cases."""
def test_ttl_zero_always_false(self):
"""TTL=0 means auto-compact is disabled; always returns False."""
ac = _make_autocompact(ttl=0)
old = datetime.now() - timedelta(days=365)
assert ac._is_expired(old) is False
def test_none_timestamp_returns_false(self):
"""None timestamp should return False."""
ac = _make_autocompact(ttl=15)
assert ac._is_expired(None) is False
def test_empty_string_timestamp_returns_false(self):
"""Empty string timestamp should return False (falsy)."""
ac = _make_autocompact(ttl=15)
assert ac._is_expired("") is False
def test_exactly_at_boundary_is_expired(self):
"""Timestamp exactly at TTL boundary should be expired (>=)."""
ac = _make_autocompact(ttl=15)
now = datetime(2026, 1, 1, 12, 0, 0)
ts = now - timedelta(minutes=15)
assert ac._is_expired(ts, now=now) is True
def test_just_under_boundary_not_expired(self):
"""Timestamp just under TTL boundary should NOT be expired."""
ac = _make_autocompact(ttl=15)
now = datetime(2026, 1, 1, 12, 0, 0)
ts = now - timedelta(minutes=14, seconds=59)
assert ac._is_expired(ts, now=now) is False
def test_iso_string_parses_correctly(self):
"""ISO format string timestamp should be parsed and evaluated."""
ac = _make_autocompact(ttl=15)
now = datetime(2026, 1, 1, 12, 0, 0)
ts = (now - timedelta(minutes=20)).isoformat()
assert ac._is_expired(ts, now=now) is True
def test_custom_now_parameter(self):
"""Custom 'now' parameter should override datetime.now()."""
ac = _make_autocompact(ttl=10)
ts = datetime(2026, 1, 1, 10, 0, 0)
# 9 minutes later → not expired
now_under = datetime(2026, 1, 1, 10, 9, 0)
assert ac._is_expired(ts, now=now_under) is False
# 10 minutes later → expired
now_over = datetime(2026, 1, 1, 10, 10, 0)
assert ac._is_expired(ts, now=now_over) is True
@@ -163,7 +146,6 @@ class TestIsExpired:
assert ac._is_expired("not-a-timestamp") is False
def test_tz_aware_string_timestamp_is_compared_by_instant(self):
"""A valid timestamp with an offset remains eligible for expiry."""
ac = _make_autocompact(ttl=15)
now = datetime(2026, 1, 1, 12, 0, 0)
recent = (now - timedelta(minutes=10)).astimezone().isoformat()
@@ -173,16 +155,9 @@ class TestIsExpired:
assert ac._is_expired(expired, now=now) is True
# ---------------------------------------------------------------------------
# check_expired
# ---------------------------------------------------------------------------
class TestCheckExpired:
"""Test AutoCompact.check_expired scheduling logic."""
async def test_empty_sessions_list(self):
"""No sessions → schedule_background should never be called."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = []
@@ -192,7 +167,6 @@ class TestCheckExpired:
scheduler.assert_not_called()
async def test_expired_session_schedules_background(self):
"""Expired session should trigger schedule_background."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
old_dt = datetime.now() - timedelta(minutes=20)
@@ -320,7 +294,6 @@ class TestCheckExpired:
await ac.check_expired(MagicMock(), fail)
async def test_active_session_key_skips(self):
"""Session in active_session_keys should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
@@ -331,7 +304,6 @@ class TestCheckExpired:
scheduler.assert_not_called()
async def test_session_already_in_archiving_skips(self):
"""Session already in _archiving set should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
@@ -343,7 +315,6 @@ class TestCheckExpired:
scheduler.assert_not_called()
async def test_dream_session_skips(self):
"""Internal Dream sessions should not be scheduled for idle compact."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
@@ -359,7 +330,6 @@ class TestCheckExpired:
assert "dream:20260602-155256" not in ac._archiving
async def test_short_unarchived_session_schedules(self):
"""A short idle session still needs an archive entry for Dream."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
last_active = datetime(2026, 1, 1, 10, 0, 0)
@@ -403,13 +373,7 @@ class TestCheckExpired:
mock_sm.state.get.assert_not_awaited()
# ---------------------------------------------------------------------------
# _archive
# ---------------------------------------------------------------------------
class TestArchiveDelegates:
"""_archive should delegate all session mutation to Consolidator."""
@pytest.mark.asyncio
async def test_calls_compact_idle_session(self):
@@ -521,13 +485,7 @@ class TestArchiveDelegates:
assert "cli:test" not in ac._archiving
# ---------------------------------------------------------------------------
# prepare_session
# ---------------------------------------------------------------------------
class TestPrepareSession:
"""Test AutoCompact.prepare_session logic."""
@pytest.mark.parametrize("archiving", [False, True])
async def test_preparing_idle_session_preserves_turn_metadata(self, archiving):
@@ -544,7 +502,6 @@ class TestPrepareSession:
assert prepared.metadata["last_channel"] == "discord:new"
async def test_hot_path_summary_from_summaries(self):
"""Summary from _summaries dict should be returned (hot path)."""
ac = _make_autocompact()
session = _make_session()
last_active = datetime(2026, 5, 13, 14, 0, 0)
@@ -563,7 +520,6 @@ class TestPrepareSession:
}
async def test_hot_path_pops_summary_one_shot(self):
"""Hot path should pop the summary (one-shot; second call returns None)."""
ac = _make_autocompact()
session = _make_session()
last_active = datetime(2026, 1, 1)
@@ -574,12 +530,10 @@ class TestPrepareSession:
_, summary1 = await ac.prepare_session(session, "cli:test")
assert summary1 is not None
# Second call: hot path entry was popped
_, summary2 = await ac.prepare_session(session, "cli:test")
assert summary2 is None
async def test_cold_path_summary_from_metadata(self):
"""When _summaries is empty, summary should come from metadata (cold path)."""
ac = _make_autocompact()
last_active = datetime(2026, 5, 13, 14, 0, 0)
session = _make_session(metadata={
@@ -622,7 +576,6 @@ class TestPrepareSession:
}
async def test_cold_path_tolerates_missing_last_active(self):
"""A _last_summary dict without last_active must not raise."""
ac = _make_autocompact(ttl=0)
fallback = datetime(2026, 1, 2, 3, 4, 5)
session = _make_session(
@@ -640,7 +593,6 @@ class TestPrepareSession:
}
async def test_cold_path_missing_text_returns_none(self):
"""A _last_summary without a non-empty string text yields no summary."""
ac = _make_autocompact()
session = _make_session(metadata={
"_last_summary": {"last_active": datetime(2026, 1, 1).isoformat()},
@@ -652,7 +604,6 @@ class TestPrepareSession:
assert summary is None
async def test_no_summary_available_returns_none(self):
"""When no summary is available, should return (session, None)."""
ac = _make_autocompact()
session = _make_session()
@@ -662,7 +613,6 @@ class TestPrepareSession:
assert summary is None
async def test_dream_session_skips_reload_and_summaries(self):
"""Internal Dream sessions should not reload or receive compact summaries."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
ac.sessions = mock_sm
@@ -692,7 +642,6 @@ class TestPrepareSession:
assert key not in ac._summaries
async def test_cold_path_metadata_not_dict_returns_none(self):
"""If metadata _last_summary is not a dict, should return None summary."""
ac = _make_autocompact()
session = _make_session(metadata={"_last_summary": "not a dict"})
@@ -702,7 +651,6 @@ class TestPrepareSession:
assert summary is None
async def test_hot_path_takes_priority_over_metadata(self):
"""Hot path (_summaries) should take priority over metadata."""
ac = _make_autocompact()
session = _make_session(metadata={
"_last_summary": {
@@ -719,4 +667,3 @@ class TestPrepareSession:
_, summary = await ac.prepare_session(session, "cli:test")
assert summary is not None
assert summary["text"] == "Hot summary."
# After hot path pops, cold path would kick in on next call
@@ -1,5 +1,3 @@
"""Exercise request governance through the Codex transport boundary."""
from copy import deepcopy
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -200,12 +198,10 @@ async def test_without_pre_request_compaction_pressure_uses_local_summary(monkey
monkeypatch.setattr(provider, "supports_pre_request_compaction", lambda _model: False)
else:
monkeypatch.setattr(provider, "can_resume_conversation_state", lambda *_args: False)
# With no replayable state, pressure must come from the actual transcript.
state, raw, consolidate = _request_state(
provider, repetitions=70_000 if mode == "incompatible_state" else 15_000,
)
if mode == "incompatible_state":
# Put the large content in accepted history so its replacement can fit.
state.compaction.accepted_messages = deepcopy(raw)
state.compaction.raw_accepted_boundary = len(raw)
_, context = await ContextGovernor().prepare_request(
@@ -1,5 +1,3 @@
"""Compaction and SDK turns settle against the same persisted transcript."""
import asyncio
from datetime import datetime, timedelta
from unittest.mock import patch
@@ -122,8 +120,6 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
assert provider.summary_started.is_set() is False
assert key not in bot._loop.auto_compact._archiving
# Only the later, genuinely idle scan may summarize the fresh reply.
# sdk:other is idle by then too; this expectation concerns sdk:shared.
scheduled = []
with patch("nanobot.agent.autocompact.datetime") as clock:
clock.now.return_value = datetime.now() + timedelta(minutes=30)
+1 -27
View File
@@ -1,5 +1,3 @@
"""Tests for Memory checkpoint consolidation and history journaling."""
from dataclasses import replace
from unittest.mock import AsyncMock, MagicMock
@@ -57,7 +55,6 @@ def runtime(mock_provider):
def consolidator(store):
sessions = MagicMock()
sessions.save = MagicMock()
# Store sessions by key so refreshes observe the same test object.
_session_cache: dict[str, MagicMock] = {}
sessions.get_or_create = MagicMock(side_effect=lambda key: _session_cache.get(key, MagicMock()))
sessions._session_cache = _session_cache
@@ -326,7 +323,6 @@ class TestConsolidatorSummarize:
async def test_summarize_appends_to_history(
self, consolidator, mock_provider, store, runtime
):
"""Consolidator should persist the LLM summary in history.jsonl."""
mock_provider.chat_stream_with_retry.return_value = MagicMock(
content="User fixed a bug in the auth module."
)
@@ -365,7 +361,6 @@ class TestConsolidatorSummarize:
async def test_summarize_raw_dumps_on_llm_failure(
self, consolidator, mock_provider, store, runtime
):
"""On LLM failure, append raw messages to memory/history.jsonl."""
mock_provider.chat_stream_with_retry.side_effect = Exception("API error")
messages = [{"role": "user", "content": "hello"}]
result = await _archive(consolidator, messages, runtime)
@@ -459,7 +454,6 @@ class TestConsolidatorArchiveErrorHandling:
runtime,
finish_reason: str,
):
"""Incomplete LLM output should trigger raw_archive, not persist partial text."""
invalid_output = f"INVALID_{finish_reason.upper()}_OUTPUT"
mock_provider.chat_stream_with_retry.return_value = MagicMock(
content=invalid_output,
@@ -480,7 +474,6 @@ class TestConsolidatorArchiveErrorHandling:
async def test_archive_preserves_summary_on_success(
self, consolidator, mock_provider, store, runtime
):
"""Normal LLM response should still produce a proper summary entry."""
mock_provider.chat_stream_with_retry.return_value = MagicMock(
content="User fixed a bug in the auth module.",
finish_reason="stop",
@@ -539,7 +532,6 @@ class TestConsolidatorArchiveErrorHandling:
class TestConsolidatorPromptEstimate:
async def test_estimate_uses_full_unarchived_tail(self, consolidator, runtime):
"""Consolidation pressure must account for the full unarchived tail."""
session = Session(key="test:full-tail")
for i in range(160):
session.add_message("user", f"msg-{i}")
@@ -576,7 +568,6 @@ class TestConsolidatorPromptEstimate:
assert captured["history"] == []
class TestCompactIdleSession:
"""Idle compaction tests."""
@pytest.fixture
def runtime(self, mock_provider):
@@ -1037,7 +1028,6 @@ class TestCompactIdleSession:
for i in range(18):
session.add_message("user", f"user msg {i}")
session.add_message("assistant", f"assistant msg {i}")
# The latest correction must be included in the replacement summary.
session.add_message("user", "no, that's wrong, use approach B")
session.add_message("assistant", "CORRECTED_FINAL_RESULT_alpha")
sessions.save(session)
@@ -1056,7 +1046,6 @@ class TestCompactIdleSession:
async def test_raw_dumps_full_archive_batch_on_llm_failure(
self, real_consolidator, mock_provider, store, runtime
):
"""The fallback covers the same full range as successful idle archival."""
mock_provider.chat_stream_with_retry.side_effect = RuntimeError("LLM unavailable")
sessions = real_consolidator.sessions
session = sessions.get_or_create("cli:rawdrop")
@@ -1109,7 +1098,6 @@ class TestCompactIdleSession:
async def test_empty_session_does_not_refresh_timestamp(
self, real_consolidator, runtime
):
"""Empty session with old updated_at does not look active after compaction."""
from datetime import datetime, timedelta
sessions = real_consolidator.sessions
@@ -1131,7 +1119,6 @@ class TestCompactIdleSession:
async def test_nothing_commits_checkpoint_once_without_raw_archive(
self, real_consolidator, mock_provider, runtime
):
"""A model's decision to retain nothing is a successful replacement."""
mock_provider.chat_stream_with_retry.return_value = MagicMock(
content="(nothing)", finish_reason="stop"
)
@@ -1178,7 +1165,6 @@ class TestCompactIdleSession:
assert result is not None
assert "[RAW]" in result
# raw_archive should have been called (history.jsonl gets an entry)
entries = store.read_unprocessed_history(since_cursor=0)
assert entries[0]["content"].startswith("[RAW] 20 messages")
@@ -1192,7 +1178,6 @@ class TestCompactIdleSession:
async def test_respects_last_archived(
self, real_consolidator, mock_provider, runtime
):
"""30 turns with last_archived=50 → only the unarchived tail is considered."""
mock_provider.chat_stream_with_retry.return_value = MagicMock(
content="Tail summary.", finish_reason="stop"
)
@@ -1201,7 +1186,7 @@ class TestCompactIdleSession:
for i in range(30):
session.add_message("user", f"u{i}")
session.add_message("assistant", f"a{i}")
session.last_archived = 50 # Only 10 messages remain unarchived
session.last_archived = 50
sessions.save(session)
result = await real_consolidator.compact_idle_session(
@@ -1212,12 +1197,9 @@ class TestCompactIdleSession:
assert len(reloaded.messages) == 61
assert reloaded.last_archived == 60
# Verify only the unarchived tail was processed:
# All 10 unarchived messages (50-59) are archived exactly once.
archived_call = mock_provider.chat_stream_with_retry.call_args
sent_messages = archived_call.kwargs["messages"]
sent_content = [message.get("content") for message in sent_messages]
# The replacement overview covers all model-visible conversation context.
assert "u0" not in sent_content
assert "u26" in sent_content
assert sent_messages[-1]["content"] == _ARCHIVE_PROMPT
@@ -1250,7 +1232,6 @@ class TestCompactIdleSession:
assert reloaded.last_archived == 25
assert reloaded.get_history(max_messages=25) == []
# Both the first question and the final tool-heavy exchange are summarized.
archived_call = mock_provider.chat_stream_with_retry.call_args
sent_content = [message.get("content") for message in archived_call.kwargs["messages"]]
assert "user-00" in sent_content
@@ -1548,10 +1529,8 @@ class TestCompactIdleSession:
async def test_acquires_consolidation_lock(
self, real_consolidator, mock_provider, runtime
):
"""Verify lock is held during execution."""
import asyncio
# Use a slow LLM response to ensure the lock is held while we check
started = asyncio.Event()
release_chat = asyncio.Event()
@@ -1585,7 +1564,6 @@ class TestCompactIdleSession:
class TestRawArchiveChunks:
"""raw_archive() keeps complete journal content with bounded individual entries."""
@pytest.mark.parametrize("boundary", ["A ", "\n\n", "<think>PRIVATE</think>"])
def test_raw_chunks_preserve_sanitized_boundaries(self, store, boundary):
@@ -1598,7 +1576,6 @@ class TestRawArchiveChunks:
store.raw_archive([message])
# Reload the real journal, rather than observing append call arguments.
entries = MemoryStore(store.workspace).read_unprocessed_history(since_cursor=0)
joined = "".join(entry["content"].split("\n", 1)[1] for entry in entries)
assert joined == expected
@@ -1606,7 +1583,6 @@ class TestRawArchiveChunks:
assert "PUBLIC_TAIL" in joined
def test_raw_archive_splits_large_content_into_bounded_entries(self, store):
"""Large messages are split across bounded journal entries."""
big = "x" * 50_000
messages = [{"role": "user", "content": big}]
store.raw_archive(messages)
@@ -1616,7 +1592,6 @@ class TestRawArchiveChunks:
assert "[RAW]" in entries[0]["content"]
def test_raw_archive_preserves_small_content(self, store):
"""Small messages should not be truncated."""
messages = [{"role": "user", "content": "hello"}]
store.raw_archive(messages)
entries = store.read_unprocessed_history(since_cursor=0)
@@ -1661,7 +1636,6 @@ class TestRawArchiveChunks:
assert entries[0]["session_key"] == "websocket:chat-1"
def test_raw_archive_custom_max_chars(self, store):
"""max_chars parameter should override default limit."""
messages = [{"role": "user", "content": "a" * 200}]
store.raw_archive(messages, max_chars=100)
entries = store.read_unprocessed_history(since_cursor=0)
+2 -42
View File
@@ -1,5 +1,3 @@
"""Tests for ContextBuilder — system prompt and message assembly."""
from pathlib import Path
import pytest
@@ -7,19 +5,11 @@ import pytest
from nanobot.agent.context import ContextBuilder, TranscriptInput
from nanobot.runtime_context import RuntimeContextBlock
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _builder(tmp_path: Path, **kw) -> ContextBuilder:
return ContextBuilder(workspace=tmp_path, **kw)
# ---------------------------------------------------------------------------
# _merge_message_content (static)
# ---------------------------------------------------------------------------
class TestMergeMessageContent:
def test_str_plus_str(self):
result = ContextBuilder._merge_message_content("hello", "world")
@@ -68,11 +58,6 @@ class TestMergeMessageContent:
assert result == [{"type": "text", "text": "raw_item"}]
# ---------------------------------------------------------------------------
# _load_bootstrap_files
# ---------------------------------------------------------------------------
class TestLoadBootstrapFiles:
def test_no_bootstrap_files(self, tmp_path):
builder = _builder(tmp_path)
@@ -176,11 +161,6 @@ class TestLoadBootstrapFiles:
assert "User prefers Chinese." in result
# ---------------------------------------------------------------------------
# _is_template_content (static)
# ---------------------------------------------------------------------------
class TestIsTemplateContent:
def test_nonexistent_template_returns_false(self):
assert ContextBuilder._is_template_content("anything", "nonexistent/path.md") is False
@@ -201,11 +181,6 @@ class TestIsTemplateContent:
assert ContextBuilder._is_template_content("totally different", "memory/MEMORY.md") is False
# ---------------------------------------------------------------------------
# Bundled bootstrap templates
# ---------------------------------------------------------------------------
class TestBundledToolContract:
def test_tool_contract_contains_shared_execution_policy(self):
from importlib.resources import files as pkg_files
@@ -226,11 +201,6 @@ class TestBundledToolContract:
assert "clear user request as authorization" in prompt
# ---------------------------------------------------------------------------
# build_user_content
# ---------------------------------------------------------------------------
class TestBuildUserContent:
def test_no_media_returns_string(self, tmp_path):
builder = _builder(tmp_path)
@@ -292,11 +262,6 @@ class TestBuildUserContent:
assert result[1]["_meta"]["path"] == str(png)
# ---------------------------------------------------------------------------
# build_system_prompt
# ---------------------------------------------------------------------------
class TestBuildSystemPrompt:
def test_includes_identity_section(self, tmp_path):
builder = _builder(tmp_path)
@@ -360,11 +325,6 @@ class TestBuildSystemPrompt:
assert "[Archived Context Summary]" not in result
# ---------------------------------------------------------------------------
# build_messages
# ---------------------------------------------------------------------------
class TestBuildMessages:
def test_optional_arguments_are_keyword_only(self, tmp_path):
builder = _builder(tmp_path)
@@ -475,7 +435,7 @@ class TestBuildMessages:
builder = _builder(tmp_path)
history = [{"role": "user", "content": "previous user message"}]
messages = builder.build_messages(history, "new message")
assert len(messages) == 2 # system + merged user
assert len(messages) == 2
assert "previous user message" in str(messages[1]["content"])
assert "new message" in str(messages[1]["content"])
@@ -511,7 +471,7 @@ class TestBuildMessages:
builder = _builder(tmp_path)
history = [{"role": "assistant", "content": "previous response"}]
messages = builder.build_messages(history, "new message")
assert len(messages) == 3 # system + assistant + user
assert len(messages) == 3
def test_media_with_history(self, tmp_path):
png = tmp_path / "img.png"
-15
View File
@@ -1,5 +1,3 @@
"""Tests for cache-friendly prompt construction."""
from __future__ import annotations
import datetime as datetime_module
@@ -35,7 +33,6 @@ def test_bootstrap_files_are_backed_by_templates() -> None:
def test_system_prompt_stays_stable_when_clock_changes(tmp_path, monkeypatch) -> None:
"""System prompt should not change just because wall clock minute changes."""
monkeypatch.setattr(datetime_module, "datetime", _FakeDatetime)
workspace = _make_workspace(tmp_path)
@@ -51,7 +48,6 @@ def test_system_prompt_stays_stable_when_clock_changes(tmp_path, monkeypatch) ->
def test_selected_project_path_follows_shared_cache_prefix(tmp_path) -> None:
"""Project paths must not invalidate the stable identity and tool contract prefix."""
agent_home = tmp_path / "agent-home"
project_a = tmp_path / "project-a"
project_b = tmp_path / "project-b"
@@ -109,7 +105,6 @@ def test_provider_context_appended_after_user_content(tmp_path) -> None:
def test_execution_rules_in_system_prompt(tmp_path) -> None:
"""Execution rules should appear in the system prompt via the default templates."""
from nanobot.utils.helpers import sync_workspace_templates
workspace = _make_workspace(tmp_path)
@@ -122,7 +117,6 @@ def test_execution_rules_in_system_prompt(tmp_path) -> None:
def test_execution_rules_reach_existing_workspace_soul(tmp_path) -> None:
"""An untouched legacy SOUL is upgraded in memory without overwriting the file."""
workspace = _make_workspace(tmp_path)
legacy_soul = (
pkg_files("nanobot") / "templates" / "legacy" / "SOUL.md"
@@ -142,7 +136,6 @@ def test_execution_rules_reach_existing_workspace_soul(tmp_path) -> None:
@pytest.mark.parametrize("legacy_workspace", [False, True])
def test_scheduling_contract_reaches_fresh_and_legacy_workspaces(tmp_path, legacy_workspace) -> None:
"""Default files can be skipped and old files must not hide the current contract."""
from nanobot.utils.helpers import sync_workspace_templates
workspace = _make_workspace(tmp_path)
@@ -175,7 +168,6 @@ def test_scheduling_contract_reaches_fresh_and_legacy_workspaces(tmp_path, legac
def test_default_soul_template_keeps_execution_policy_in_tool_contract() -> None:
"""SOUL owns personality while the always-injected contract owns execution policy."""
soul = (pkg_files("nanobot") / "templates" / "SOUL.md").read_text(encoding="utf-8")
contract = (
pkg_files("nanobot") / "templates" / "agent" / "tool_contract.md"
@@ -189,7 +181,6 @@ def test_default_soul_template_keeps_execution_policy_in_tool_contract() -> None
def test_channel_format_hint_telegram(tmp_path) -> None:
"""Telegram channel should get messaging-app format hint."""
workspace = _make_workspace(tmp_path)
builder = ContextBuilder(workspace)
@@ -199,7 +190,6 @@ def test_channel_format_hint_telegram(tmp_path) -> None:
def test_channel_format_hint_whatsapp(tmp_path) -> None:
"""WhatsApp should get plain-text format hint."""
workspace = _make_workspace(tmp_path)
builder = ContextBuilder(workspace)
@@ -209,7 +199,6 @@ def test_channel_format_hint_whatsapp(tmp_path) -> None:
def test_channel_format_hint_absent_for_unknown(tmp_path) -> None:
"""Unknown or None channel should not inject a format hint."""
workspace = _make_workspace(tmp_path)
builder = ContextBuilder(workspace)
@@ -221,7 +210,6 @@ def test_channel_format_hint_absent_for_unknown(tmp_path) -> None:
def test_build_messages_passes_channel_to_system_prompt(tmp_path) -> None:
"""build_messages should pass channel through to build_system_prompt."""
workspace = _make_workspace(tmp_path)
builder = ContextBuilder(workspace)
@@ -235,7 +223,6 @@ def test_build_messages_passes_channel_to_system_prompt(tmp_path) -> None:
def test_memory_skill_is_lazy_loaded_from_skills_index(tmp_path) -> None:
"""Memory search guidance should be discoverable without loading its full body."""
workspace = _make_workspace(tmp_path)
builder = ContextBuilder(workspace)
@@ -262,7 +249,6 @@ def test_fresh_workspace_omits_default_prompt_scaffolding(tmp_path) -> None:
def test_template_memory_md_is_skipped(tmp_path) -> None:
"""Template content is omitted while memory locations remain available."""
workspace = _make_workspace(tmp_path)
from nanobot.utils.helpers import sync_workspace_templates
sync_workspace_templates(workspace, silent=True)
@@ -276,7 +262,6 @@ def test_template_memory_md_is_skipped(tmp_path) -> None:
def test_customized_memory_md_is_injected(tmp_path, monkeypatch) -> None:
"""A Dream-populated MEMORY.md should be injected normally."""
workspace = _make_workspace(tmp_path)
from nanobot.utils.helpers import sync_workspace_templates
sync_workspace_templates(workspace, silent=True)
-13
View File
@@ -21,20 +21,17 @@ class TestNextCursorRecovery:
cursor is corrupted (non-int)."""
def test_string_cursor_falls_back_to_scan(self, store):
"""Last entry has a string cursor — scan backwards to find a valid int."""
store.history_file.write_text(
'{"cursor": 5, "timestamp": "2026-04-01 10:00", "content": "good"}\n'
'{"cursor": 6, "timestamp": "2026-04-01 10:01", "content": "also good"}\n'
'{"cursor": "bad", "timestamp": "2026-04-01 10:02", "content": "corrupted"}\n',
encoding="utf-8",
)
# Delete .cursor file so _next_cursor falls back to reading JSONL
store._cursor_file.unlink(missing_ok=True)
cursor = store.append_history("recovered event")
assert cursor == 7
def test_all_corrupted_cursors_return_one(self, store):
"""Every entry has a non-int cursor — should restart at 1."""
store.history_file.write_text(
'{"cursor": "a", "timestamp": "2026-04-01 10:00", "content": "bad1"}\n'
'{"cursor": "b", "timestamp": "2026-04-01 10:01", "content": "bad2"}\n',
@@ -45,7 +42,6 @@ class TestNextCursorRecovery:
assert cursor == 1
def test_non_int_cursor_types(self, store):
"""Float, None, list — all non-int types handled gracefully."""
store.history_file.write_text(
'{"cursor": 3, "timestamp": "2026-04-01 10:00", "content": "valid"}\n'
'{"cursor": 3.5, "timestamp": "2026-04-01 10:01", "content": "float"}\n'
@@ -58,9 +54,7 @@ class TestNextCursorRecovery:
assert cursor == 4
def test_cursor_file_with_string_content(self, store):
"""Cursor file contains a non-numeric string — should fall back."""
store._cursor_file.write_text("not_a_number", encoding="utf-8")
# Also add valid JSONL so the fallback scan finds something
store.history_file.write_text(
'{"cursor": 10, "timestamp": "2026-04-01 10:00", "content": "valid"}\n',
encoding="utf-8",
@@ -69,7 +63,6 @@ class TestNextCursorRecovery:
assert cursor == 11
def test_stale_cursor_file_does_not_reuse_history_cursor(self, store):
"""A stale .cursor file must not allocate a duplicate cursor."""
store.history_file.write_text(
'{"cursor": 10, "timestamp": "2026-04-01 10:00", "content": "valid"}\n',
encoding="utf-8",
@@ -83,7 +76,6 @@ class TestNextCursorRecovery:
assert [e["cursor"] for e in entries] == [10, 11]
def test_cursor_file_stays_ahead_after_history_compaction(self, store):
"""A cursor counter ahead of the tail preserves monotonic allocation."""
store.history_file.write_text(
'{"cursor": 10, "timestamp": "2026-04-01 10:00", "content": "valid"}\n',
encoding="utf-8",
@@ -95,7 +87,6 @@ class TestNextCursorRecovery:
assert cursor == 101
def test_negative_cursor_file_content_falls_back(self, store):
"""A negative .cursor value is corrupt and should not produce negative IDs."""
store._cursor_file.write_text("-5", encoding="utf-8")
cursor = store.append_history("after negative cursor file")
@@ -108,7 +99,6 @@ class TestReadUnprocessedWithCorruption:
instead of crashing on comparison."""
def test_skips_string_cursor_entries(self, store):
"""Entries with string cursors are silently skipped."""
store.history_file.write_text(
'{"cursor": 1, "timestamp": "2026-04-01 10:00", "content": "valid1"}\n'
'{"cursor": "bad", "timestamp": "2026-04-01 10:01", "content": "corrupted"}\n'
@@ -120,7 +110,6 @@ class TestReadUnprocessedWithCorruption:
assert [e["cursor"] for e in entries] == [1, 3]
def test_mixed_corruption_preserves_order(self, store):
"""Valid entries maintain correct order despite corrupt neighbors."""
store.history_file.write_text(
'{"cursor": "x", "timestamp": "2026-04-01 10:00", "content": "bad"}\n'
'{"cursor": 2, "timestamp": "2026-04-01 10:01", "content": "good2"}\n'
@@ -132,7 +121,6 @@ class TestReadUnprocessedWithCorruption:
assert [e["cursor"] for e in entries] == [2, 4]
def test_all_valid_still_works(self, store):
"""Normal operation unaffected — baseline regression check."""
store.append_history("event 1")
store.append_history("event 2")
store.append_history("event 3")
@@ -169,7 +157,6 @@ class TestCursorValidationInvariant:
assert [e["cursor"] for e in entries] == [4, 5]
def test_negative_history_cursor_rejected(self, store):
"""A negative history cursor is corrupt and must not seed new writes."""
store.history_file.write_text(
'{"cursor": -5, "timestamp": "2026-04-01 10:00", "content": "negative"}\n',
encoding="utf-8",
+1 -26
View File
@@ -1,5 +1,3 @@
"""Tests for Dream memory consolidation — build_dream_prompt and cursor management."""
import pytest
from nanobot.agent.memory import MemoryStore
@@ -40,15 +38,11 @@ class TestBuildDreamPrompt:
assert r1 is not None
_, c1 = r1
# Cursor not yet advanced — same entries are still available
assert store.build_dream_prompt() is not None
# Advance cursor
store.set_last_dream_cursor(c1)
# Now no new entries
assert store.build_dream_prompt() is None
# Add new entry
store.append_history("second")
r2 = store.build_dream_prompt()
assert r2 is not None
@@ -144,7 +138,6 @@ class TestBuildDreamPrompt:
assert "entry-25" in next_prompt
def test_skips_malformed_history_entries(self, store):
"""Dream prompt building should tolerate externally corrupted JSONL rows."""
store.history_file.write_text(
'{"cursor": 1, "timestamp": "2026-04-01 10:00"}\n'
'{"cursor": 2, "timestamp": "2026-04-01 10:01", "content": "usable memory"}\n',
@@ -172,7 +165,6 @@ class TestBuildDreamPrompt:
class TestDreamRunCompletion:
"""The runner's terminal state gates Dream cursor advancement."""
class _Resp:
def __init__(self, stop_reason: str = "completed") -> None:
@@ -376,7 +368,6 @@ class TestDreamTools:
class TestEphemeralDirect:
"""Tests for the ephemeral flag that skips history.jsonl writes for Dream."""
@pytest.fixture
def _make_loop(self, tmp_path):
@@ -430,7 +421,6 @@ class TestEphemeralDirect:
assert loop.model_preset is None
async def test_ephemeral_skips_raw_archive(self, tmp_path, _make_loop):
"""When ephemeral=True, raw_archive must not be called."""
from unittest.mock import patch
loop, store = _make_loop
@@ -442,7 +432,6 @@ class TestEphemeralDirect:
mock_archive.assert_not_called()
async def test_non_ephemeral_runs_normally(self, tmp_path, _make_loop):
"""Without ephemeral, the normal path returns the model response."""
loop, store = _make_loop
response = await loop.process_direct("test", session_key="cli:normal")
@@ -495,7 +484,6 @@ class TestEphemeralDirect:
assert len(transcript_copies) == 0
async def test_ephemeral_sets_ctx_flag(self, tmp_path, _make_loop):
"""Verify that ephemeral=True is forwarded to TurnContext."""
from unittest.mock import patch
loop, store = _make_loop
@@ -516,7 +504,6 @@ class TestEphemeralDirect:
assert captured.get("ephemeral") is True
async def test_default_ephemeral_is_false(self, tmp_path, _make_loop):
"""By default ephemeral is False in TurnContext."""
from unittest.mock import patch
loop, store = _make_loop
@@ -550,7 +537,6 @@ class TestEphemeralDirect:
assert MemoryStore.dream_run_completed(resp) is False
async def test_completed_response_after_tool_error_is_success(self, _make_loop):
"""A soft tool error is model input, not a second run-level failure state."""
from unittest.mock import AsyncMock
from nanobot.providers.base import ToolCallRequest
@@ -589,7 +575,6 @@ class TestEphemeralDirect:
assert "Error" in tool_result["content"]
async def test_dream_turn_can_skip_unbatched_recent_history(self, tmp_path):
"""Dream must only see the batch selected by build_dream_prompt."""
from unittest.mock import MagicMock
from nanobot.agent.loop import AgentLoop
@@ -639,7 +624,6 @@ class TestEphemeralDirect:
assert "entry-60" not in request_text
async def test_dream_turn_injects_memory_files_once_and_persists_session(self, tmp_path):
"""Dream gets durable files from system context without losing its session record."""
from unittest.mock import MagicMock
from nanobot.agent.loop import AgentLoop
@@ -697,7 +681,6 @@ class TestEphemeralDirect:
class TestEphemeralHooks:
"""When ephemeral=True, extra hooks must not fire."""
@pytest.fixture
def _make_loop_with_spy(self, tmp_path):
@@ -742,7 +725,6 @@ class TestEphemeralHooks:
return loop, spy
async def test_extra_hooks_skipped_when_ephemeral(self, tmp_path, _make_loop_with_spy):
"""When ephemeral=True, extra hooks must not fire."""
loop, spy = _make_loop_with_spy
await loop.process_direct(
@@ -752,7 +734,6 @@ class TestEphemeralHooks:
spy.after_iteration.assert_not_called()
async def test_extra_hooks_fire_for_normal_sessions(self, tmp_path, _make_loop_with_spy):
"""Without ephemeral, extra hooks should fire normally."""
loop, spy = _make_loop_with_spy
await loop.process_direct("test", session_key="cli:normal")
@@ -774,10 +755,8 @@ class TestDreamCommitMessage:
store.git.init()
store.git.auto_commit("initial state")
# A real edit to a tracked content file.
store.write_memory("# Memory\n- DMSO research notes")
# A lying narrative the old code would have appended verbatim.
lying = "Added a Medical Research section (Mastic Gum, DMSO) to MEMORY.md"
diff_body = store.dream_content_diff()
assert diff_body, "real edit must be detected"
@@ -801,14 +780,12 @@ class TestDreamCommitMessage:
assert lying not in log
def test_commit_message_is_bare_prefix_when_no_changes(self, tmp_path):
"""A no-op Dream run yields only the prefix — never a narrated summary."""
store = MemoryStore(tmp_path)
store.write_soul("# Soul")
store.write_memory("# Memory")
store.git.init()
store.git.auto_commit("initial state")
# No edits at all.
assert store.dream_content_diff() == ""
msg = MemoryStore.build_dream_commit_message(
"dream: manual run", store.dream_content_diff(),
@@ -826,7 +803,6 @@ class TestDreamCommitMessage:
class TestDreamContentDiff:
"""The ground-truth signal that gates cursor advance and commit messages."""
def test_empty_when_git_not_initialized(self, store):
assert store.dream_content_diff() == ""
@@ -893,8 +869,7 @@ class TestDreamContentDiff:
assert "DMSO research notes" in diff
def test_ignores_cursor_only_changes(self, store):
"""Advancing the cursor must not count as a productive content edit."""
store.git.init()
store.git.auto_commit("initial")
store.set_last_dream_cursor(99) # only memory/.dream_cursor changes
store.set_last_dream_cursor(99)
assert store.dream_content_diff() == ""
-2
View File
@@ -1,5 +1,3 @@
"""Tests for Dream session key generation and rotation."""
from datetime import datetime, timedelta
from unittest.mock import patch
@@ -17,8 +17,6 @@ from nanobot.providers.registry import ProviderSpec
GEMINI_EXTRA = {"google": {"thought_signature": "sig-abc-123"}}
# ── ToolCallRequest serialization ──────────────────────────────────────
def test_tool_call_request_serializes_extra_content() -> None:
tc = ToolCallRequest(
id="abc123xyz",
@@ -57,8 +55,6 @@ def test_tool_call_request_omits_absent_extras() -> None:
assert "provider_specific_fields" not in payload["function"]
# ── _parse: SDK objects ────────────────────────────────────────────────
def _make_sdk_response_with_extra_content() -> ChatCompletion:
return ChatCompletion.model_validate({
"id": "chatcmpl-gemini",
@@ -105,8 +101,6 @@ def test_parse_sdk_object_preserves_extra_content() -> None:
assert payload["function"]["provider_specific_fields"] == {"inner": "value"}
# ── _parse: dict/mapping branch ───────────────────────────────────────
def test_parse_dict_preserves_extra_content() -> None:
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -189,8 +183,6 @@ def test_parse_deduplicates_duplicate_tool_call_ids(as_sdk: bool) -> None:
assert [tc.arguments for tc in result.tool_calls] == [{"path": "a.txt"}, {"path": "b.txt"}]
# ── _parse_chunks: streaming round-trip ───────────────────────────────
def test_parse_chunks_sdk_preserves_extra_content() -> None:
chunk = ChatCompletionChunk.model_validate({
"id": "chatcmpl-gemini",
@@ -253,8 +245,6 @@ def test_parse_chunks_dict_preserves_extra_content() -> None:
assert payload["extra_content"] == GEMINI_EXTRA
# ── Model switching: stale extras shouldn't break other providers ─────
def test_stale_extra_content_in_tool_calls_survives_sanitize() -> None:
"""When switching from Gemini to OpenAI, extra_content inside tool_calls
should survive message sanitization (it lives inside the tool_call dict,
@@ -283,8 +273,6 @@ def test_stale_extra_content_in_tool_calls_survives_sanitize() -> None:
assert sanitized[1]["tool_calls"][0]["extra_content"] == GEMINI_EXTRA
# ── Replay to Gemini: preserve or backfill thought signatures ─────────
def _gemini_provider() -> OpenAICompatProvider:
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
return OpenAICompatProvider(
@@ -307,7 +295,6 @@ def _tool_call(tc_id: str, name: str, *, signed: bool = False) -> dict:
def test_gemini_backfills_unsigned_tool_calls_and_keeps_results() -> None:
"""Cross-provider history stays intact and receives the documented fallback."""
provider = _gemini_provider()
messages = [
{"role": "user", "content": "check the sensor"},
@@ -332,7 +319,6 @@ def test_gemini_backfills_unsigned_tool_calls_and_keeps_results() -> None:
def test_gemini_preserves_parallel_calls_when_only_first_is_signed() -> None:
"""Gemini signs only the first native parallel call; all calls must replay."""
provider = _gemini_provider()
messages = [
{"role": "user", "content": "do both"},
@@ -421,7 +407,6 @@ def test_gemini_requires_signature_on_first_parallel_call() -> None:
def test_gemini_replay_preserves_signed_tool_calls() -> None:
"""A pure Gemini-origin history replays unchanged (signature intact)."""
provider = _gemini_provider()
messages = [
{"role": "user", "content": "hi"},
@@ -444,7 +429,6 @@ def test_gemini_replay_preserves_signed_tool_calls() -> None:
def test_non_gemini_provider_keeps_unsigned_tool_calls() -> None:
"""The filter is Gemini-scoped: other providers still replay unsigned calls."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
+2 -8
View File
@@ -1,5 +1,3 @@
"""Tests for GitStore — git-backed version control for memory files."""
import os
from unittest.mock import patch
@@ -114,7 +112,7 @@ class TestAutoCommit:
def test_does_not_create_empty_commits(self, git_ready):
git_ready.auto_commit("nothing 1")
git_ready.auto_commit("nothing 2")
assert len(git_ready.log()) == 1 # only init commit
assert len(git_ready.log()) == 1
def test_status_failure_is_explicit(self, git_ready):
with patch("dulwich.porcelain.status", side_effect=OSError("broken index")):
@@ -133,7 +131,7 @@ class TestLog:
git_ready.auto_commit(f"commit {i}")
commits = git_ready.log()
assert len(commits) == 4 # init + 3
assert len(commits) == 4
assert "commit 2" in commits[0].message
assert "init" in commits[-1].message
@@ -252,20 +250,16 @@ class TestRevert:
assert git.revert("abc") is None
def test_undoes_commit_changes(self, git_ready):
"""revert(sha) should undo the given commit by restoring to its parent."""
ws = git_ready._workspace
(ws / "SOUL.md").write_text("v2 content", encoding="utf-8")
git_ready.auto_commit("v2")
commits = git_ready.log()
# commits[0] = v2 (HEAD), commits[1] = init
# Revert v2 → restore to init's state (empty SOUL.md)
new_sha = git_ready.revert(commits[0].sha)
assert new_sha is not None
assert (ws / "SOUL.md").read_text(encoding="utf-8") == ""
def test_root_commit_returns_none(self, git_ready):
"""Cannot revert the root commit (no parent to restore to)."""
commits = git_ready.log()
assert len(commits) == 1
assert git_ready.revert(commits[0].sha) is None
-2
View File
@@ -1,5 +1,3 @@
"""Tests for token-bounded session history replay."""
from __future__ import annotations
from pathlib import Path
-45
View File
@@ -1,5 +1,3 @@
"""Tests for CompositeHook fan-out, error isolation, and integration."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
@@ -31,11 +29,6 @@ def _run_ctx() -> AgentRunHookContext:
return AgentRunHookContext(messages=[])
# ---------------------------------------------------------------------------
# Base AgentHook emit_reasoning: no-op
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_base_hook_emit_reasoning_is_noop():
hook = AgentHook()
@@ -43,11 +36,6 @@ async def test_base_hook_emit_reasoning_is_noop():
assert result is None
# ---------------------------------------------------------------------------
# Fan-out: every hook is called in order
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_composite_fans_out_before_iteration():
calls: list[str] = []
@@ -68,7 +56,6 @@ async def test_composite_fans_out_before_iteration():
@pytest.mark.asyncio
async def test_composite_fans_out_all_async_methods():
"""Verify all async methods fan out to every hook."""
events: list[str] = []
class RecordingHook(AgentHook):
@@ -151,11 +138,6 @@ async def test_composite_fans_out_all_async_methods():
]
# ---------------------------------------------------------------------------
# Error isolation: one hook raises, others still run
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_composite_error_isolation_before_iteration():
calls: list[str] = []
@@ -192,7 +174,6 @@ async def test_composite_error_isolation_on_stream():
@pytest.mark.asyncio
async def test_composite_error_isolation_all_async():
"""Error isolation for on_stream_end, before_execute_tools, after_iteration."""
calls: list[str] = []
class Bad(AgentHook):
@@ -284,18 +265,12 @@ async def test_composite_error_isolation_all_async():
]
# ---------------------------------------------------------------------------
# finalize_content: pipeline semantics (no error isolation)
# ---------------------------------------------------------------------------
def test_composite_finalize_content_none_passthrough():
hook = CompositeHook([AgentHook()])
assert hook.finalize_content(_ctx(), None) is None
def test_composite_finalize_content_ordering():
"""First hook transforms first, result feeds second hook."""
steps: list[str] = []
class H1(AgentHook):
@@ -314,11 +289,6 @@ def test_composite_finalize_content_ordering():
assert steps == ["H1:hi", "H2:HI"]
# ---------------------------------------------------------------------------
# wants_streaming: any-semantics
# ---------------------------------------------------------------------------
def test_composite_wants_streaming_any_true():
class No(AgentHook):
def wants_streaming(self):
@@ -355,11 +325,6 @@ def test_composite_detects_nested_run_snapshot_consumers():
assert CompositeHook([progress, CompositeHook([SDKCaptureHook()])]).has_run_hooks() is True
# ---------------------------------------------------------------------------
# Empty hooks list: behaves like no-op AgentHook
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_composite_empty_hooks_no_ops():
hook = CompositeHook([])
@@ -410,11 +375,6 @@ async def test_composite_can_wrap_another_composite():
assert calls == ["inner"]
# ---------------------------------------------------------------------------
# Integration: AgentLoop with extra hooks
# ---------------------------------------------------------------------------
def _make_loop(tmp_path, hooks=None, hook_factories=None):
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -441,7 +401,6 @@ def _make_loop(tmp_path, hooks=None, hook_factories=None):
@pytest.mark.asyncio
async def test_agent_loop_extra_hook_receives_calls(tmp_path):
"""Extra hook passed to AgentLoop is called alongside core LoopHook."""
from nanobot.providers.base import LLMResponse
events: list[str] = []
@@ -479,7 +438,6 @@ async def test_agent_loop_extra_hook_receives_calls(tmp_path):
@pytest.mark.asyncio
async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):
"""Turn-scoped hooks can be supplied externally and see turn-local context."""
from nanobot.providers.base import LLMResponse
captured: list[tuple[str, AgentTurnHookContext]] = []
@@ -545,7 +503,6 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):
@pytest.mark.asyncio
async def test_agent_loop_extra_hook_error_isolation(tmp_path):
"""A faulty extra hook does not crash the agent loop."""
from nanobot.providers.base import LLMResponse
class BadHook(AgentHook):
@@ -568,7 +525,6 @@ async def test_agent_loop_extra_hook_error_isolation(tmp_path):
@pytest.mark.asyncio
async def test_agent_loop_extra_hooks_do_not_swallow_loop_hook_errors(tmp_path):
"""Extra hooks must not change the core LoopHook failure behavior."""
from nanobot.providers.base import LLMResponse, ToolCallRequest
loop = _make_loop(tmp_path, hooks=[AgentHook()])
@@ -593,7 +549,6 @@ async def test_agent_loop_extra_hooks_do_not_swallow_loop_hook_errors(tmp_path):
@pytest.mark.asyncio
async def test_agent_loop_no_hooks_backward_compat(tmp_path):
"""Without hooks param, behavior is identical to before."""
from nanobot.providers.base import LLMResponse, ToolCallRequest
loop = _make_loop(tmp_path)
@@ -1,5 +1,3 @@
"""Image generation runtime reload tests."""
from __future__ import annotations
import pytest
@@ -35,7 +35,6 @@ async def test_generate_image_does_not_attach_media_to_final_response(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Generating an image does not attach it to the final outbound response."""
set_config_path(tmp_path / "config.json")
monkeypatch.setattr(
"nanobot.agent.tools.image_generation.get_image_gen_provider",
@@ -85,5 +84,4 @@ async def test_generate_image_does_not_attach_media_to_final_response(
assert result is not None
assert result.content == "Done"
# Image delivery requires a separate message tool call.
assert result.media == []
-4
View File
@@ -76,7 +76,6 @@ async def test_next_turn_is_told_not_to_resume_after_iteration_limit(tmp_path):
await loop.process_direct("what is 2 + 2?", session_key="cli:limit")
assert _STOP_MARKER in _last_user_content(requests[-1])
# Later inputs get no new marker; the earlier marked input stays in history.
await loop.process_direct("thanks", session_key="cli:limit")
assert _STOP_MARKER not in _last_user_content(requests[-1])
assert _STOP_MARKER in json.dumps(requests[-1])
@@ -99,7 +98,6 @@ async def test_stop_survives_restart_and_keeps_history_prefix(tmp_path):
try:
await loop.process_direct("what is 2 + 2?", session_key="cli:limit")
assert _STOP_MARKER in _last_user_content(current[0])
# Ordinary prefix and tool schemas are unchanged. Structured failed calls remain.
assert json.dumps(previous[0]) == json.dumps(current[0][:len(previous[0])])
assert schemas[0] == loop.provider.schemas[0]
assert [m for m in previous[-1] if m["role"] == "tool"] == [
@@ -111,7 +109,6 @@ async def test_stop_survives_restart_and_keeps_history_prefix(tmp_path):
session = await loop.sessions.state.get("cli:limit")
assert _STOP_MARKER not in json.dumps(public_history_messages(session.messages))
# Another session must not inherit this stopped turn.
await loop.process_direct("hello", session_key="cli:other")
assert _STOP_MARKER not in json.dumps(current[-1])
finally:
@@ -134,7 +131,6 @@ async def test_goal_budget_handoff_is_not_an_abandoned_turn(tmp_path):
continuation = pending.get_nowait()
assert continuation.sender_id == "system:continuation"
# A new user input can run before the already queued goal continuation.
next_request = len(requests)
await loop.process_direct("give me a progress update", session_key="cli:goal")
assert _STOP_MARKER not in _last_user_content(requests[next_request])
-10
View File
@@ -1,5 +1,3 @@
"""Tests for structured tool activity emitted through AgentLoop progress events."""
import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
@@ -57,7 +55,6 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:
class TestToolEventProgress:
"""AgentLoop wires tool hooks and turn delivery into progress events."""
@pytest.mark.asyncio
async def test_write_file_emits_file_edit_progress(self, tmp_path: Path) -> None:
@@ -213,7 +210,6 @@ class TestToolEventProgress:
@pytest.mark.asyncio
async def test_bus_progress_delivers_tool_activity_in_progress_events(self, tmp_path: Path) -> None:
"""Bus-dispatched turns deliver tool activity through ProgressEvent.tool_events."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
@@ -237,7 +233,6 @@ class TestToolEventProgress:
)
await run_session(loop, msg)
# Drain all outbound messages and find the one carrying tool events.
outbound = []
while bus.outbound_size > 0:
outbound.append(await bus.consume_outbound())
@@ -311,7 +306,6 @@ class TestToolEventProgress:
@pytest.mark.asyncio
async def test_goal_turn_keeps_file_edit_progress_for_webui(self, tmp_path: Path) -> None:
"""The /goal command rewrites the prompt but must not bypass WebUI file-edit progress."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
@@ -396,7 +390,6 @@ class TestToolEventProgress:
self,
tmp_path: Path,
) -> None:
"""Non-streaming channels should get one final reply, not token progress spam."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "openai-codex/gpt-5.5"
@@ -427,7 +420,6 @@ class TestToolEventProgress:
self,
tmp_path: Path,
) -> None:
"""Streaming channels still receive provider deltas through stream events."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "openai-codex/gpt-5.5"
@@ -716,7 +708,6 @@ class TestToolEventProgress:
self,
tmp_path: Path,
) -> None:
"""A no-tools finalization must not be dropped after empty stream retries."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "openai-codex/gpt-5.5"
@@ -918,7 +909,6 @@ class TestToolEventProgress:
self,
tmp_path: Path,
) -> None:
"""Recovered streaming output should use a new stream segment."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "openai-codex/gpt-5.5"
@@ -1,5 +1,3 @@
"""Tests for AgentLoop integration with AgentRunner: streaming, think-filter, error handling, subagent."""
from __future__ import annotations
import asyncio
@@ -512,7 +510,6 @@ async def test_loop_retries_think_only_final_response(tmp_path):
@pytest.mark.asyncio
async def test_llm_error_returns_regular_response_instead_of_streamed_event(tmp_path):
"""LLM errors must not produce StreamedResponseEvent, so channels deliver the error."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
+1 -4
View File
@@ -212,7 +212,6 @@ async def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path
try:
identifier = await loop.sessions.state.queue_followup(message.session_key, message)
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
# Control: unlike mid-turn injection, this draft already sees the journal.
session = await loop.sessions.state.get(message.session_key)
assert await loop._persist_user_message_early(message, session)
assert PENDING_FOLLOWUPS_KEY not in session.metadata
@@ -1822,7 +1821,7 @@ async def test_request_context_uses_effective_key_for_subagent_tool(tmp_path: Pa
@pytest.mark.asyncio
async def test_next_turn_after_crash_closes_pending_user_turn_before_new_input(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
loop.provider.chat_stream_with_retry = AsyncMock(return_value=MagicMock()) # unused because _run_agent_loop is stubbed
loop.provider.chat_stream_with_retry = AsyncMock(return_value=MagicMock())
session = loop.sessions.get_or_create("feishu:c3")
session.add_message("user", "old question")
@@ -2039,8 +2038,6 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
non_system = [m for m in initial_messages if m.get("role") != "system"]
assert "question" in non_system[0]["content"]
assert "working" in non_system[1]["content"]
# Persisted timestamps stay in session records, but replay content is not
# rewritten with volatile ``[Message Time: ...]`` prefixes.
assert "[Message Time:" not in non_system[0]["content"]
assert "[Message Time:" not in non_system[1]["content"]
assert non_system[2]["role"] == "user"
-2
View File
@@ -219,7 +219,6 @@ async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -
await asyncio.Event().wait()
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
# The session policy must suffice even without passing ephemeral=True.
task = asyncio.create_task(loop._run_agent_loop(
TranscriptInput(history=[], current_message="synthetic question"),
runtime=loop.llm_runtime(), session=session,
@@ -252,7 +251,6 @@ async def test_session_worker_errors_keep_private_content_out_of_logs(
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(secret))
else:
async def fail_after_discard(*args, **kwargs):
# The privacy snapshot must survive cache eviction during failure.
loop.sessions.invalidate(key)
raise ValueError(secret)
-4
View File
@@ -1,5 +1,3 @@
"""Tests for the application-owned MCP provider lifecycle."""
from __future__ import annotations
import asyncio
@@ -777,7 +775,6 @@ async def test_shared_proxy_snapshot_survives_reconnect_and_reloads_only_opted_i
("independent", "http://proxy-a.example:8080", None),
]
# Mutating the caller's config must not reroute a live provider's reconnect.
config.network.proxy = "http://not-live.example:8080"
sessions["proxied"].expired = True
old_tool = registry.get("mcp_proxied_echo")
@@ -798,7 +795,6 @@ async def test_shared_proxy_snapshot_survives_reconnect_and_reloads_only_opted_i
assert closed == ["proxied", "proxied"]
assert registry.get("mcp_independent_echo") is independent_tool
# Reload also captures a copy, rather than retaining the loader's mutable model.
next_network.proxy = "http://proxy-c.example:8080"
sessions["proxied"].expired = True
current_tool = registry.get("mcp_proxied_echo")
+1 -4
View File
@@ -166,7 +166,6 @@ def allow_loopback_mcp_urls(monkeypatch: pytest.MonkeyPatch):
@pytest.mark.asyncio
async def test_mcp_reconnect_after_session_timeout(tmp_path, mcp_server_url):
"""Reconnect to a real MCP server after its idle timeout kills the session."""
cfg = MCPServerConfig(
type="streamableHttp",
url=mcp_server_url,
@@ -184,12 +183,11 @@ async def test_mcp_reconnect_after_session_timeout(tmp_path, mcp_server_url):
output = await asyncio.create_task(tool.execute(name="first"))
assert "Hello, first" in output
# Wait for the server-side idle timeout to terminate the session.
await asyncio.sleep(_IDLE_TIMEOUT_SECONDS + _IDLE_EXPIRY_GRACE_SECONDS)
output = await asyncio.create_task(tool.execute(name="second"))
assert "Hello, second" in output
assert registry.get("mcp_repro_greet") is not tool # Recovery must replace the session's wrapper.
assert registry.get("mcp_repro_greet") is not tool
await asyncio.create_task(provider.aclose())
@@ -200,7 +198,6 @@ async def test_mcp_reconnect_during_shutdown_does_not_crash(
mcp_server_url,
monkeypatch: pytest.MonkeyPatch,
):
"""Simulate the production crash: shutdown while reconnect is in flight."""
cfg = MCPServerConfig(
type="streamableHttp",
url=mcp_server_url,
-39
View File
@@ -1,5 +1,3 @@
"""Tests for MCP tool/resource/prompt transient error retry."""
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -20,10 +18,6 @@ from nanobot.agent.tools.mcp import (
)
from nanobot.agent.tools.registry import is_tool_error_result
# ---------------------------------------------------------------------------
# _is_transient helper
# ---------------------------------------------------------------------------
class _FakeClosedResourceError(Exception):
pass
@@ -87,11 +81,6 @@ def test_is_session_terminated_recognizes_connection_closed_mcp_error():
assert _is_session_terminated(_connection_closed_error())
# ---------------------------------------------------------------------------
# MCPToolWrapper retry behaviour
# ---------------------------------------------------------------------------
def _make_tool_def(name="test_tool"):
return SimpleNamespace(
name=name,
@@ -107,7 +96,6 @@ def _make_tool_result(text):
@pytest.mark.asyncio
async def test_tool_retries_on_transient_error():
"""Tool should retry once when a transient error occurs, then succeed."""
session = AsyncMock()
result = _make_tool_result("ok")
exc = _FakeClosedResourceError("connection lost")
@@ -124,7 +112,6 @@ async def test_tool_retries_on_transient_error():
@pytest.mark.asyncio
async def test_tool_fails_after_retry_exhausted():
"""Tool should fail with retry message when both attempts hit transient errors."""
session = AsyncMock()
exc1 = _FakeClosedResourceError("still dead")
exc2 = _FakeClosedResourceError("still dead again")
@@ -143,7 +130,6 @@ async def test_tool_fails_after_retry_exhausted():
@pytest.mark.asyncio
async def test_tool_no_retry_on_non_transient_error():
"""Tool should NOT retry on non-transient errors like ValueError."""
session = AsyncMock()
session.call_tool = AsyncMock(side_effect=ValueError("bad input"))
@@ -157,7 +143,6 @@ async def test_tool_no_retry_on_non_transient_error():
@pytest.mark.asyncio
async def test_tool_no_retry_on_timeout():
"""Timeouts should not trigger retry (they have their own handling)."""
session = AsyncMock()
session.call_tool = AsyncMock(side_effect=asyncio.TimeoutError())
@@ -170,7 +155,6 @@ async def test_tool_no_retry_on_timeout():
@pytest.mark.asyncio
async def test_tool_success_on_first_try_no_retry():
"""Normal success path — no retry logic involved."""
session = AsyncMock()
result = _make_tool_result("hello")
session.call_tool = AsyncMock(return_value=result)
@@ -208,7 +192,6 @@ async def test_tool_does_not_retry_on_cancelled_error():
@pytest.mark.asyncio
async def test_tool_retry_on_connection_reset():
"""ConnectionResetError (a stdlib exception) should also trigger retry."""
session = AsyncMock()
result = _make_tool_result("recovered")
session.call_tool = AsyncMock(
@@ -226,7 +209,6 @@ async def test_tool_retry_on_connection_reset():
@pytest.mark.asyncio
async def test_tool_retry_on_end_of_stream():
"""EndOfStream (anyio) should trigger retry."""
session = AsyncMock()
result = _make_tool_result("back")
session.call_tool = AsyncMock(side_effect=[_FakeEndOfStreamError("eof"), result])
@@ -242,7 +224,6 @@ async def test_tool_retry_on_end_of_stream():
@pytest.mark.asyncio
async def test_tool_reconnects_on_transient_failure():
"""Tool should reconnect when a stale session reports a transient stream failure."""
old_session = AsyncMock()
old_session.call_tool = AsyncMock(side_effect=_FakeClosedResourceError("closed"))
new_session = AsyncMock()
@@ -268,11 +249,6 @@ async def test_tool_reconnects_on_transient_failure():
mock_sleep.assert_not_called()
# ---------------------------------------------------------------------------
# MCPResourceWrapper retry behaviour
# ---------------------------------------------------------------------------
def _make_resource_def(name="test_resource"):
return SimpleNamespace(
name=name,
@@ -289,7 +265,6 @@ def _make_resource_result(text):
@pytest.mark.asyncio
async def test_resource_retries_on_transient_error():
"""Resource should retry once on transient connection error."""
session = AsyncMock()
result = _make_resource_result("data")
exc = _FakeClosedResourceError("gone")
@@ -306,7 +281,6 @@ async def test_resource_retries_on_transient_error():
@pytest.mark.asyncio
async def test_resource_fails_after_retry_exhausted():
"""Resource should fail with retry message when both attempts fail."""
session = AsyncMock()
exc = _FakeClosedResourceError("dead")
session.read_resource = AsyncMock(side_effect=[exc, exc])
@@ -322,7 +296,6 @@ async def test_resource_fails_after_retry_exhausted():
@pytest.mark.asyncio
async def test_resource_no_retry_on_non_transient():
"""Resource should not retry on non-transient errors."""
session = AsyncMock()
session.read_resource = AsyncMock(side_effect=RuntimeError("bad"))
@@ -335,7 +308,6 @@ async def test_resource_no_retry_on_non_transient():
@pytest.mark.asyncio
async def test_resource_reconnects_on_session_terminated():
"""Resource should reconnect once when the MCP SDK reports a dead session."""
old_session = AsyncMock()
old_session.read_resource = AsyncMock(side_effect=_session_terminated_error())
new_session = AsyncMock()
@@ -359,11 +331,6 @@ async def test_resource_reconnects_on_session_terminated():
assert new_session.read_resource.call_count == 1
# ---------------------------------------------------------------------------
# MCPPromptWrapper retry behaviour
# ---------------------------------------------------------------------------
def _make_prompt_def(name="test_prompt"):
return SimpleNamespace(
name=name,
@@ -384,7 +351,6 @@ def _make_prompt_result(text):
@pytest.mark.asyncio
async def test_prompt_retries_on_transient_error():
"""Prompt should retry once on transient connection error."""
session = AsyncMock()
result = _make_prompt_result("prompt text")
exc = _FakeClosedResourceError("gone")
@@ -401,7 +367,6 @@ async def test_prompt_retries_on_transient_error():
@pytest.mark.asyncio
async def test_prompt_fails_after_retry_exhausted():
"""Prompt should fail with retry message when both attempts fail."""
session = AsyncMock()
exc = _FakeClosedResourceError("dead")
session.get_prompt = AsyncMock(side_effect=[exc, exc])
@@ -417,7 +382,6 @@ async def test_prompt_fails_after_retry_exhausted():
@pytest.mark.asyncio
async def test_prompt_no_retry_on_mcp_error():
"""McpError (application-level) should NOT trigger retry."""
session = AsyncMock()
session.get_prompt = AsyncMock(
side_effect=McpError(ErrorData(code=-1, message="not found"))
@@ -432,7 +396,6 @@ async def test_prompt_no_retry_on_mcp_error():
@pytest.mark.asyncio
async def test_prompt_no_retry_on_non_transient():
"""Non-transient errors should not trigger retry for prompts."""
session = AsyncMock()
session.get_prompt = AsyncMock(side_effect=RuntimeError("bad"))
@@ -445,7 +408,6 @@ async def test_prompt_no_retry_on_non_transient():
@pytest.mark.asyncio
async def test_prompt_reconnects_on_session_terminated():
"""Prompt should reconnect once before falling back to McpError handling."""
old_session = AsyncMock()
old_session.get_prompt = AsyncMock(side_effect=_session_terminated_error())
new_session = AsyncMock()
@@ -471,7 +433,6 @@ async def test_prompt_reconnects_on_session_terminated():
@pytest.mark.asyncio
async def test_prompt_reconnects_on_connection_closed_exception():
"""Prompt should reconnect when the SDK reports a closed session as a generic exception."""
old_session = AsyncMock()
old_session.get_prompt = AsyncMock(side_effect=RuntimeError("Connection closed"))
new_session = AsyncMock()
+2 -25
View File
@@ -1,5 +1,3 @@
"""Tests for the restructured MemoryStore — pure file I/O layer."""
import json
from datetime import datetime
from pathlib import Path
@@ -105,7 +103,6 @@ class TestHistoryWithCursor:
assert len(entries) == 2
def test_read_unprocessed_skips_entries_without_cursor(self, store):
"""Regression: entries missing the cursor key should be silently skipped."""
store.history_file.write_text(
'{"timestamp": "2026-04-01 10:00", "content": "no cursor"}\n'
'{"cursor": 2, "timestamp": "2026-04-01 10:01", "content": "valid"}\n'
@@ -116,7 +113,6 @@ class TestHistoryWithCursor:
assert [e["cursor"] for e in entries] == [2, 3]
def test_read_unprocessed_skips_malformed_history_payloads(self, store):
"""Externally edited JSONL can keep an int cursor but miss required payload fields."""
store.history_file.write_text(
'{"cursor": 1, "timestamp": "2026-04-01 10:00", "content": "valid"}\n'
'{"cursor": 2, "timestamp": "2026-04-01 10:01"}\n'
@@ -133,19 +129,15 @@ class TestHistoryWithCursor:
assert [e["content"] for e in entries] == ["valid", "also valid"]
def test_next_cursor_falls_back_when_last_entry_has_no_cursor(self, store):
"""Regression: _next_cursor should not KeyError on entries without cursor."""
store.history_file.write_text(
'{"timestamp": "2026-04-01 10:01", "content": "no cursor"}\n',
encoding="utf-8",
)
# Delete .cursor file so _next_cursor falls back to reading JSONL
store._cursor_file.unlink(missing_ok=True)
# Last entry has no cursor — should safely return 1, not KeyError
cursor = store.append_history("new event")
assert cursor == 1
def test_append_history_allocates_unique_cursors_under_concurrent_writes(self, store):
"""Regression: concurrent appends must not allocate duplicate cursors."""
import threading
writers = 16
@@ -196,32 +188,25 @@ class TestHistoryWithCursor:
assert [entry["cursor"] for entry in entries] == list(range(21, 101))
def test_write_entries_uses_atomic_write(self, tmp_path):
"""_write_entries uses a temporary file and atomic replacement."""
store = MemoryStore(tmp_path)
store.append_history("event 1")
store.append_history("event 2")
store.append_history("event 3")
entries = store.read_unprocessed_history(since_cursor=0)
# Monitor temp file existence
tmp_path_obj = store.history_file.with_suffix(".jsonl.tmp")
assert not tmp_path_obj.exists() # Should not exist initially
assert not tmp_path_obj.exists()
# Call _write_entries
store._write_entries(entries)
# Temp file should be cleaned up
assert not tmp_path_obj.exists()
# Original file should exist
assert store.history_file.exists()
def test_write_entries_cleans_up_tmp_on_exception(self, tmp_path, monkeypatch):
"""Exception during _write_entries cleans up the temp file."""
store = MemoryStore(tmp_path)
store.append_history("event 1")
entries = store.read_unprocessed_history(since_cursor=0)
# Fail the platform-independent replacement boundary.
def failing_replace(*args, **kwargs):
raise RuntimeError("Simulated failure")
@@ -230,10 +215,8 @@ class TestHistoryWithCursor:
with pytest.raises(RuntimeError):
store._write_entries(entries)
# Temp file should be cleaned up, including uniquely named temps.
assert list(store.history_file.parent.glob("*.tmp")) == []
# Original file should still exist (because replace failed)
assert store.history_file.exists()
@@ -243,14 +226,12 @@ class TestAppendHistoryHardCap:
any current caller's per-call cap, so normal operation never trips it."""
def test_oversized_entry_is_truncated(self, store):
"""An entry above _HISTORY_ENTRY_HARD_CAP is truncated before being persisted."""
huge = "x" * (_HISTORY_ENTRY_HARD_CAP + 10_000)
store.append_history(huge)
entry = store.read_unprocessed_history(since_cursor=0)[0]
assert len(entry["content"]) <= _HISTORY_ENTRY_HARD_CAP + 50
def test_oversize_warning_is_emitted_once(self, store, monkeypatch):
"""Repeated oversized writes should warn only on the first occurrence."""
records: list[str] = []
monkeypatch.setattr(
"nanobot.agent.memory.logger.warning",
@@ -265,13 +246,11 @@ class TestAppendHistoryHardCap:
assert len(oversize_warnings) == 1
def test_custom_max_chars_overrides_default(self, store):
"""Callers that pass max_chars should get their tighter cap applied."""
store.append_history("a" * 500, max_chars=100)
entry = store.read_unprocessed_history(since_cursor=0)[0]
assert len(entry["content"]) <= 150 # 100 + "\n... (truncated)"
assert len(entry["content"]) <= 150
def test_normal_sized_entries_unaffected(self, store):
"""The hard cap must not alter entries that fit within it."""
msg = "normal short entry"
store.append_history(msg)
entry = store.read_unprocessed_history(since_cursor=0)[0]
@@ -335,7 +314,6 @@ class TestDreamCursor:
class TestLegacyHistoryMigration:
def test_read_unprocessed_history_handles_entries_without_cursor(self, store):
"""JSONL entries with cursor=1 are correctly parsed and returned."""
store.history_file.write_text(
'{"cursor": 1, "timestamp": "2026-03-30 14:30", "content": "Old event"}\n',
encoding="utf-8",
@@ -493,7 +471,6 @@ class TestLegacyHistoryMigration:
def test_history_skips_non_dict_jsonl_lines(tmp_path: Path) -> None:
"""Null/list/bool history lines must not crash reads or appends."""
memory = MemoryStore(tmp_path)
memory.history_file.parent.mkdir(parents=True, exist_ok=True)
memory.history_file.write_text(
-2
View File
@@ -1,5 +1,3 @@
"""Explicit goal requests can steer a running session without restarting it."""
import asyncio
from unittest.mock import AsyncMock, MagicMock
+3 -6
View File
@@ -1,5 +1,3 @@
"""Repeated SDK overrides reuse clients without changing execution ownership."""
import asyncio
from unittest.mock import AsyncMock, MagicMock
@@ -118,7 +116,7 @@ async def test_nested_signature_changes_are_typed_and_borrowers_are_detached(con
current = resolve(config, resolver)
assert current.provider is not second.provider
second = current
assert len(created) == 4 # default, bool, int, float
assert len(created) == 4
await resolver.aclose()
@@ -133,7 +131,7 @@ async def test_replacement_and_invalidation_do_not_close_active_borrowers(config
after_invalidate = resolve(config, resolver)
assert after_invalidate.provider is not before_invalidate.provider
assert resolve(config, resolver).provider is after_invalidate.provider
resolver.refresh() # No loader is also an explicit invalidation boundary.
resolver.refresh()
after_refresh = resolve(config, resolver)
assert after_refresh.provider is not after_invalidate.provider
resolver.adopt_snapshot(factory.build_provider_snapshot(config))
@@ -243,7 +241,6 @@ async def test_sdk_stream_survives_reuse_replacement_and_invalidation(configured
finally:
release.set()
await bot.aclose()
# The fixture resolver has its own initial provider, not owned by bot.
assert all(provider.aclose.await_count == 1 for provider in created[1:])
await fixture_resolver.aclose()
@@ -282,7 +279,7 @@ async def test_equivalent_invalid_fallback_is_not_hidden_by_reuse(configured_ove
assert (await first.provider.chat(messages=[], model=first.model)).content == "ok"
fallback.extra_headers = {"X-Route": "fixture"}
second = resolve(config, resolver) # Invalid fallback setup must remain lazy.
second = resolve(config, resolver)
second.provider._primary.chat = AsyncMock(return_value=error)
result = await second.provider.chat(messages=[], model=second.model)
assert result.finish_reason == "error"
-5
View File
@@ -1,5 +1,3 @@
"""Test /new archival behavior."""
import asyncio
from collections.abc import Coroutine
from pathlib import Path
@@ -14,7 +12,6 @@ _ARCHIVE_PROMPT = render_template("agent/consolidator_archive.md", strip=True)
class TestNewCommandArchival:
"""Test /new archival behavior with the structured archive flow."""
@staticmethod
def _make_loop(tmp_path: Path):
@@ -45,7 +42,6 @@ class TestNewCommandArchival:
self,
tmp_path: Path,
) -> None:
"""/new clears session immediately; archive is fire-and-forget."""
from nanobot.bus.events import InboundMessage
loop = self._make_loop(tmp_path)
@@ -146,7 +142,6 @@ class TestNewCommandArchival:
@pytest.mark.asyncio
async def test_aclose_drains_background_tasks(self, tmp_path: Path) -> None:
"""aclose waits for background tasks to complete."""
from nanobot.bus.events import InboundMessage
loop = self._make_loop(tmp_path)
+3 -120
View File
@@ -1,5 +1,3 @@
"""Tests for onboard logic and prompt keyboard behavior."""
from pathlib import Path
from types import SimpleNamespace
from typing import Any, cast
@@ -27,7 +25,6 @@ from nanobot.utils.helpers import sync_workspace_templates
class TestMergeMissingDefaults:
"""Tests for recursive config default merging."""
def test_adds_missing_top_level_keys(self):
existing = {"a": 1}
@@ -91,7 +88,6 @@ class TestMergeMissingDefaults:
assert merge_missing_defaults({}, {}) == {}
def test_backfills_channel_config(self):
"""Real-world scenario: backfill missing channel fields."""
existing_channel = {
"enabled": False,
"appId": "",
@@ -112,7 +108,6 @@ class TestMergeMissingDefaults:
class TestGetFieldTypeInfo:
"""Tests for _get_field_type_info type extraction."""
def test_extracts_str_type(self):
class Model(BaseModel):
@@ -155,23 +150,19 @@ class TestGetFieldTypeInfo:
assert inner is str
def test_extracts_list_type_without_item_type(self):
# Plain list without type param falls back to str
class Model(BaseModel):
items: list # type: ignore
# Plain list annotation doesn't match list check, returns str
type_name, inner = _get_field_type_info(Model.model_fields["items"])
assert type_name == "str" # Falls back to str for untyped list
assert type_name == "str"
assert inner is None
def test_extracts_dict_type(self):
# Plain dict without type param falls back to str
class Model(BaseModel):
data: dict # type: ignore
# Plain dict annotation doesn't match dict check, returns str
type_name, inner = _get_field_type_info(Model.model_fields["data"])
assert type_name == "str" # Falls back to str for untyped dict
assert type_name == "str"
assert inner is None
def test_extracts_optional_type(self):
@@ -179,7 +170,6 @@ class TestGetFieldTypeInfo:
optional: str | None = None
type_name, inner = _get_field_type_info(Model.model_fields["optional"])
# Should unwrap Optional and get str
assert type_name == "str"
assert inner is None
@@ -195,15 +185,12 @@ class TestGetFieldTypeInfo:
assert inner is Inner
def test_handles_none_annotation(self):
"""Field with None annotation defaults to str."""
# Create a mock field_info with None annotation
field_info = SimpleNamespace(annotation=None)
type_name, inner = _get_field_type_info(field_info)
assert type_name == "str"
assert inner is None
def test_literal_type_returns_literal_with_choices(self):
"""Literal["a", "b"] should return ("literal", ["a", "b"])."""
from typing import Literal
class Model(BaseModel):
@@ -214,7 +201,6 @@ class TestGetFieldTypeInfo:
assert inner == ["standard", "persistent"]
def test_real_provider_retry_mode_field(self):
"""Validate against actual AgentDefaults.provider_retry_mode field."""
from nanobot.config.schema import AgentDefaults
type_name, inner = _get_field_type_info(AgentDefaults.model_fields["provider_retry_mode"])
@@ -223,7 +209,6 @@ class TestGetFieldTypeInfo:
class TestGetFieldDisplayName:
"""Tests for _get_field_display_name human-readable name generation."""
def test_uses_description_if_present(self):
class Model(BaseModel):
@@ -268,7 +253,6 @@ class TestGetFieldDisplayName:
class TestFormatValue:
"""Tests for _format_value display formatting."""
def test_formats_none_as_not_set(self):
assert "not set" in _format_value(None)
@@ -308,22 +292,18 @@ class TestFormatValue:
class TestSyncWorkspaceTemplates:
"""Tests for sync_workspace_templates file synchronization."""
def test_does_not_overwrite_existing_files(self, tmp_path):
"""Should not overwrite files that already exist."""
workspace = tmp_path / "workspace"
workspace.mkdir(parents=True)
(workspace / "AGENTS.md").write_text("existing content")
sync_workspace_templates(workspace, silent=True)
# Existing file should not be changed
content = (workspace / "AGENTS.md").read_text()
assert content == "existing content"
def test_does_not_create_tools_md(self, tmp_path):
"""Tool contract is injected internally, not copied into user workspaces."""
workspace = tmp_path / "workspace"
added = sync_workspace_templates(workspace, silent=True)
@@ -332,7 +312,6 @@ class TestSyncWorkspaceTemplates:
assert not (workspace / "TOOLS.md").exists()
def test_preserves_existing_tools_md_without_overwriting(self, tmp_path):
"""Legacy user workspaces may have TOOLS.md; sync should leave it untouched."""
workspace = tmp_path / "workspace"
workspace.mkdir(parents=True)
tools_path = workspace / "TOOLS.md"
@@ -343,7 +322,6 @@ class TestSyncWorkspaceTemplates:
assert tools_path.read_text(encoding="utf-8") == "custom tool notes"
def test_creates_memory_directory(self, tmp_path):
"""Should create memory directory structure."""
workspace = tmp_path / "workspace"
sync_workspace_templates(workspace, silent=True)
@@ -360,19 +338,16 @@ class TestSyncWorkspaceTemplates:
assert not (workspace / "prompts" / "dream.md").exists()
def test_returns_list_of_added_files(self, tmp_path):
"""Should return list of relative paths for added files."""
workspace = tmp_path / "workspace"
added = sync_workspace_templates(workspace, silent=True)
assert isinstance(added, list)
# All paths should be relative to workspace
for path in added:
assert not Path(path).is_absolute()
class TestProviderChannelInfo:
"""Tests for provider and channel info retrieval."""
def test_get_provider_names_returns_dict(self):
from nanobot.cli.onboard import _get_provider_names
@@ -380,7 +355,6 @@ class TestProviderChannelInfo:
names = _get_provider_names()
assert isinstance(names, dict)
assert len(names) > 0
# Should include common providers
assert "openai" in names or "anthropic" in names
assert "openai_codex" not in names
assert "github_copilot" not in names
@@ -401,10 +375,9 @@ class TestProviderChannelInfo:
info = _get_provider_info()
assert isinstance(info, dict)
# Each value should be a tuple with expected structure
for provider_name, value in info.items():
assert isinstance(value, tuple)
assert len(value) == 4 # (display_name, needs_api_key, needs_api_base, env_var)
assert len(value) == 4
class _SimpleDraftModel(BaseModel):
@@ -520,10 +493,8 @@ class TestRunOnboardExitBehavior:
class TestValidateFieldConstraint:
"""Tests for _validate_field_constraint schema-aware input validation."""
def test_returns_none_when_no_constraints(self):
"""Fields without constraints should pass validation."""
from pydantic import BaseModel
class M(BaseModel):
@@ -535,7 +506,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint("anything", field_info) is None
def test_rejects_value_below_ge_bound(self):
"""Value below ge (>=) bound should return error."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -549,7 +519,6 @@ class TestValidateFieldConstraint:
assert "0" in result
def test_accepts_value_at_ge_bound(self):
"""Value exactly at ge (>=) bound should pass."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -561,7 +530,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint(0, field_info) is None
def test_rejects_value_above_le_bound(self):
"""Value above le (<=) bound should return error."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -575,7 +543,6 @@ class TestValidateFieldConstraint:
assert "10" in result
def test_accepts_value_at_le_bound(self):
"""Value exactly at le (<=) bound should pass."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -587,7 +554,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint(10, field_info) is None
def test_combined_ge_and_le_bounds(self):
"""Field with both ge and le should validate both."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -601,7 +567,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint(11, field_info) is not None
def test_gt_and_lt_bounds(self):
"""Strict inequality bounds (gt, lt) should exclude boundary."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -615,7 +580,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint(1.0, field_info) is not None
def test_min_length_constraint(self):
"""min_length should validate string/list length."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -628,7 +592,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint("", field_info) is not None
def test_max_length_constraint(self):
"""max_length should validate string/list length."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -641,7 +604,6 @@ class TestValidateFieldConstraint:
assert _validate_field_constraint("abcdef", field_info) is not None
def test_real_send_max_retries_field(self):
"""Validate against the actual ChannelsConfig.send_max_retries field."""
from nanobot.cli.onboard import _validate_field_constraint
from nanobot.config.schema import ChannelsConfig
@@ -654,10 +616,8 @@ class TestValidateFieldConstraint:
class TestGetConstraintHint:
"""Tests for _get_constraint_hint field display suffix."""
def test_no_constraints_returns_empty(self):
"""Fields without constraints should return empty string."""
from pydantic import BaseModel
class M(BaseModel):
@@ -667,7 +627,6 @@ class TestGetConstraintHint:
assert _get_constraint_hint(field_info) == ""
def test_ge_le_range(self):
"""Field with ge+le should show a min-max suffix."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -681,7 +640,6 @@ class TestGetConstraintHint:
assert ")" not in hint
def test_ge_only(self):
"""Field with only ge should show a >= suffix."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -695,7 +653,6 @@ class TestGetConstraintHint:
assert ")" not in hint
def test_le_only(self):
"""Field with only le should show a <= suffix."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -709,7 +666,6 @@ class TestGetConstraintHint:
assert ")" not in hint
def test_real_send_max_retries_hint(self):
"""Actual ChannelsConfig.send_max_retries should show a 0-10 suffix."""
from nanobot.config.schema import ChannelsConfig
field_info = ChannelsConfig.model_fields["send_max_retries"]
@@ -721,10 +677,8 @@ class TestGetConstraintHint:
class TestInputTextWithValidation:
"""Tests for _input_text integration with constraint validation."""
def test_rejects_out_of_range_int(self, monkeypatch):
"""_input_text with field_info should reject values violating ge/le constraints."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -741,7 +695,6 @@ class TestInputTextWithValidation:
assert result is None
def test_accepts_valid_int(self, monkeypatch):
"""_input_text with field_info should accept valid constrained values."""
from pydantic import BaseModel, Field
class M(BaseModel):
@@ -758,7 +711,6 @@ class TestInputTextWithValidation:
assert result == 5
def test_works_without_field_info(self, monkeypatch):
"""_input_text without field_info should work as before (no validation)."""
monkeypatch.setattr(
onboard_wizard,
"_get_questionary",
@@ -770,16 +722,13 @@ class TestInputTextWithValidation:
class TestChannelCommonRegistration:
"""Tests for Channel Common menu registration."""
def test_channel_common_in_settings_sections(self):
"""Channel Common should be registered in _SETTINGS_SECTIONS."""
from nanobot.cli.onboard import _SETTINGS_SECTIONS
assert "Channel Common" in _SETTINGS_SECTIONS
def test_channel_common_getter_returns_channels(self):
"""Channel Common getter should return config.channels."""
from nanobot.cli.onboard import _SETTINGS_GETTER
config = Config()
@@ -787,7 +736,6 @@ class TestChannelCommonRegistration:
assert result is config.channels
def test_channel_common_setter_writes_channels(self):
"""Channel Common setter should update config.channels."""
from nanobot.cli.onboard import _SETTINGS_SETTER
config = Config()
@@ -798,7 +746,6 @@ class TestChannelCommonRegistration:
assert config.channels.send_tool_hints is True
def test_channel_common_edit_preserves_extras(self):
"""Editing Channel Common should not lose per-channel extras."""
config = Config()
config.channels.feishu = {"enabled": True, "appId": "test123"}
channels = config.channels.model_copy(deep=True)
@@ -809,16 +756,13 @@ class TestChannelCommonRegistration:
class TestApiServerRegistration:
"""Tests for API Server menu registration."""
def test_api_server_in_settings_sections(self):
"""API Server should be registered in _SETTINGS_SECTIONS."""
from nanobot.cli.onboard import _SETTINGS_SECTIONS
assert "API Server" in _SETTINGS_SECTIONS
def test_api_server_getter_returns_api(self):
"""API Server getter should return config.api."""
from nanobot.cli.onboard import _SETTINGS_GETTER
config = Config()
@@ -826,7 +770,6 @@ class TestApiServerRegistration:
assert result is config.api
def test_api_server_setter_writes_api(self):
"""API Server setter should update config.api."""
from nanobot.cli.onboard import _SETTINGS_SETTER
config = Config()
@@ -899,10 +842,8 @@ class TestSelectWithBack:
class TestMainMenuInteraction:
"""Main menu navigation, save actions, and terminal input behavior."""
def test_main_menu_hides_save_actions_until_needed(self):
"""The first screen should not show save or summary actions before edits."""
from nanobot.cli.onboard import _get_main_menu_choices
clean_choices = _get_main_menu_choices(False)
@@ -919,7 +860,6 @@ class TestMainMenuInteraction:
assert "[X] Exit Without Saving" in dirty_choices
def test_run_onboard_quick_start_edit(self, monkeypatch):
"""run_onboard should route [Q] to Quick Start."""
initial_config = Config()
responses = iter([
@@ -943,7 +883,6 @@ class TestMainMenuInteraction:
assert result.config.agents.defaults.bot_name == "quickbot"
def test_main_menu_default_resets_after_returning_from_advanced(self, monkeypatch):
"""Returning from Advanced should not leave its item visually selected."""
initial_config = Config()
responses = iter([
"[A] Advanced Settings",
@@ -967,7 +906,6 @@ class TestMainMenuInteraction:
assert main_defaults == [None, None]
def test_ask_prompt_shortens_escape_timeout(self):
"""Questionary text prompts should not wait the default timeout on Escape."""
class FakePrompt:
def __init__(self):
@@ -983,7 +921,6 @@ class TestMainMenuInteraction:
assert prompt.application.timeoutlen == onboard_wizard._PROMPT_ESCAPE_TIMEOUT_SECONDS
def test_quick_start_provider_choices_include_all_chat_providers(self):
"""Quick Start should be driven by the provider registry, not a short allowlist."""
from nanobot.providers.registry import PROVIDERS
choices = onboard_wizard._get_quick_start_provider_choices()
@@ -1014,7 +951,6 @@ class TestMainMenuInteraction:
assert choices[onboard_wizard._QUICK_START_CUSTOM_PROVIDER_CHOICE] == "custom"
def test_quick_start_openai_codex_uses_oauth_and_default_model(self, monkeypatch):
"""Codex should authenticate without asking for an API key."""
config = Config()
oauth_calls: list[tuple[Config, str]] = []
model_prompts: list[tuple[str, str, str]] = []
@@ -1055,7 +991,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "openai-codex/gpt-5.6-sol"
def test_quick_start_openai_codex_login_failure_does_not_create_preset(self, monkeypatch):
"""A failed Codex login must not leave a ready-looking model preset."""
config = Config()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
@@ -1075,7 +1010,6 @@ class TestMainMenuInteraction:
assert "primary" not in config.model_presets
def test_quick_start_openai_codex_login_reuses_existing_token(self, monkeypatch):
"""Quick Start should not open a new login flow when Codex is already authenticated."""
import oauth_cli_kit
config = Config()
@@ -1127,7 +1061,6 @@ class TestMainMenuInteraction:
def test_quick_start_openai_codex_runs_interactive_login_for_bad_cached_token(
self, monkeypatch
):
"""A malformed cached token should fall back to the interactive OAuth flow."""
import oauth_cli_kit
config = Config()
@@ -1175,7 +1108,6 @@ class TestMainMenuInteraction:
assert any(r"\[red]account-123\[/red]" in str(args[0]) for args, _kwargs in printed)
def test_quick_start_codex_auth_check_ignores_unrelated_missing_env(self, monkeypatch):
"""OAuth readiness should depend only on the Codex proxy and token."""
import oauth_cli_kit
config = Config()
@@ -1193,7 +1125,6 @@ class TestMainMenuInteraction:
)
def test_quick_start_codex_auth_check_rejects_malformed_token(self, monkeypatch):
"""A malformed cached token should report not-ready instead of crashing."""
import oauth_cli_kit
monkeypatch.setattr(
@@ -1208,7 +1139,6 @@ class TestMainMenuInteraction:
)
def test_quick_start_summary_reports_missing_codex_oauth(self, monkeypatch):
"""The review step should distinguish OAuth from an API-key setup."""
config = Config()
config.model_presets["primary"] = ModelPresetConfig(
model="openai-codex/gpt-5.6-sol",
@@ -1235,7 +1165,6 @@ class TestMainMenuInteraction:
assert rows["WebSocket channel"] == "enabled"
def test_quick_start_provider_choice_skips_advanced_prompts(self, monkeypatch):
"""The beginner path should ask for provider credentials and model."""
config = Config()
def fail_websocket_config(*_args, **_kwargs):
@@ -1285,7 +1214,6 @@ class TestMainMenuInteraction:
assert websocket["tokenIssueSecret"] == "webui-secret"
def test_quick_start_provider_menu_escape_returns_back(self, monkeypatch):
"""Esc from the first Quick Start menu should return to the main menu."""
config = Config()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
@@ -1299,7 +1227,6 @@ class TestMainMenuInteraction:
assert "primary" not in config.model_presets
def test_quick_start_provider_back_skips_pause(self, monkeypatch):
"""Returning from Quick Start should not require an extra Enter key press."""
config = Config()
pause_messages: list[str] = []
@@ -1324,7 +1251,6 @@ class TestMainMenuInteraction:
assert pause_messages == []
def test_quick_start_websocket_decline_rolls_back_provider_defaults(self, monkeypatch):
"""A failed WebSocket step should not leave saveable Quick Start defaults behind."""
config = Config()
original = config.model_dump(by_alias=True)
@@ -1359,7 +1285,6 @@ class TestMainMenuInteraction:
assert getattr(config.channels, "websocket", None) is None
def test_quick_start_provider_choice_asks_for_model_id(self, monkeypatch):
"""Known providers should ask users for the model instead of fetching one."""
config = Config()
model_prompts: list[tuple[str, str, str]] = []
@@ -1382,7 +1307,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "openai/gpt-4o-mini"
def test_quick_start_local_provider_skips_api_key(self, monkeypatch):
"""Local providers should only need a model when they have a default base URL."""
config = Config()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
@@ -1406,7 +1330,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "llama3.2"
def test_quick_start_openai_stores_key_and_model_without_base(self, monkeypatch):
"""OpenAI should support key-only setup without storing a default base URL."""
config = Config()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
@@ -1426,7 +1349,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "gpt-4o-mini"
def test_quick_start_api_key_escape_returns_to_provider_choice(self, monkeypatch):
"""Esc from an API-key prompt should go back to provider selection."""
config = Config()
provider_answers = iter(["DeepSeek", "OpenAI"])
api_key_answers = iter([onboard_wizard._BACK_PRESSED, "sk-openai-test"])
@@ -1454,7 +1376,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].provider == "openai"
def test_quick_start_zhipu_coding_plan_uses_coding_base_url(self, monkeypatch):
"""Zhipu Coding Plan should not use the standard Zhipu base URL."""
config = Config()
choices = iter(["Zhipu AI", "Coding Plan"])
@@ -1475,7 +1396,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "glm-4.6"
def test_quick_start_minimax_mainland_token_plan_uses_mainland_base_url(self, monkeypatch):
"""MiniMax mainland token plan should not use the global MiniMax base URL."""
config = Config()
choices = iter(["MiniMax", "Mainland China Token Plan"])
@@ -1496,7 +1416,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "MiniMax-M2"
def test_quick_start_stepfun_step_plan_uses_plan_base_url(self, monkeypatch):
"""StepFun Step Plan should not use the standard StepFun base URL."""
config = Config()
choices = iter(["Step Fun", "Step Plan"])
@@ -1517,7 +1436,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "step-3.5-flash"
def test_quick_start_xiaomi_mimo_token_plan_uses_token_plan_base_url(self, monkeypatch):
"""Xiaomi MiMo Token Plan should not use the standard MiMo base URL."""
config = Config()
choices = iter(["Xiaomi MIMO", "Token Plan"])
@@ -1538,7 +1456,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "mimo-v2.5-pro"
def test_quick_start_custom_base_url_asks_for_model_id(self, monkeypatch):
"""Custom providers should ask for base URL and model ID."""
config = Config()
text_answers = iter(["sk-custom-test", "https://api.example.test/v1"])
@@ -1563,7 +1480,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "custom-model"
def test_quick_start_provider_without_default_base_url_prompts_for_base(self, monkeypatch):
"""Providers that require an endpoint should ask for a base URL in Quick Start."""
config = Config()
text_answers = iter(["azure-key", "https://azure.example.test/openai"])
@@ -1584,7 +1500,6 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].model == "deployment-name"
def test_quick_start_websocket_step_explains_channel_enablement(self, monkeypatch):
"""Quick Start should confirm and protect WebSocket for WebUI."""
config = Config()
messages: list[str] = []
@@ -1616,7 +1531,6 @@ class TestMainMenuInteraction:
assert websocket["tokenIssueSecret"] == "webui-secret"
def test_quick_start_websocket_step_can_be_declined(self, monkeypatch):
"""Declining WebSocket should stop Quick Start before changing channel config."""
config = Config()
class FakePrompt:
@@ -1638,7 +1552,6 @@ class TestMainMenuInteraction:
assert getattr(config.channels, "websocket", None) is None
def test_quick_start_websocket_requires_password(self, monkeypatch):
"""Accepting WebSocket with an empty password should not enable the channel."""
config = Config()
class FakePrompt:
@@ -1663,7 +1576,6 @@ class TestMainMenuInteraction:
assert getattr(config.channels, "websocket", None) is None
def test_quick_start_requires_api_key_before_setting_defaults(self, monkeypatch):
"""Quick Start should not create a ready-looking config without an API key."""
config = Config()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
@@ -1679,7 +1591,6 @@ class TestMainMenuInteraction:
assert "primary" not in config.model_presets
def test_quick_start_requires_model_id_before_setting_defaults(self, monkeypatch):
"""Quick Start should not create a preset without an explicit model ID."""
config = Config()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
@@ -1694,7 +1605,6 @@ class TestMainMenuInteraction:
assert "primary" not in config.model_presets
def test_quick_start_summary_calls_out_missing_api_key(self, monkeypatch):
"""Quick Start summary should retain the missing-key status."""
config = Config()
config.model_presets["primary"] = ModelPresetConfig(
model="deepseek-v4-flash",
@@ -1717,7 +1627,6 @@ class TestMainMenuInteraction:
assert rows["WebSocket channel"] == "enabled"
def test_configure_login_channel_defaults_to_login(self, monkeypatch):
"""The channel wizard should start login before exposing advanced fields."""
from nanobot.channels.base import BaseChannel
config = Config()
@@ -1771,7 +1680,6 @@ class TestMainMenuInteraction:
assert calls == {"force": False}
def test_run_onboard_channel_common_edit(self, monkeypatch):
"""run_onboard should handle [H] Channel Common through Advanced Settings."""
initial_config = Config()
responses = iter([
@@ -1801,7 +1709,6 @@ class TestMainMenuInteraction:
assert result.config.channels.send_tool_hints is True
def test_run_onboard_api_server_edit(self, monkeypatch):
"""run_onboard should handle [I] API Server through Advanced Settings."""
initial_config = Config()
responses = iter([
@@ -1831,7 +1738,6 @@ class TestMainMenuInteraction:
assert result.config.api.port == 9999
def test_view_summary_calls_pause(self, monkeypatch):
"""Advanced [V] View Summary should pause before returning to the menu."""
initial_config = Config()
pause_called = {"n": 0}
@@ -1853,9 +1759,7 @@ class TestMainMenuInteraction:
monkeypatch.setattr(onboard_wizard, "_show_main_menu_header", lambda: None)
monkeypatch.setattr(onboard_wizard, "_select_with_back", fake_select_with_back)
# _pause is called inside _show_summary, so we patch it there
monkeypatch.setattr(onboard_wizard, "_pause", fake_pause)
# Suppress summary output but still call _pause
monkeypatch.setattr(onboard_wizard, "_print_summary_panel", lambda *a, **kw: None)
monkeypatch.setattr(onboard_wizard, "_get_provider_names", lambda: {})
monkeypatch.setattr(onboard_wizard, "_get_channel_names", lambda: {})
@@ -1867,10 +1771,8 @@ class TestMainMenuInteraction:
class TestInputTextEmptyString:
"""Tests for _input_text empty-string handling bug fix."""
def test_empty_string_returned_not_none(self, monkeypatch):
"""_input_text should return empty string, not None, when user enters ''."""
monkeypatch.setattr(
onboard_wizard,
"_get_questionary",
@@ -1881,7 +1783,6 @@ class TestInputTextEmptyString:
assert result == ""
def test_none_still_returns_none(self, monkeypatch):
"""_input_text should return None when questionary returns None."""
monkeypatch.setattr(
onboard_wizard,
"_get_questionary",
@@ -1892,7 +1793,6 @@ class TestInputTextEmptyString:
assert result is None
def test_escape_returns_back_pressed(self, monkeypatch):
"""_input_text should preserve the local back sentinel."""
monkeypatch.setattr(
onboard_wizard,
"_get_questionary",
@@ -1906,7 +1806,6 @@ class TestInputTextEmptyString:
class TestIsStrOrNone:
"""Tests for _is_str_or_none helper."""
def test_str_or_none_true(self):
from nanobot.cli.onboard import _is_str_or_none
@@ -1932,10 +1831,8 @@ class TestIsStrOrNone:
class TestConfigurePydanticModelEmptyString:
"""Tests that optional string fields are cleared when empty string is entered."""
def test_optional_str_empty_string_becomes_none(self, monkeypatch):
"""Entering '' for an optional str field should set it to None."""
from pydantic import BaseModel
@@ -1948,7 +1845,6 @@ class TestConfigurePydanticModelEmptyString:
def fake_select(_prompt, choices, default=None):
call_count["select"] += 1
# First call: select the api_key field, then Done
if call_count["select"] == 1:
for c in choices:
if "Api Key" in c:
@@ -1958,7 +1854,6 @@ class TestConfigurePydanticModelEmptyString:
monkeypatch.setattr(onboard_wizard, "_select_with_back", fake_select)
monkeypatch.setattr(onboard_wizard, "_show_config_panel", lambda *a, **kw: None)
# Simulate user entering empty string
monkeypatch.setattr(
onboard_wizard, "_input_with_existing", lambda *a, **kw: ""
)
@@ -1968,7 +1863,6 @@ class TestConfigurePydanticModelEmptyString:
assert result.api_key is None
def test_required_str_empty_string_kept(self, monkeypatch):
"""Entering '' for a required str field should keep the empty string."""
from pydantic import BaseModel
class M(BaseModel):
@@ -1999,10 +1893,8 @@ class TestConfigurePydanticModelEmptyString:
class TestModelPresetWizard:
"""Tests for model preset CRUD in the onboard wizard."""
def test_sync_preset_cache(self):
"""_sync_preset_cache should populate the module-level cache."""
from nanobot.cli.onboard import _MODEL_PRESET_CACHE, _sync_preset_cache
from nanobot.config.schema import ModelPresetConfig
@@ -2014,7 +1906,6 @@ class TestModelPresetWizard:
_MODEL_PRESET_CACHE.clear()
def test_model_preset_add(self, monkeypatch):
"""_configure_model_presets should add a new preset."""
from nanobot.cli.onboard import _MODEL_PRESET_CACHE, _configure_model_presets
from nanobot.config.schema import ModelPresetConfig
@@ -2057,7 +1948,6 @@ class TestModelPresetWizard:
_MODEL_PRESET_CACHE.clear()
def test_model_preset_delete(self, monkeypatch):
"""_configure_model_presets should delete an existing preset."""
from nanobot.cli.onboard import _MODEL_PRESET_CACHE, _configure_model_presets
from nanobot.config.schema import ModelPresetConfig
@@ -2105,7 +1995,6 @@ class TestModelPresetWizard:
_MODEL_PRESET_CACHE.clear()
def test_model_preset_field_handler(self, monkeypatch):
"""_handle_model_preset_field should set a preset name from choices."""
from nanobot.cli.onboard import _MODEL_PRESET_CACHE, _handle_model_preset_field
from nanobot.config.schema import AgentDefaults
@@ -2120,7 +2009,6 @@ class TestModelPresetWizard:
_MODEL_PRESET_CACHE.clear()
def test_model_preset_field_handler_clear(self, monkeypatch):
"""_handle_model_preset_field should clear preset when Clear value is chosen."""
from nanobot.cli.onboard import (
_CLEAR_CHOICE,
_MODEL_PRESET_CACHE,
@@ -2139,7 +2027,6 @@ class TestModelPresetWizard:
_MODEL_PRESET_CACHE.clear()
def test_run_onboard_model_presets_edit(self, monkeypatch):
"""run_onboard should handle [M] Model Presets through Advanced Settings."""
from nanobot.config.schema import ModelPresetConfig
initial_config = Config()
@@ -2175,7 +2062,6 @@ class TestModelPresetWizard:
assert "test" in result.config.model_presets
def test_fallback_models_field_add(self, monkeypatch):
"""_handle_fallback_models_field should add a preset name."""
from nanobot.cli.onboard import _MODEL_PRESET_CACHE, _handle_fallback_models_field
from nanobot.config.schema import AgentDefaults
@@ -2213,7 +2099,6 @@ class TestModelPresetWizard:
_MODEL_PRESET_CACHE.clear()
def test_provider_field_handler(self, monkeypatch):
"""_handle_provider_field should set provider from choices."""
from nanobot.cli.onboard import _handle_provider_field
from nanobot.config.schema import AgentDefaults
@@ -2224,7 +2109,6 @@ class TestModelPresetWizard:
assert defaults.provider == "anthropic"
def test_search_provider_field_handler(self, monkeypatch):
"""_handle_search_provider_field should set the search engine from choices."""
from nanobot.agent.tools.web import WebSearchConfig
from nanobot.cli.onboard import _handle_search_provider_field
@@ -2235,7 +2119,6 @@ class TestModelPresetWizard:
assert cfg.provider == "keenable"
def test_provider_field_dispatch_is_model_type_aware(self):
"""WebSearchConfig.provider must not be hijacked by the LLM provider handler."""
from nanobot.agent.tools.web import WebSearchConfig
from nanobot.cli.onboard import (
_handle_provider_field,
@@ -1,5 +1,3 @@
"""Inline reasoning should not change when a provider splits its stream."""
import pytest
from nanobot.agent.hook import AgentHookContext
@@ -1,5 +1,3 @@
"""Prompt preparation must leave the public runtime responsive."""
import asyncio
import threading
from copy import deepcopy
@@ -156,14 +154,12 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
assert final_loop is runtime_loop
if phase != "prompt":
assert snapshot
# 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()
@@ -183,7 +179,6 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
with pytest.raises(asyncio.CancelledError):
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"
release.set()
await asyncio.wait_for(finished.wait(), 5)
@@ -416,7 +411,6 @@ async def test_cancelled_prompt_keeps_its_worker_slot_until_read_finishes() -> N
second = asyncio.create_task(runner.prepare_prompt(read, "second"))
tasks.append(second)
await asyncio.sleep(0)
# The cancelled caller's read keeps its slot until the worker exits.
assert not entered["second"].is_set()
released["first"].set()
await asyncio.wait_for(entered["second"].wait(), timeout=5)
-6
View File
@@ -1,5 +1,3 @@
"""Actual invocation identity survives delivery and the display transcript."""
import asyncio
import json
from copy import deepcopy
@@ -105,7 +103,6 @@ async def test_actual_candidate_is_delivered_and_replayed(history,
}
recorder.prepare_event("chat", record, metadata=msg.metadata, phase="answer", include_source=True)
records.append(record)
# Completed segment is the durable record; token-sized deltas aren't needed on replay.
for record in (r for r in records if r["event"] != "delta"):
history.append("websocket:chat", record)
replay = history.build("websocket:chat")
@@ -169,7 +166,6 @@ async def test_auxiliary_calls_do_not_publish_response_identity():
@pytest.mark.parametrize("with_images", [False, True])
@pytest.mark.parametrize("fallback", [False, True])
async def test_attribution_does_not_change_provider_requests(with_tools, with_images, fallback):
"""Display metadata must not modify the cacheable prompt or generation payload."""
requests = []
class CapturingProvider(AnswerProvider):
@@ -345,7 +341,6 @@ async def test_runner_records_each_provider_when_streaming_times_out_and_recover
assert [m.metadata["response_sources"][0]["preset"] for m in ends if m.metadata["response_sources"]] == ["codex", "grok"]
assert [m.metadata["response_sources"][0]["fallback"] for m in ends if m.metadata["response_sources"]] == [False, True]
assert len({m.event.stream_id for m in ends}) == len(ends)
# Display provenance stays out of canonical model input/history.
assert all("response_sources" not in message for message in result.messages)
@@ -370,7 +365,6 @@ async def test_websocket_wire_and_disk_replay_preserve_sources(history, tmp_path
if temporary:
assert history.read("websocket:source-chat") == []
else:
# A fresh reader after an unrelated preset rename/delete sees the saved snapshot.
sources[0]["preset"] = "renamed later"
replay = history.build("websocket:source-chat")
assert replay is not None
+3 -21
View File
@@ -1,6 +1,3 @@
"""Tests for core AgentRunner behavior: message passing, iteration limits,
empty-response handling, usage accumulation, and config passthrough."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
@@ -767,7 +764,6 @@ async def test_runner_replaces_empty_tool_result_with_marker():
@pytest.mark.asyncio
async def test_runner_retries_empty_final_response_with_summary_prompt():
"""Empty responses get 2 silent retries before finalization kicks in."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
@@ -801,7 +797,6 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
))
assert result.final_content == "final answer"
# 2 silent retries (iterations 0,1) + finalization on iteration 1
assert len(calls) == 3
assert calls[0]["tools"] is not None
assert calls[1]["tools"] is not None
@@ -881,7 +876,6 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
@pytest.mark.asyncio
async def test_runner_uses_specific_message_after_empty_finalization_retry():
"""After silent retries + finalization all return empty, stop_reason is empty_final_response."""
from nanobot.agent.runner import AgentRunner
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
@@ -959,7 +953,6 @@ async def test_empty_finalization_retry_discards_candidate_provider_state():
@pytest.mark.asyncio
async def test_runner_length_recovery_returns_all_segments():
"""Recovered output segments are returned together instead of only the tail."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
@@ -991,7 +984,6 @@ async def test_runner_length_recovery_returns_all_segments():
@pytest.mark.asyncio
async def test_runner_length_recovery_preserves_prefix_at_max_iterations():
"""Budget exhaustion must not replace output already produced by recovery."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
@@ -1025,7 +1017,6 @@ async def test_runner_length_recovery_preserves_prefix_at_max_iterations():
@pytest.mark.asyncio
async def test_runner_length_recovery_does_not_leak_across_tool_calls():
"""A recovered prefix belongs only to its contiguous response chain."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
@@ -1116,7 +1107,6 @@ async def test_runner_empty_response_does_not_break_tool_chain():
@pytest.mark.asyncio
async def test_runner_accumulates_usage_and_preserves_cache_reads():
"""Runner accumulates usage across iterations, including cache reads."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
@@ -1150,11 +1140,10 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
))
# Usage should be accumulated across iterations
assert result.usage is not None
assert result.usage.input_tokens == 300 # 100 + 200
assert result.usage.output_tokens == 30 # 10 + 20
assert result.usage.cache_read_tokens == 230 # 80 + 150
assert result.usage.input_tokens == 300
assert result.usage.output_tokens == 30
assert result.usage.cache_read_tokens == 230
assert result.usage.context_tokens == 200
assert result.usage.request_count == 2
assert [
@@ -1168,7 +1157,6 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
@pytest.mark.asyncio
async def test_runner_carries_retry_notifications_in_provider_context():
"""The runner carries a generic scope, not an event-specific callback."""
from nanobot.agent.runner import AgentRunner
from nanobot.events import EventSink, RetryWaitEvent
@@ -1204,14 +1192,8 @@ async def test_runner_carries_retry_notifications_in_provider_context():
retry_wait_cb.assert_awaited_once_with(event)
# ---------------------------------------------------------------------------
# Config passthrough tests
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_runner_passes_generation_settings_to_provider():
"""Non-default generation settings should reach provider.chat_stream_with_retry."""
from nanobot.agent.runner import AgentRunner
captured: dict = {}
-10
View File
@@ -1,6 +1,3 @@
"""Tests for AgentRunner error handling: tool errors, LLM errors,
session message isolation, and tool result preservation."""
from __future__ import annotations
import json
@@ -183,7 +180,6 @@ async def test_runner_ignores_tool_calls_when_finish_reason_blocks_execution(
finish_reason: str,
expected_stop_reason: str,
):
"""Provider/gateway-injected tool calls under terminal block reasons must not run."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
@@ -401,12 +397,10 @@ async def test_runner_preserves_tool_error_results_in_messages():
))
assert result.stop_reason == "max_iterations"
# Both tool results must be in messages even though tc2 returned an error.
tool_msgs = [m for m in result.messages if m.get("role") == "tool"]
assert len(tool_msgs) == 2
assert tool_msgs[0]["tool_call_id"] == "tc1"
assert tool_msgs[1]["tool_call_id"] == "tc2"
# The assistant message with tool_calls must precede the tool results.
asst_tc_idx = next(
i for i, m in enumerate(result.messages)
if m.get("role") == "assistant" and m.get("tool_calls")
@@ -431,8 +425,6 @@ async def test_length_finish_with_blank_content_routes_to_length_recovery():
from nanobot.utils.runtime import LENGTH_RECOVERY_PROMPT
provider = MagicMock(spec=LLMProvider)
# First call: truncated (length) with blank content and a dropped tool call.
# Second call: normal completion so the loop can terminate.
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(
content="",
@@ -454,8 +446,6 @@ async def test_length_finish_with_blank_content_routes_to_length_recovery():
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
))
# The runner must have injected a length-recovery prompt and continued,
# rather than exhausting empty-response retries into a generic apology.
user_msgs = [m.get("content") or "" for m in result.messages if m.get("role") == "user"]
assert any(LENGTH_RECOVERY_PROMPT in c for c in user_msgs), (
"expected a length-recovery message to be appended for a "
+1 -33
View File
@@ -1,5 +1,3 @@
"""Tests for FallbackProvider model failover."""
from __future__ import annotations
import asyncio
@@ -130,9 +128,6 @@ class _FakeProvider(LLMProvider):
return self.compact
# -- config-level tests --
def test_fallback_models_default_empty() -> None:
from nanobot.config.schema import AgentDefaults
@@ -358,9 +353,6 @@ def test_inline_fallback_reasoning_effort_does_not_inherit_primary() -> None:
assert provider_signature(config)[-1] != fallback_signatures
# -- FallbackProvider tests --
class TestNoFallbackWhenPrimarySucceeds:
@pytest.mark.asyncio
async def test(self) -> None:
@@ -412,7 +404,6 @@ class TestFallbackWhenPrimaryRaises:
)
@pytest.mark.asyncio
async def test_transient_exception_triggers_fallback(self, exc: Exception) -> None:
"""Transient exceptions remain eligible even when their messages are empty."""
primary = _RaisingProvider("primary", exc)
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
factory = MagicMock(return_value=fallback)
@@ -458,7 +449,6 @@ class TestFallbackWhenPrimaryRaises:
self,
stream: bool,
) -> None:
"""A retry wrapper must not hide an empty transient exception from failover."""
primary = _RaisingProvider("primary", TimeoutError())
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
factory = MagicMock(return_value=fallback)
@@ -497,7 +487,6 @@ class TestFallbackWhenPrimaryRaises:
@pytest.mark.asyncio
async def test_non_string_exception_metadata_is_normalized_before_fallback(self) -> None:
"""Provider exception metadata must be string-like before fallback consumes it."""
class NumericMetadataError(Exception):
error_type = 429
@@ -529,7 +518,6 @@ class TestFallbackWhenPrimaryRaises:
async def test_non_fallbackable_primary_exception_does_not_trigger_fallback(
self, exc: Exception,
) -> None:
"""An unrelated provider bug must not silently switch models."""
primary = _RaisingProvider("primary", exc)
factory = MagicMock(
return_value=_FakeProvider("fallback", _make_response("fallback"))
@@ -552,7 +540,6 @@ class TestFallbackWhenPrimaryRaises:
@pytest.mark.asyncio
async def test_fallback_exception_advances_to_next_fallback(self) -> None:
"""A fallback whose chat() raises must advance to the next fallback."""
primary = _FakeProvider("primary", _error_response())
raising_fb = _RaisingProvider("fb1")
ok_fb = _FakeProvider("fb2", _make_response("second fallback ok"))
@@ -570,7 +557,6 @@ class TestFallbackWhenPrimaryRaises:
@pytest.mark.asyncio
async def test_primary_exception_stream_triggers_fallback(self) -> None:
"""Streaming path: a raising primary still fails over when nothing streamed."""
primary = _RaisingProvider("primary")
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
factory = MagicMock(return_value=fallback)
@@ -587,7 +573,6 @@ class TestFallbackWhenPrimaryRaises:
@pytest.mark.asyncio
async def test_primary_exception_after_streaming_does_not_duplicate_output(self) -> None:
"""Once content was emitted, an exception must not start a replacement stream."""
primary = _StreamingThenRaisingProvider("primary")
factory = MagicMock(return_value=_FakeProvider("fallback", _make_response("duplicate")))
deltas: list[str] = []
@@ -613,7 +598,6 @@ class TestFallbackWhenPrimaryRaises:
@pytest.mark.asyncio
async def test_primary_cancellation_is_not_converted_to_failover(self) -> None:
"""Task cancellation must retain asyncio cancellation semantics."""
primary = _RaisingProvider("primary", asyncio.CancelledError())
factory = MagicMock(return_value=_FakeProvider("fallback", _make_response("fallback")))
fb = FallbackProvider(
@@ -1081,11 +1065,9 @@ class TestFallbackOnStreamStalledAfterContent:
class TestFailoverOnEmptyChoices:
"""Fallback should trigger when API returns empty choices (no error metadata)."""
@pytest.mark.asyncio
async def test_empty_choices_text_fallback(self) -> None:
"""_should_fallback should return True for 'API returned empty choices'."""
from nanobot.providers.fallback_provider import FallbackProvider
response = _make_response(
@@ -1093,25 +1075,20 @@ class TestFailoverOnEmptyChoices:
finish_reason="error",
error_kind="empty",
)
# error_kind="empty" matches _FALLBACK_ERROR_KINDS via kind check
assert FallbackProvider._should_fallback(response)
@pytest.mark.asyncio
async def test_empty_choices_no_error_kind_text_fallback(self) -> None:
"""_should_fallback should also match via text token when error_kind is None."""
from nanobot.providers.fallback_provider import FallbackProvider
response = _make_response(
"Error: API returned empty choices.",
finish_reason="error",
# error_kind=None, no status — pure text matching
)
# "empty" token in _FALLBACK_ERROR_TOKENS matches via text fallback
assert FallbackProvider._should_fallback(response)
@pytest.mark.asyncio
async def test_empty_choices_triggers_failover(self) -> None:
"""End-to-end: empty choices on primary triggers fallback."""
primary = _FakeProvider(
"primary",
_make_response("Error: API returned empty choices.", finish_reason="error"),
@@ -1189,7 +1166,6 @@ class TestRetryBeforeFailover:
assert result.finish_reason == "error"
events = [call.args[0] for call in observe.await_args_list]
notices = [event.content for event in events if isinstance(event, RetryWaitEvent)]
# Two candidates, three waits each, for two chains, plus one chain wait.
assert len(notices) == 14
assert sum("Persistent retry stopped" in text for text in notices) == 1
assert not any("giving up" in text for text in notices)
@@ -1312,7 +1288,7 @@ class TestRetryBeforeFailover:
assert len(fallback.chat_calls) == 1
assert LLMProvider.public_error_kind(result) == "connection"
assert result.preserve_provider_state_on_error is True
assert not LLMProvider.is_transient_response(result) # Retry policy is still terminal.
assert not LLMProvider.is_transient_response(result)
assert statuses[-1] == RetryStatusEvent(
state="exhausted", attempt=4, max_attempts=4, error_kind="connection",
)
@@ -1506,7 +1482,6 @@ class TestFailoverOnArrearageError:
@pytest.mark.asyncio
async def test_insufficient_credits_on_400_tries_configured_fallback(self) -> None:
"""Some OpenAI-compatible gateways report exhausted credits as HTTP 400."""
arrearage = _make_response(
"[400]: You have insufficient credits to make this request.",
finish_reason="error",
@@ -1532,7 +1507,6 @@ class TestFailoverOnArrearageError:
@pytest.mark.asyncio
async def test_plain_bad_request_still_does_not_fall_back(self) -> None:
"""A 400 with no billing semantics stays non-fallbackable."""
bad_request = _make_response(
"invalid parameter: temperature must be <= 2",
finish_reason="error",
@@ -1869,7 +1843,6 @@ class TestNoFallbackWhenEmptyList:
class TestChatStreamFailover:
@pytest.mark.asyncio
async def test_fallback_succeeds(self) -> None:
# Use empty content so on_content_delta is not triggered on the error
primary = _FakeProvider("primary", _error_response(""))
fallback = _FakeProvider("fallback", _make_response("stream ok"))
factory = MagicMock(return_value=fallback)
@@ -1924,14 +1897,12 @@ class TestCircuitBreaker:
provider_factory=factory,
)
# 3 failures — primary should still be called each time
for _ in range(3):
result = await fb.chat(messages=[{"role": "user", "content": "hi"}])
assert result.content == "fallback ok"
assert len(primary.chat_calls) == 3
# 4th call — primary circuit is open, should be skipped
primary.chat_calls.clear()
result = await fb.chat(messages=[{"role": "user", "content": "hi"}])
assert result.content == "fallback ok"
@@ -1948,16 +1919,13 @@ class TestCircuitBreaker:
provider_factory=factory,
)
# 2 failures
for _ in range(2):
await fb.chat(messages=[{"role": "user", "content": "hi"}])
# 3rd call: primary succeeds — circuit resets
primary._response = _make_response("primary ok")
result = await fb.chat(messages=[{"role": "user", "content": "hi"}])
assert result.content == "primary ok"
# 4th call: primary fails again — should still be called (counter reset)
primary._response = _error_response()
primary.chat_calls.clear()
result = await fb.chat(messages=[{"role": "user", "content": "hi"}])
-3
View File
@@ -1,5 +1,3 @@
"""File-read deduplication follows the model request, including context rewrites."""
import asyncio
from copy import deepcopy
from unittest.mock import AsyncMock, MagicMock
@@ -164,7 +162,6 @@ async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, ope
assert "data.txt" in results[0]
else:
assert results == [contents]
# A later direct read has no model input proving that its contents are visible.
assert await tools.execute("read_file", {"path": "data.txt"}) == contents
-2
View File
@@ -1,5 +1,3 @@
"""Caller-controlled continuation respects live state and the runner budget."""
from unittest.mock import AsyncMock, MagicMock
import pytest
+3 -20
View File
@@ -1,5 +1,3 @@
"""Tests for AgentRunner context governance, repair, and compaction."""
from __future__ import annotations
import asyncio
@@ -647,7 +645,6 @@ async def test_runner_recovers_oversized_file_read_delta(
})
for index, path in enumerate(paths)
]
# Retrying the omitted file alone must return its content, not "unchanged".
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=calls, provider_state=provider_state),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
@@ -1447,7 +1444,6 @@ async def test_runner_refuses_oversized_request_without_compactor(
async def test_backfill_missing_tool_results_inserts_error():
"""Orphaned tool_use (no matching tool_result) should get a synthetic error."""
messages = [
{"role": "user", "content": "hi"},
@@ -1505,7 +1501,6 @@ def test_drop_orphan_tool_results_removes_unmatched_tool_messages():
@pytest.mark.asyncio
async def test_backfill_noop_when_complete():
"""Complete message chains should not be modified."""
messages = [
{"role": "user", "content": "hi"},
{
@@ -1519,7 +1514,7 @@ async def test_backfill_noop_when_complete():
{"role": "assistant", "content": "all good"},
]
result = ContextGovernor.backfill_missing_tool_results(messages)
assert result is messages # same object — no copy
assert result is messages
@pytest.mark.asyncio
@@ -1563,7 +1558,6 @@ async def test_runner_drops_orphan_tool_results_before_model_request():
@pytest.mark.asyncio
async def test_backfill_repairs_model_context_without_shifting_save_turn_boundary(tmp_path):
"""Historical backfill should not duplicate old tail messages on persist."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -1645,7 +1639,6 @@ async def test_backfill_repairs_model_context_without_shifting_save_turn_boundar
@pytest.mark.asyncio
async def test_runner_backfill_only_mutates_model_context_not_returned_messages():
"""Runner should repair orphaned tool calls for the model without rewriting result.messages."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -1721,14 +1714,11 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(
]
# ---------------------------------------------------------------------------
# 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)
# ---------------------------------------------------------------------------
def test_drop_malformed_tool_calls_trims_response():
"""LLM response tool_calls with a missing/empty name are dropped in place."""
from nanobot.agent.runner import AgentRunner
candidate_state = ProviderConversationState(
@@ -1760,7 +1750,6 @@ def test_drop_malformed_tool_calls_trims_response():
def test_drop_malformed_tool_calls_all_bad_disables_execution():
"""If every tool call is malformed, execution is disabled (no empty exec)."""
from nanobot.agent.runner import AgentRunner
response = LLMResponse(
@@ -1778,7 +1767,6 @@ def test_drop_malformed_tool_calls_all_bad_disables_execution():
def test_drop_malformed_returns_tuple_no_calls():
"""No tool calls returns (0, False, current_finish_reason)."""
from nanobot.agent.runner import AgentRunner
response = LLMResponse(content="hi", finish_reason="stop")
@@ -1789,7 +1777,6 @@ def test_drop_malformed_returns_tuple_no_calls():
def test_strip_malformed_tool_calls_keeps_valid_calls_in_history():
"""A mixed assistant turn keeps only its valid tool_calls."""
messages = [
{"role": "user", "content": "hi"},
{
@@ -1803,8 +1790,8 @@ def test_strip_malformed_tool_calls_keeps_valid_calls_in_history():
{"role": "tool", "tool_call_id": "ok", "name": "exec", "content": "done"},
]
result = ContextGovernor.strip_malformed_tool_calls(messages)
assert result is not messages # copied, original untouched
assert len(messages[1]["tool_calls"]) == 2 # original preserved
assert result is not messages
assert len(messages[1]["tool_calls"]) == 2
kept = result[1]["tool_calls"]
assert [tc["function"]["name"] for tc in kept] == ["exec"]
@@ -1831,7 +1818,6 @@ def test_strip_malformed_tool_calls_drops_empty_assistant_turn():
def test_strip_malformed_tool_calls_noop_when_clean():
"""Clean history is returned unchanged (same object)."""
messages = [
{"role": "user", "content": "hi"},
{
@@ -1847,7 +1833,6 @@ def test_strip_malformed_tool_calls_noop_when_clean():
def test_strip_placeholder_assistant_messages_removes_omitted():
"""Placeholder assistant messages are removed; real messages kept."""
messages = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "real response"},
@@ -1865,7 +1850,6 @@ def test_strip_placeholder_assistant_messages_removes_omitted():
def test_strip_placeholder_noop_when_clean():
"""Clean history is returned unchanged (same object)."""
messages = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "hello back"},
@@ -1874,7 +1858,6 @@ def test_strip_placeholder_noop_when_clean():
def test_strip_placeholder_keeps_assistant_with_tool_calls():
"""A placeholder assistant that also carries tool_calls is kept."""
messages = [
{"role": "user", "content": "hi"},
{
-4
View File
@@ -1,6 +1,3 @@
"""Tests for AgentRunner hook lifecycle: ordering, streaming deltas,
cached-token propagation, and hook context."""
from __future__ import annotations
from copy import deepcopy
@@ -243,7 +240,6 @@ async def test_runner_length_recovery_streams_segments_once_and_returns_all_cont
@pytest.mark.asyncio
async def test_runner_passes_cache_read_tokens_to_hook_context():
"""Hook context usage preserves a reported cache-read count."""
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.runner import AgentRunner
-46
View File
@@ -1,5 +1,3 @@
"""Tests for the mid-turn injection system: drain, checkpoints, pending queues, error paths."""
from __future__ import annotations
import asyncio
@@ -50,7 +48,6 @@ def _make_loop(tmp_path, *, recovery_admission=None):
@pytest.mark.asyncio
async def test_drain_injections_returns_empty_when_no_callback():
"""No injection_callback → empty list."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -68,7 +65,6 @@ async def test_drain_injections_returns_empty_when_no_callback():
@pytest.mark.asyncio
async def test_drain_injections_extracts_content_from_inbound_messages():
"""Should extract .content from InboundMessage objects."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -99,7 +95,6 @@ async def test_drain_injections_extracts_content_from_inbound_messages():
@pytest.mark.asyncio
async def test_drain_injections_keeps_entire_callback_snapshot():
"""A callback snapshot is never split by an arbitrary message count."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -129,7 +124,6 @@ async def test_drain_injections_keeps_entire_callback_snapshot():
@pytest.mark.asyncio
async def test_drain_injections_skips_empty_content():
"""Messages with blank content should be filtered out."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -158,7 +152,6 @@ async def test_drain_injections_skips_empty_content():
@pytest.mark.asyncio
async def test_drain_injections_filters_empty_dict_payloads():
"""Pre-normalized dict injections should obey the same empty-content guard."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -194,7 +187,6 @@ async def test_drain_injections_filters_empty_dict_payloads():
@pytest.mark.asyncio
async def test_drain_injections_skips_objects_with_none_content():
"""Objects exposing content=None should be skipped rather than stringified."""
from types import SimpleNamespace
from nanobot.agent.runner import AgentRunner
@@ -222,7 +214,6 @@ async def test_drain_injections_skips_objects_with_none_content():
@pytest.mark.asyncio
async def test_drain_injections_handles_callback_exception():
"""If the callback raises, return empty list (error is logged)."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -244,7 +235,6 @@ async def test_drain_injections_handles_callback_exception():
@pytest.mark.asyncio
async def test_checkpoint1_injects_after_tool_execution():
"""Follow-up messages are injected after tool execution, before next LLM call."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -291,7 +281,6 @@ async def test_checkpoint1_injects_after_tool_execution():
assert result.had_injections is True
assert result.final_content == "final answer"
# The second call should have the injected user message
assert call_count["n"] == 2
last_messages = captured_messages[-1]
injected = [m for m in last_messages if m.get("role") == "user" and m.get("content") == "follow-up question"]
@@ -300,7 +289,6 @@ async def test_checkpoint1_injects_after_tool_execution():
@pytest.mark.asyncio
async def test_terminal_wait_does_not_block_next_iteration_after_tools():
"""Background waits begin only after a no-tool response is ready to finish."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -379,7 +367,6 @@ async def test_terminal_wait_does_not_block_next_iteration_after_tools():
@pytest.mark.asyncio
async def test_goal_continuation_precedes_terminal_wait():
"""An active sustained goal keeps running without joining background work."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -424,7 +411,6 @@ async def test_goal_continuation_precedes_terminal_wait():
@pytest.mark.asyncio
async def test_checkpoint2_injects_after_final_response_with_resuming_stream():
"""After final response, if injections exist, stream_end should get resuming=True."""
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -475,15 +461,12 @@ async def test_checkpoint2_injects_after_final_response_with_resuming_stream():
assert result.had_injections is True
assert result.final_content == "second answer"
assert call_count["n"] == 2
# First stream_end should have resuming=True (because injections found)
assert stream_end_calls[0] is True
# Second (final) stream_end should have resuming=False
assert stream_end_calls[-1] is False
@pytest.mark.asyncio
async def test_injected_followup_starts_new_length_recovery_chain():
"""A follow-up gets a fresh recovery budget and no content from the prior answer."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -588,7 +571,6 @@ async def test_truncated_answer_followup_requires_remaining_iteration(max_iterat
@pytest.mark.asyncio
async def test_checkpoint2_preserves_final_response_in_history_before_followup():
"""A follow-up injected after a final answer must still see that answer in history."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -644,7 +626,6 @@ async def test_checkpoint2_preserves_final_response_in_history_before_followup()
@pytest.mark.asyncio
async def test_loop_injected_followup_preserves_image_media(tmp_path):
"""Mid-turn follow-ups with images should keep multimodal content."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -901,7 +882,6 @@ async def test_subagent_pending_injection_is_hidden_history_and_not_merged(tmp_p
@pytest.mark.asyncio
async def test_model_request_merges_injected_user_messages_without_losing_media():
"""The model copy may merge follow-ups while the raw transcript keeps each event."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -970,7 +950,6 @@ async def test_model_request_merges_injected_user_messages_without_losing_media(
def test_runner_append_keeps_recovery_followups_separate() -> None:
"""Each raw follow-up keeps its own recovery identity."""
from nanobot.agent.runner import AgentRunner
from nanobot.session.recovery import PENDING_FOLLOWUP_ID_KEY
@@ -1040,7 +1019,6 @@ def test_model_request_merge_preserves_runtime_markers_with_media() -> None:
@pytest.mark.asyncio
async def test_injection_cycles_are_not_stopped_by_an_arbitrary_cap():
"""Every pending snapshot runs until the normal iteration budget is reached."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1081,7 +1059,6 @@ async def test_injection_cycles_are_not_stopped_by_an_arbitrary_cap():
@pytest.mark.asyncio
async def test_no_injections_flag_is_false_by_default():
"""had_injections should be False when no injection callback or no messages."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -1107,7 +1084,6 @@ async def test_no_injections_flag_is_false_by_default():
@pytest.mark.asyncio
async def test_followup_routed_to_pending_queue(tmp_path):
"""Unified-session follow-ups should route into the active pending queue."""
from nanobot.bus.events import InboundMessage
from nanobot.session.keys import UNIFIED_SESSION_KEY
@@ -1133,7 +1109,6 @@ async def test_followup_routed_to_pending_queue(tmp_path):
@pytest.mark.asyncio
async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path):
"""Recovery admission runs before a newer WebUI message is injected."""
from nanobot.bus.events import InboundMessage
admission = MagicMock()
@@ -1164,7 +1139,6 @@ async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path):
@pytest.mark.asyncio
async def test_unified_websocket_followup_admits_effective_session(tmp_path):
"""Recovery admission and the pending queue must use the same session key."""
from nanobot.bus.events import InboundMessage
from nanobot.session.keys import UNIFIED_SESSION_KEY
@@ -1199,7 +1173,6 @@ async def test_unified_websocket_followup_admits_effective_session(tmp_path):
@pytest.mark.asyncio
async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_path):
"""Injected results stay inside the active turn instead of opening a side turn."""
from nanobot.bus.events import InboundMessage
loop = _make_loop(tmp_path)
@@ -1236,7 +1209,6 @@ async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_pa
@pytest.mark.asyncio
async def test_pending_queue_batches_full_snapshot_before_first_model_call(tmp_path):
"""All messages waiting at the checkpoint enter one model request in order."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -1297,7 +1269,6 @@ async def test_pending_queue_batches_full_snapshot_before_first_model_call(tmp_p
@pytest.mark.asyncio
async def test_pending_queue_snapshot_excludes_messages_arriving_during_conversion(tmp_path):
"""A checkpoint is a finite snapshot even when message conversion awaits."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -1475,7 +1446,6 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
@pytest.mark.asyncio
async def test_session_inbox_is_installed_before_worker_start(tmp_path, monkeypatch):
"""A preloaded burst has one FIFO path before the worker can be scheduled."""
from nanobot.bus.events import InboundMessage, OutboundMessage
loop = _make_loop(tmp_path)
@@ -1534,7 +1504,6 @@ async def test_session_inbox_is_installed_before_worker_start(tmp_path, monkeypa
async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
tmp_path, request, monkeypatch, log_content,
):
"""Messages accumulated during a model call share its next request snapshot."""
from loguru import logger
from nanobot.agent.loop import AgentLoop
@@ -1608,7 +1577,6 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
finally:
release_first_request.set()
loop.stop()
# Shutdown drains accepted writes and closes the worker's WAL connection.
await asyncio.wait_for(run_task, timeout=30)
assert len(captured_messages) == 2
@@ -1636,7 +1604,6 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
@pytest.mark.asyncio
async def test_session_worker_processes_leftovers_without_republishing(tmp_path):
"""Messages left by one turn stay on the same FIFO worker."""
from nanobot.bus.events import InboundMessage, OutboundMessage
loop = _make_loop(tmp_path)
@@ -1667,7 +1634,6 @@ async def test_session_worker_processes_leftovers_without_republishing(tmp_path)
@pytest.mark.asyncio
async def test_drain_injections_after_recoverable_tool_error():
"""A tool error and injected follow-up continue in the same runner conversation."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1688,7 +1654,6 @@ async def test_drain_injections_after_recoverable_tool_error():
tool_calls=[ToolCallRequest(id="c1", name="exec", arguments={"cmd": "bad"})],
usage=None,
)
# Third call: respond normally to the injected follow-up.
return LLMResponse(content="reply to follow-up", tool_calls=[], usage=None)
provider.chat_stream_with_retry = chat_stream_with_retry
@@ -1716,7 +1681,6 @@ async def test_drain_injections_after_recoverable_tool_error():
assert result.had_injections is True
assert result.final_content == "reply to follow-up"
assert call_count["n"] == 3
# The injection should be in the messages history
injected = [
m for m in result.messages
if m.get("role") == "user" and m.get("content") == "follow-up after error"
@@ -1726,7 +1690,6 @@ async def test_drain_injections_after_recoverable_tool_error():
@pytest.mark.asyncio
async def test_drain_injections_on_llm_error():
"""A follow-up after an error stays raw and reaches the next model request."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1752,7 +1715,6 @@ async def test_drain_injections_on_llm_error():
finish_reason="error",
usage=None,
)
# Second call: respond normally to the injected follow-up
return LLMResponse(content="recovered answer", tool_calls=[], usage=None)
provider.chat_stream_with_retry = chat_stream_with_retry
@@ -1800,7 +1762,6 @@ async def test_drain_injections_on_llm_error():
@pytest.mark.asyncio
async def test_drain_injections_on_empty_final_response():
"""Pending injections should be drained when the runner exits due to empty response."""
from nanobot.agent.runner import _MAX_EMPTY_RETRIES, AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1818,7 +1779,6 @@ async def test_drain_injections_on_empty_final_response():
content="follow-up after empty",
))
return LLMResponse(content="", tool_calls=[], usage=None)
# After retries exhausted + injection drain, respond normally
return LLMResponse(content="answer after empty", tool_calls=[], usage=None)
provider.chat_stream_with_retry = chat_stream_with_retry
@@ -1854,7 +1814,6 @@ async def test_drain_injections_on_empty_final_response():
@pytest.mark.asyncio
@pytest.mark.parametrize("failed_stop_reason", ["error", "empty_final_response"])
async def test_late_injection_recovery_completes_and_delivers_reply(failed_stop_reason):
"""Input arriving after failure bookkeeping must not poison a recovered turn."""
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import _MAX_EMPTY_RETRIES, AgentRunner
from nanobot.agent.tools.registry import ToolRegistry
@@ -1881,8 +1840,6 @@ async def test_late_injection_recovery_completes_and_delivers_reply(failed_stop_
async def after_iteration(self, context) -> None:
if context.stop_reason == failed_stop_reason and context.error is not None:
observed_failures.append(context.error)
# The earlier final-response drain has already run. Inject at
# the late drain, after the runner has recorded the failure.
await injection_queue.put(InboundMessage(
channel="websocket",
sender_id="user",
@@ -1933,7 +1890,6 @@ async def test_late_injection_recovery_completes_and_delivers_reply(failed_stop_
@pytest.mark.asyncio
async def test_max_iterations_without_finalization_keeps_late_injection_queued():
"""Never consume a user message when no later model request can observe it."""
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1987,7 +1943,6 @@ async def test_max_iterations_without_finalization_keeps_late_injection_queued()
@pytest.mark.asyncio
async def test_max_iterations_finalization_keeps_late_injection_queued():
"""New input waits for a turn with tools instead of entering no-tools finalization."""
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -2057,7 +2012,6 @@ async def test_max_iterations_finalization_keeps_late_injection_queued():
@pytest.mark.asyncio
async def test_error_path_is_not_stopped_by_an_arbitrary_injection_cap():
"""Error recovery consumes every arrived snapshot until no follow-up remains."""
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1,5 +1,3 @@
"""Model failures retain the assistant text already delivered to the user."""
from __future__ import annotations
from copy import deepcopy
-7
View File
@@ -1,5 +1,3 @@
"""Tests for tool result persistence: large results, pruning, temp files, cleanup."""
from __future__ import annotations
import os
@@ -189,7 +187,6 @@ def test_persist_tool_result_logs_cleanup_failures(monkeypatch, tmp_path):
async def test_read_file_result_is_not_offloaded(tmp_path):
"""read_file must not trigger generic offloading (prevents persist->read->persist loops)."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock()
@@ -225,17 +222,13 @@ async def test_read_file_result_is_not_offloaded(tmp_path):
assert result.final_content == "done"
tool_message = next(msg for msg in captured_second_call if msg.get("role") == "tool")
# read_file result must NOT be offloaded to a file
assert "[tool output persisted]" not in tool_message["content"]
# read_file manages its own size; generic truncation must NOT apply
assert len(tool_message["content"]) == 20_000
# no file should have been written for this read_file call
offload_dir = tmp_path / ".nanobot" / "tool-results"
assert not any(offload_dir.rglob("call_rf.txt")) if offload_dir.exists() else True
async def test_processed_tool_result_is_stable_for_persistence_and_replay(tmp_path):
"""The content sent after a tool call must survive the session round trip unchanged."""
from nanobot.agent.loop import AgentLoop
from nanobot.agent.runner import AgentRunner
from nanobot.session.manager import Session
@@ -1,5 +1,3 @@
"""Tests for runner progress hooks and provider event routing."""
import asyncio
from unittest.mock import AsyncMock, MagicMock
@@ -1,5 +1,3 @@
"""Runner-owned tool progress rules, without session or channel setup."""
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -87,7 +85,6 @@ async def test_start_and_finish_events_emitted() -> None:
@pytest.mark.asyncio
async def test_streamed_content_is_not_repeated_before_tool_execution() -> None:
"""If content was already streamed, tool setup should not repeat it."""
provider = MagicMock()
tools = MagicMock()
tool_call = ToolCallRequest(id="call1", name="custom_tool", arguments={"path": "foo.txt"})
-12
View File
@@ -1,5 +1,3 @@
"""Tests for AgentRunner security: workspace violations, SSRF, shell guard, throttling."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
@@ -59,27 +57,22 @@ async def test_runner_does_not_abort_on_workspace_violation_anymore():
assert result.error is None
assert result.final_content == "ok, telling the user instead"
assert result.tool_events and result.tool_events[0]["status"] == "error"
# Detail still carries the workspace_violation breadcrumb for telemetry,
# but the runner did not raise.
assert "workspace_violation" in result.tool_events[0]["detail"]
def test_is_ssrf_violation_recognizes_private_url_blocks():
"""SSRF rejections are classified separately from workspace boundaries."""
ssrf_msg = "Error: Command blocked by safety guard (internal/private URL detected)"
assert is_ssrf_violation(ssrf_msg) is True
assert is_ssrf_violation(
"URL validation failed: Blocked: host resolves to private/internal address 192.168.1.2"
) is True
# Workspace-bound markers are NOT classified as SSRF.
assert is_ssrf_violation(
"Error: Command blocked by safety guard (path outside working dir)"
) is False
assert is_ssrf_violation(
"Path /tmp/x is outside allowed directory /ws"
) is False
# Deny / allowlist filter messages stay non-fatal too.
assert is_ssrf_violation(
"Error: Command blocked by deny pattern filter"
) is False
@@ -87,7 +80,6 @@ def test_is_ssrf_violation_recognizes_private_url_blocks():
@pytest.mark.asyncio
async def test_runner_returns_non_retryable_hint_on_ssrf_violation():
"""SSRF stays blocked, but the runtime gives the LLM a final chance to recover."""
provider = MagicMock()
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(
@@ -180,7 +172,6 @@ async def test_runner_lets_llm_recover_from_shell_guard_path_outside():
assert result.error is None
assert result.final_content == "recovered final answer"
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
@@ -240,12 +231,9 @@ async def test_runner_throttles_repeated_workspace_bypass_attempts():
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
))
# All 4 bypass attempts surface to the LLM (no fatal abort), and the
# runner finally completes once the LLM stops asking.
assert result.stop_reason != "tool_error"
assert result.error is None
assert result.final_content == "ok telling user"
# The third+ attempts must have been escalated -- look at the events.
escalated = [
ev for ev in result.tool_events
if ev["status"] == "error"
@@ -1,5 +1,3 @@
"""Tests for AgentRunner tool execution: batching, concurrency, exclusive tools."""
from __future__ import annotations
import asyncio
@@ -1,5 +1,3 @@
"""Model-facing search failures through real ddgs parsing and aggregation."""
from __future__ import annotations
import json
@@ -31,7 +29,6 @@ from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
],
)
async def test_ddgs_failure_reaches_model_with_observable_cause(monkeypatch, outcome, expected_header):
# Keep the released parser and aggregator, selecting one real engine offline.
engine = Wikipedia(timeout=1)
monkeypatch.setattr(DDGS, "_get_engines", lambda *_args: [engine])
requests: list[str] = []
-6
View File
@@ -1,5 +1,3 @@
"""Gateway task admission, without installing packages or contacting a model."""
import asyncio
import inspect
import json
@@ -74,7 +72,6 @@ async def test_idle_maintenance_refuses_new_work_and_abort_restores_it(agent):
assert agent.bus.inbound_size == 0
assert not agent._pending_queues
assert agent.sessions.get_existing("cli:direct") is None
# A duplicate attempt must not reopen the first maintenance window.
with pytest.raises(RuntimeMaintenanceError):
with agent.maintenance():
pytest.fail("duplicate maintenance was admitted")
@@ -396,7 +393,6 @@ async def test_exec_cleanup_is_owned_through_failure_and_retry(agent, tmp_path,
release.set()
with pytest.raises(OSError, match="cleanup was not confirmed"):
await task
# An exited parent alone cannot prove that failed process-tree cleanup settled.
assert session.process.returncode is not None
with pytest.raises(RuntimeBusyError):
with agent.maintenance():
@@ -517,14 +513,12 @@ async def test_cron_timer_waits_without_consuming_and_manual_run_is_refused(agen
if stop:
assert not ran.is_set()
else:
# A user may abort and immediately retry before this waiter resumes.
with agent.maintenance():
await asyncio.sleep(0)
assert not ran.is_set() and not timer.done()
assert cron.store_path.read_bytes() == before
async with asyncio.timeout(3):
await ran.wait()
# The scheduler cancels its previous timer when rearming itself.
await asyncio.gather(timer, return_exceptions=True)
assert len(cron.get_job(job.id).state.run_history) == 1
assert cron._timer_task is not timer and not cron._timer_task.done()
-2
View File
@@ -1,5 +1,3 @@
"""Private continuation state stays outside public conversation history."""
import json
from pathlib import Path
-2
View File
@@ -1,5 +1,3 @@
"""Session keys with punctuation and Unicode remain distinct in storage."""
from nanobot.session.manager import Session, SessionManager
-4
View File
@@ -1,5 +1,3 @@
"""Tests for SessionManager.delete_session and read_session_file."""
from pathlib import Path
from nanobot.session.manager import Session, SessionManager
@@ -17,13 +15,11 @@ def _seed(workspace: Path, key: str = "telegram:abc") -> SessionManager:
def test_delete_session_removes_file_and_invalidates_cache(tmp_path: Path) -> None:
sm = _seed(tmp_path, "telegram:abc")
assert sm.read_session_snapshot("telegram:abc") is not None
# Populate cache as a real consumer would.
cached = sm.get_or_create("telegram:abc")
assert cached.messages
assert sm.delete_session("telegram:abc") is True
assert sm.read_session_snapshot("telegram:abc") is None
# Subsequent get_or_create returns a fresh, empty Session (no stale cache).
fresh = sm.get_or_create("telegram:abc")
assert fresh.messages == []
@@ -1,5 +1,3 @@
"""Independent turns and internal controls retain their session inbox semantics."""
import asyncio
import threading
from unittest.mock import AsyncMock, MagicMock
-1
View File
@@ -202,7 +202,6 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
assert [event.content for event in events] == [f"Review {i}" for i in range(message_count)]
provenance = {"id": source.id, "name": source.name}
assert all(event.provenance["session_message"]["session"] == provenance for event in events)
# Reconnect/reload must preserve provenance, not just live events.
records = await loop.sessions.state.project_history(
target_key,
lambda history: [record_from_fact(fact, target_key) for fact in history.all_facts()],
+1 -26
View File
@@ -120,10 +120,7 @@ def test_get_history_drops_orphan_tool_results_when_window_cuts_tool_calls():
assert history[-1]["content"] == "new telegram question"
# --- Positive test: legitimate pairs survive trimming ---
def test_legitimate_tool_pairs_preserved_after_trim():
"""Complete tool-call groups within the window must not be dropped."""
session = Session(key="test:positive")
session.messages.append({"role": "user", "content": "hello"})
for i in range(5):
@@ -137,10 +134,7 @@ def test_legitimate_tool_pairs_preserved_after_trim():
assert history[0]["role"] == "user"
# --- last_archived > 0 ---
def test_orphan_trim_with_last_archived():
"""Orphan trimming works correctly when a session is partially archived."""
session = Session(key="test:consolidated")
for i in range(10):
session.messages.append({"role": "user", "content": f"old {i}"})
@@ -241,8 +235,6 @@ def test_archived_tool_turn_stays_out_of_replay():
assert len(session.messages) > 8
# --- Edge: no tool messages at all ---
def test_no_tool_messages_unchanged():
session = Session(key="test:plain")
for i in range(5):
@@ -254,10 +246,7 @@ def test_no_tool_messages_unchanged():
_assert_no_orphans(history)
# --- Edge: all leading messages are orphan tool results ---
def test_all_orphan_prefix_stripped():
"""If the window starts with orphan tool results and nothing else, they're all dropped."""
session = Session(key="test:all-orphan")
session.messages.append({"role": "tool", "tool_call_id": "gone_1", "name": "x", "content": "ok"})
session.messages.append({"role": "tool", "tool_call_id": "gone_2", "name": "y", "content": "ok"})
@@ -270,8 +259,6 @@ def test_all_orphan_prefix_stripped():
assert len(history) == 2
# --- Edge: empty session ---
def test_empty_session_history():
session = Session(key="test:empty")
history = session.get_history(max_messages=500)
@@ -306,7 +293,6 @@ def test_get_history_preserves_reasoning_content():
def test_get_history_does_not_inject_persisted_timestamps_into_replay_content():
"""Persisted timestamps are session metadata, not prompt content."""
session = Session(key="test:timestamps")
session.messages.append({
"role": "user",
@@ -336,7 +322,6 @@ def test_get_history_does_not_inject_persisted_timestamps_into_replay_content():
def test_get_history_keeps_proactive_delivery_timestamps_out_of_replay_content():
"""Timestamp metadata remains persisted without becoming prompt text."""
session = Session(key="test:proactive-timestamps")
session.messages.append({
"role": "assistant",
@@ -379,10 +364,7 @@ def test_get_history_does_not_inject_tool_result_timestamps():
assert tool_result["content"] == "ok"
# --- Window cuts mid-group: assistant present but some tool results orphaned ---
def test_window_cuts_mid_tool_group():
"""If the window starts between an assistant's tool results, the partial group is trimmed."""
session = Session(key="test:mid-cut")
session.messages.append({"role": "user", "content": "setup"})
session.messages.append({
@@ -398,16 +380,11 @@ def test_window_cuts_mid_tool_group():
session.messages.extend(_tool_turn("intact", 0))
session.messages.append({"role": "assistant", "content": "final"})
# Window of 6 should cut off the "setup" user msg and the assistant with split_a/split_b,
# leaving orphan tool results for split_a at the front.
history = session.get_history(max_messages=6)
_assert_no_orphans(history)
assert history[0]["role"] == "user"
# --- Image breadcrumbs: media kwarg is synthesized into content for replay ---
def test_get_history_synthesizes_image_breadcrumb_from_media_kwarg():
"""Persisted user turns carry image paths as a ``media`` kwarg; LLM
replay must still see an ``[image: path]`` breadcrumb so the assistant's
@@ -671,12 +648,10 @@ def test_get_history_ignores_media_kwarg_on_non_user_rows():
{
"role": "assistant",
"content": [{"type": "text", "text": "structured"}],
"media": ["/m/x.png"], # nonsense but shouldn't crash
"media": ["/m/x.png"],
}
)
history = session.get_history(max_messages=500)
# List content is passed through verbatim — the synthesizer only
# rewrites plain-string content.
assert history[0]["content"] == [{"type": "text", "text": "structured"}]
-11
View File
@@ -1,5 +1,3 @@
"""Tests for nanobot.agent.skills.SkillsLoader."""
from __future__ import annotations
import json
@@ -541,11 +539,7 @@ def test_prompt_reads_skills_once_and_refreshes_on_next_build(
assert checks == ["prompt-test-cli"]
# -- multiline description tests (YAML folded > and literal |) -----------------
def test_build_skills_summary_folded_description(tmp_path: Path) -> None:
"""description: > (YAML folded scalar) should be parsed correctly."""
workspace = tmp_path / "ws"
ws_skills = workspace / "skills"
ws_skills.mkdir(parents=True)
@@ -571,7 +565,6 @@ def test_build_skills_summary_folded_description(tmp_path: Path) -> None:
def test_build_skills_summary_literal_description(tmp_path: Path) -> None:
"""description: | (YAML literal scalar) should be parsed correctly."""
workspace = tmp_path / "ws"
ws_skills = workspace / "skills"
ws_skills.mkdir(parents=True)
@@ -600,7 +593,6 @@ def test_build_skills_summary_literal_description(tmp_path: Path) -> None:
def test_get_skill_metadata_handles_yaml_types(tmp_path: Path) -> None:
"""yaml.safe_load returns native types; always should be True, not 'true'."""
workspace = tmp_path / "ws"
ws_skills = workspace / "skills"
ws_skills.mkdir(parents=True)
@@ -622,14 +614,11 @@ def test_get_skill_metadata_handles_yaml_types(tmp_path: Path) -> None:
loader = SkillsLoader(workspace, builtin_skills_dir=builtin)
meta = loader.get_skill_metadata("typed")
assert meta is not None
# YAML parsed 'true' to Python True
assert meta.get("always") is True
# metadata is a parsed dict, not a JSON string
assert isinstance(meta.get("metadata"), dict)
def test_check_requirements_tolerates_null_requires_and_lists(tmp_path: Path) -> None:
"""Null requires/bins/env must not crash skill listing (JSON/YAML nulls)."""
workspace = tmp_path / "ws"
ws_skills = workspace / "skills"
ws_skills.mkdir(parents=True)
@@ -118,7 +118,6 @@ async def test_dispatch_cancellation_restores_checkpoint():
@pytest.mark.asyncio
async def test_dispatch_cancellation_keeps_checkpoint_for_gateway_shutdown(tmp_path: Path) -> None:
"""Gateway shutdown preserves the checkpoint; an explicit stop restores it."""
loop = _make_loop(tmp_path)
loop.preserve_inflight_turns_on_shutdown()
checkpoint_key = RUNTIME_CHECKPOINT_KEY
-4
View File
@@ -1,5 +1,3 @@
"""Tests for SubagentManager."""
import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
@@ -25,7 +23,6 @@ def _runtime(provider: LLMProvider) -> LLMRuntime:
@pytest.mark.asyncio
async def test_subagent_uses_tool_loader():
"""Verify subagent registers tools via ToolLoader, not hard-coded imports."""
provider = MagicMock(spec=LLMProvider)
provider.get_default_model.return_value = "test"
sm = SubagentManager(
@@ -47,7 +44,6 @@ async def test_subagent_uses_tool_loader():
@pytest.mark.asyncio
async def test_subagent_build_tools_isolates_file_read_state(tmp_path):
"""Each spawned subagent needs a fresh file-state cache."""
(tmp_path / "note.txt").write_text("hello\n", encoding="utf-8")
provider = MagicMock(spec=LLMProvider)
provider.get_default_model.return_value = "test"
@@ -1,5 +1,3 @@
"""Public construction and execution contracts for subagent consolidation."""
import asyncio
import hashlib
import json
@@ -44,7 +42,6 @@ class _EvidenceProvider(LLMProvider):
return "test"
def estimate_prompt_tokens(self, messages, tools, model):
# Deterministic provider counter; no tokenizer cache or network dependency.
return len(json.dumps([messages, tools])) // 2, "test-provider"
async def chat(self, messages, tools=None, **kwargs):
+1 -6
View File
@@ -1,5 +1,3 @@
"""Private task ownership, message receipts, cancellation, and shell lifetime."""
import asyncio
import json
import os
@@ -300,7 +298,6 @@ async def test_owner_canonical_fallback_and_absent_context(tmp_path):
for action in [None, "send", "cancel"]:
assert await control(manager, stranger, task_id, action, "secret") == denied
assert await control(manager, ctx, "missing") == denied
# Canonical identity, not the transport route, owns the task.
same_owner = RequestContext("cli", "different", session_key="owner")
assert json.loads(await control(manager, same_owner, task_id))["result"] == "private"
fallback = RequestContext("cli", "fallback", runtime=ctx.runtime)
@@ -600,7 +597,6 @@ async def test_real_task_process_cleanup_preserves_sibling_parent_and_work_produ
return AgentRunResult(messages=[], final_content="finished")
manager.runner.run = run
# The parent's exec manager must not be closed by task cancellation.
parent_exec = ExecTool(working_dir=str(tmp_path), session_manager=manager._exec_session_manager)
try:
with request_context(ctx):
@@ -635,7 +631,7 @@ async def test_real_task_process_cleanup_preserves_sibling_parent_and_work_produ
assert "SURVIVED" in poll.output
assert script.exists()
assert await manager.cancel_by_session("owner") == 1
assert manager.bus.inbound_size == 1 # No cancelled sibling notice on parent stop.
assert manager.bus.inbound_size == 1
parent_poll = await manager._exec_session_manager.write(
session_id=parent_id, chars="STILL ALIVE\n", close_stdin=False, terminate=False,
yield_time_ms=1000, max_output_chars=1000, owner_session_key="owner",
@@ -912,7 +908,6 @@ async def test_resistant_dependency_has_bounded_stop_and_no_late_result(tmp_path
assert record.cleanup_task.done()
assert record.exec_manager._closed
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "rejected"))
# Repeated cancel is bounded and must not interrupt the resistant coroutine.
assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "stopping"
assert manager.bus.inbound_size == 0
finally:
-40
View File
@@ -1,5 +1,3 @@
"""Tests for SubagentManager lifecycle — spawn, run, announce, cancel."""
import asyncio
import time
from pathlib import Path
@@ -20,9 +18,6 @@ from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMUsage
from nanobot.utils.llm_runtime import LLMRuntime
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _manager(tmp_path: Path, **kw) -> SubagentManager:
defaults = dict(
@@ -93,11 +88,6 @@ async def test_close_cancels_tasks_before_closing_exec_sessions(tmp_path):
sm._exec_session_manager.close_all.assert_awaited_once()
# ---------------------------------------------------------------------------
# SubagentStatus defaults
# ---------------------------------------------------------------------------
class TestSubagentStatus:
def test_defaults(self):
s = SubagentStatus(
@@ -185,11 +175,6 @@ class TestLegacyCompatibility:
await sm.spawn("task")
# ---------------------------------------------------------------------------
# spawn
# ---------------------------------------------------------------------------
class TestSpawn:
@pytest.mark.asyncio
async def test_returns_string_with_task_id(self, tmp_path):
@@ -344,11 +329,6 @@ class TestSpawn:
await _drain_subagent_tasks(sm)
# ---------------------------------------------------------------------------
# _run_subagent
# ---------------------------------------------------------------------------
class TestRunSubagent:
@pytest.mark.asyncio
async def test_successful_run(self, tmp_path):
@@ -406,11 +386,6 @@ class TestRunSubagent:
assert status.stop_reason == "completed"
# ---------------------------------------------------------------------------
# _announce_result
# ---------------------------------------------------------------------------
class TestAnnounceResult:
@pytest.mark.asyncio
async def test_publishes_inbound_message(self, tmp_path):
@@ -497,11 +472,6 @@ class TestAnnounceResult:
assert published[0].metadata["origin_message_id"] == "msg-123"
# ---------------------------------------------------------------------------
# cancel_by_session
# ---------------------------------------------------------------------------
class TestCancelBySession:
@pytest.mark.asyncio
async def test_cancels_running_tasks(self, tmp_path):
@@ -570,11 +540,6 @@ class TestCancelBySession:
assert count == 0
# ---------------------------------------------------------------------------
# get_running_count / get_running_count_by_session
# ---------------------------------------------------------------------------
class TestRunningCounts:
@pytest.mark.asyncio
async def test_running_count_zero(self, tmp_path):
@@ -606,11 +571,6 @@ class TestRunningCounts:
assert sm.get_running_count_by_session("nonexistent") == 0
# ---------------------------------------------------------------------------
# _SubagentHook
# ---------------------------------------------------------------------------
class TestSubagentHook:
@pytest.mark.asyncio
async def test_after_iteration_updates_status(self):
-7
View File
@@ -1,5 +1,3 @@
"""Tests for /stop task cancellation."""
from __future__ import annotations
import asyncio
@@ -513,7 +511,6 @@ class TestSubagentCancellation:
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
consolidator=MagicMock(spec=Consolidator),
)
# Replace the real exec session manager with a mock
mock_exec_mgr = AsyncMock(spec=ExecSessionManager)
mock_exec_mgr.terminate_by_owner = AsyncMock(return_value=0)
mgr._exec_session_manager = mock_exec_mgr
@@ -727,7 +724,6 @@ class TestSubagentCancellation:
class TestSubagentAnnounceSessionKey:
"""Verify _announce_result uses the effective session key for mid-turn routing."""
def _make_mgr(self):
"""Create a SubagentManager with mocked deps and its bus."""
@@ -758,7 +754,6 @@ class TestSubagentAnnounceSessionKey:
@pytest.mark.asyncio
async def test_announce_uses_raw_key_in_normal_mode(self):
"""Without unified sessions, session_key_override is the raw channel:chat_id."""
mgr, bus = self._make_mgr()
origin = {"channel": "telegram", "chat_id": "222", "session_key": "telegram:222"}
@@ -770,7 +765,6 @@ class TestSubagentAnnounceSessionKey:
@pytest.mark.asyncio
async def test_announce_falls_back_to_origin_when_no_session_key(self):
"""When session_key is None, fallback to f'{channel}:{chat_id}'."""
mgr, bus = self._make_mgr()
origin = {"channel": "discord", "chat_id": "333", "session_key": None}
@@ -783,7 +777,6 @@ class TestSubagentAnnounceSessionKey:
@pytest.mark.asyncio
async def test_spawn_routes_result_to_parent_session(self):
"""Background results return to the parent's canonical session."""
mgr, bus = self._make_mgr()
+6 -39
View File
@@ -1,5 +1,3 @@
"""Tests for tool hint formatting (nanobot.utils.tool_hints)."""
from nanobot.providers.base import ToolCallRequest
from nanobot.utils.tool_hints import format_tool_hints
@@ -14,7 +12,6 @@ def _hint(calls, max_length=40):
class TestToolHintKnownTools:
"""Test registered tool types produce correct formatted output."""
def test_rg_shows_argument_boundaries(self):
assert _hint([_tc("rg", {"args": ["-n", "hello world", "src"]})]) == 'rg -n "hello world" src'
@@ -57,30 +54,26 @@ class TestToolHintKnownTools:
cmd = "cd /very/long/path && cat file && echo done && sleep 1 && ls -la"
result = _hint([_tc("exec", {"command": cmd})])
assert result.startswith("$ ")
assert len(result) <= 50 # reasonable limit
assert len(result) <= 50
def test_exec_abbreviates_paths_in_command(self):
"""Windows paths in exec commands should be folded, not blindly truncated."""
cmd = "cd D:\\Documents\\GitHub\\nanobot\\.worktree\\tomain\\nanobot && git diff origin/main...pr-2706 --name-only 2>&1"
result = _hint([_tc("exec", {"command": cmd})])
assert "\u2026/" in result # path should be folded with …/
assert "worktree" not in result # middle segments should be collapsed
assert "\u2026/" in result
assert "worktree" not in result
def test_exec_abbreviates_linux_paths(self):
"""Unix absolute paths in exec commands should be folded."""
cmd = "cd /home/user/projects/nanobot/.worktree/tomain && make build"
result = _hint([_tc("exec", {"command": cmd})])
assert "\u2026/" in result
assert "projects" not in result
def test_exec_abbreviates_home_paths(self):
"""~/ paths in exec commands should be folded."""
cmd = "cd ~/projects/nanobot/workspace && pytest tests/"
result = _hint([_tc("exec", {"command": cmd})])
assert "\u2026/" in result
def test_exec_abbreviates_quoted_linux_paths_with_spaces(self):
"""Quoted Unix paths with spaces should still be folded."""
cmd = 'cd "/home/user/My Documents/project" && pytest tests/'
result = _hint([_tc("exec", {"command": cmd})])
assert "\u2026/" in result
@@ -88,7 +81,6 @@ class TestToolHintKnownTools:
assert '"' in result
def test_exec_abbreviates_quoted_windows_paths_with_spaces(self):
"""Quoted Windows paths with spaces should still be folded."""
cmd = 'cd "C:/Program Files/Git/project" && git status'
result = _hint([_tc("exec", {"command": cmd})])
assert "\u2026/" in result
@@ -96,11 +88,10 @@ class TestToolHintKnownTools:
assert '"' in result
def test_exec_chained_commands_truncated_not_mid_path(self):
"""Long chained commands should truncate preserving abbreviated paths."""
cmd = "cd D:\\Documents\\GitHub\\project && npm run build && npm test"
result = _hint([_tc("exec", {"command": cmd})])
assert "\u2026/" in result # path folded
assert "npm" in result # chained command still visible
assert "\u2026/" in result
assert "npm" in result
def test_web_search(self):
result = _hint([_tc("web_search", {"query": "Claude 4 vs GPT-4"})])
@@ -112,7 +103,6 @@ class TestToolHintKnownTools:
class TestToolHintMCP:
"""Test MCP tools are abbreviated to server::tool format."""
def test_mcp_standard_format(self):
result = _hint([_tc("mcp_4_5v_mcp__analyze_image", {"imageSource": "https://img.jpg", "prompt": "describe"})])
@@ -126,7 +116,6 @@ class TestToolHintMCP:
class TestToolHintFallback:
"""Test unknown tools fall back to original behavior."""
def test_unknown_tool_with_string_arg(self):
result = _hint([_tc("custom_tool", {"data": "hello world"})])
@@ -148,7 +137,6 @@ class TestToolHintFallback:
class TestToolHintFolding:
"""Test consecutive same-tool calls are folded."""
def test_single_call_no_fold(self):
calls = [_tc("grep", {"pattern": "*.py"})]
@@ -199,7 +187,6 @@ class TestToolHintFolding:
class TestToolHintMultipleCalls:
"""Test multiple different tool calls are comma-separated."""
def test_two_different_tools(self):
calls = [
@@ -213,39 +200,31 @@ class TestToolHintMultipleCalls:
class TestToolHintEdgeCases:
"""Test edge cases and defensive handling (G1, G2)."""
def test_known_tool_empty_list_args(self):
"""C1/G1: Empty list arguments should not crash."""
result = _hint([_tc("read_file", [])])
assert result == "read_file"
def test_known_tool_none_args(self):
"""G2: None arguments should not crash."""
result = _hint([_tc("read_file", None)])
assert result == "read_file"
def test_fallback_empty_list_args(self):
"""C1: Empty list args in fallback should not crash."""
result = _hint([_tc("custom_tool", [])])
assert result == "custom_tool"
def test_fallback_none_args(self):
"""G2: None args in fallback should not crash."""
result = _hint([_tc("custom_tool", None)])
assert result == "custom_tool"
def test_list_dir_registered(self):
"""S2: list_dir should use 'ls' format."""
result = _hint([_tc("list_dir", {"path": "/tmp"})])
assert result == "ls /tmp"
class TestToolHintMixedFolding:
"""G4: Mixed folding groups with interleaved same-tool segments."""
def test_read_read_grep_grep_read(self):
"""All different args — each hint listed separately."""
calls = [
_tc("read_file", {"path": "a.py"}),
_tc("read_file", {"path": "b.py"}),
@@ -260,12 +239,11 @@ class TestToolHintMixedFolding:
class TestToolHintMaxLength:
"""Test max_length parameter controls truncation of tool hints."""
def test_exec_explicit_max_length_limits_hint(self):
cmd = "cd /very/long/path/to/some/project && npm run build && npm test"
result = _hint([_tc("exec", {"command": cmd})], max_length=40)
assert len(result) <= 50 # "$ " prefix + 40 + ellipsis
assert len(result) <= 50
assert "\u2026" in result
def test_exec_larger_max_length_shows_more(self):
@@ -294,21 +272,18 @@ class TestToolHintMaxLength:
assert len(result) >= len(result_40)
def test_path_type_respects_max_length(self):
"""Path-type tools (read_file, write_file, etc.) should honor max_length."""
long_path = "/home/user/.local/share/uv/tools/nanobot/agent/loop.py"
short = _hint([_tc("read_file", {"path": long_path})], max_length=40)
long = _hint([_tc("read_file", {"path": long_path})], max_length=120)
assert len(long) > len(short)
def test_edit_path_respects_max_length(self):
"""edit (is_path=True) should honor max_length, not stay hardcoded at 40."""
long_path = "/home/user/projects/nanobot/src/agent/loop.py"
short = _hint([_tc("edit", {"file_path": long_path})], max_length=40)
long = _hint([_tc("edit", {"file_path": long_path})], max_length=120)
assert len(long) > len(short)
def test_list_dir_path_respects_max_length(self):
"""list_dir (is_path=True) should honor max_length."""
long_path = "/home/user/.local/share/uv/tools/nanobot/"
short = _hint([_tc("list_dir", {"path": long_path})], max_length=40)
long = _hint([_tc("list_dir", {"path": long_path})], max_length=120)
@@ -330,42 +305,34 @@ class TestToolHintMaxLength:
short = _hint([_tc(name, {key: "x" * 400})], max_length=40)
long = _hint([_tc(name, {key: "x" * 400})], max_length=120)
assert len(long) > len(short), name
# Longest template is 'search X "{}"' — 12 chars of overhead.
assert len(short) <= 40 + 12, name
assert "\u2026" in short, name
def test_plain_value_short_value_untouched(self):
"""Values inside the budget must not gain an ellipsis."""
result = _hint([_tc("grep", {"pattern": "TODO|FIXME"})], max_length=40)
assert result == 'grep "TODO|FIXME"'
def test_plain_value_exactly_at_max_length_untouched(self):
"""A value exactly at max_length already fits."""
query = "a" * 40
result = _hint([_tc("web_search", {"query": query})], max_length=40)
assert result == f'search "{query}"'
assert "\u2026" not in result
def test_plain_value_one_over_max_length_truncates(self):
"""One character over the budget truncates instead of overflowing."""
result = _hint([_tc("grep", {"pattern": "a" * 41})], max_length=40)
assert result == 'grep "' + "a" * 39 + "\u2026" + '"'
class TestToolHintMalformedCalls:
"""Malformed tool calls must not crash hint formatting (see HKUDS/nanobot)."""
def test_none_name_is_skipped(self):
"""A tool call with name=None should be skipped, not raise AttributeError."""
result = _hint([_tc(None, None)])
assert result == ""
def test_empty_name_is_skipped(self):
"""A tool call with an empty name should be skipped."""
result = _hint([_tc("", {"path": "foo.txt"})])
assert result == ""
def test_none_name_mixed_with_valid_call(self):
"""A degenerate call must not suppress hints for the valid calls beside it."""
result = _hint([_tc(None, None), _tc("read_file", {"path": "foo.txt"})])
assert result == "read foo.txt"
@@ -12,7 +12,6 @@ from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
def test_loader_discovers_entry_point_tools(tmp_path, monkeypatch):
"""Discover a real distribution descriptor in the tool entry-point group."""
class _FakeTool(Tool):
__name__ = "FakeTool"
@@ -64,7 +63,6 @@ def test_loader_discovers_entry_point_tools(tmp_path, monkeypatch):
def test_loader_skips_abstract_entry_point_tools():
"""Verify abstract tool classes registered via entry_points are skipped."""
mock_ep = MagicMock()
mock_ep.name = "abstract_plugin"
@@ -81,7 +79,6 @@ def test_loader_skips_abstract_entry_point_tools():
def create(cls, ctx):
return MagicMock()
# Intentionally missing abstract properties (name, description, parameters, execute)
mock_ep.load.return_value = _AbstractTool
@@ -94,7 +91,6 @@ def test_loader_skips_abstract_entry_point_tools():
@pytest.mark.asyncio
async def test_loader_entry_point_error_wrapper_preserves_tool_api(tmp_path):
"""Only adapt legacy plugin error strings; keep the wrapped tool API intact."""
mock_ep = MagicMock()
mock_ep.name = "api_plugin"
-1
View File
@@ -36,7 +36,6 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
delivery.remember_session_route(metadata)
assert "_compaction_route" not in metadata
# The same destination still receives the user's own compaction lifecycle.
user_delivery = factory.create(msg, f"{channel}:chat")
user_delivery.remember_session_route(metadata)
for sink in (user_delivery.events, factory.session_events(f"{channel}:chat", metadata, generation="generation")):
+2 -68
View File
@@ -1,16 +1,3 @@
"""Tests for unified_session feature.
Covers:
- Session admission rewrites session_key to "unified:default" when enabled
- Existing session_key_override is respected (not overwritten)
- Feature is off by default (no behavior change for existing users)
- Config schema serialises unified_session as camelCase "unifiedSession"
- onboard-generated config.json contains "unifiedSession" key
- /new command correctly clears the shared session in unified mode
- /new is NOT a priority command; the effective session key applies
- Context window consolidation is unaffected by unified_session
"""
import asyncio
import json
from pathlib import Path
@@ -30,9 +17,6 @@ from nanobot.config.schema import AgentDefaults, Config
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionManager
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_loop(tmp_path: Path, unified_session: bool = False) -> AgentLoop:
"""Create a minimal AgentLoop for dispatch-level tests."""
@@ -63,16 +47,10 @@ def _make_msg(channel: str = "telegram", chat_id: str = "111",
)
# ---------------------------------------------------------------------------
# TestUnifiedSessionDispatch — core behaviour
# ---------------------------------------------------------------------------
class TestUnifiedSessionDispatch:
"""Session admission applies the unified-session routing policy."""
@pytest.mark.asyncio
async def test_unified_session_rewrites_key_to_unified_default(self, tmp_path: Path):
"""When unified_session=True, all messages use 'unified:default' as session key."""
loop = _make_loop(tmp_path, unified_session=True)
captured: list[str] = []
@@ -90,7 +68,6 @@ class TestUnifiedSessionDispatch:
@pytest.mark.asyncio
async def test_unified_session_different_channels_share_same_key(self, tmp_path: Path):
"""Messages from different channels all resolve to the same session key."""
loop = _make_loop(tmp_path, unified_session=True)
captured: list[str] = []
@@ -109,7 +86,6 @@ class TestUnifiedSessionDispatch:
@pytest.mark.asyncio
async def test_unified_session_disabled_preserves_original_key(self, tmp_path: Path):
"""When unified_session=False (default), session key is channel:chat_id as usual."""
loop = _make_loop(tmp_path, unified_session=False)
captured: list[str] = []
@@ -127,7 +103,6 @@ class TestUnifiedSessionDispatch:
@pytest.mark.asyncio
async def test_unified_session_respects_existing_override(self, tmp_path: Path):
"""If session_key_override is already set (e.g. Telegram thread), it is NOT overwritten."""
loop = _make_loop(tmp_path, unified_session=True)
captured: list[str] = []
@@ -144,30 +119,21 @@ class TestUnifiedSessionDispatch:
assert captured == ["telegram:thread:42"]
def test_unified_session_default_is_false(self, tmp_path: Path):
"""unified_session defaults to False — no behavior change for existing users."""
loop = _make_loop(tmp_path)
assert loop._unified_session is False
# ---------------------------------------------------------------------------
# TestUnifiedSessionConfig — schema & serialisation
# ---------------------------------------------------------------------------
class TestUnifiedSessionConfig:
"""Config schema and onboard serialisation for unified_session."""
def test_agent_defaults_unified_session_default_is_false(self):
"""AgentDefaults.unified_session defaults to False."""
defaults = AgentDefaults()
assert defaults.unified_session is False
def test_agent_defaults_unified_session_can_be_enabled(self):
"""AgentDefaults.unified_session can be set to True."""
defaults = AgentDefaults(unified_session=True)
assert defaults.unified_session is True
def test_config_serialises_unified_session_as_camel_case(self):
"""model_dump(by_alias=True) outputs 'unifiedSession' (camelCase) for JSON."""
config = Config()
data = config.model_dump(mode="json", by_alias=True)
agents_defaults = data["agents"]["defaults"]
@@ -175,19 +141,16 @@ class TestUnifiedSessionConfig:
assert agents_defaults["unifiedSession"] is False
def test_config_parses_unified_session_from_camel_case(self):
"""Config can be loaded from JSON with camelCase 'unifiedSession'."""
raw = {"agents": {"defaults": {"unifiedSession": True}}}
config = Config.model_validate(raw)
assert config.agents.defaults.unified_session is True
def test_config_parses_unified_session_from_snake_case(self):
"""Config also accepts snake_case 'unified_session' (populate_by_name=True)."""
raw = {"agents": {"defaults": {"unified_session": True}}}
config = Config.model_validate(raw)
assert config.agents.defaults.unified_session is True
def test_onboard_generated_config_contains_unified_session(self, tmp_path: Path):
"""save_config() writes 'unifiedSession' into config.json (simulates nanobot onboard)."""
from nanobot.config.loader import save_config
config = Config()
@@ -204,31 +167,22 @@ class TestUnifiedSessionConfig:
assert agents_defaults["unifiedSession"] is False
# ---------------------------------------------------------------------------
# TestCmdNewUnifiedSession — /new command behaviour in unified mode
# ---------------------------------------------------------------------------
class TestCmdNewUnifiedSession:
"""/new command routing and session-clear behaviour in unified mode."""
def test_new_is_not_a_priority_command(self):
"""/new uses the effective session key before its command handler runs."""
router = CommandRouter()
register_builtin_commands(router)
assert router.is_priority("/new") is False
def test_new_is_an_exact_command(self):
"""/new must be registered as an exact command."""
router = CommandRouter()
register_builtin_commands(router)
assert "/new" in router._exact
@pytest.mark.asyncio
async def test_cmd_new_clears_unified_session(self, tmp_path: Path):
"""cmd_new called with key='unified:default' clears the shared session."""
sessions = SessionManager(tmp_path)
# Pre-populate the shared session with some messages
shared = sessions.get_or_create("unified:default")
shared.add_message("user", "hello from telegram")
shared.add_message("assistant", "hi there")
@@ -270,7 +224,6 @@ class TestCmdNewUnifiedSession:
result = await cmd_new(ctx)
assert "New session started" in result.content
# Invalidate cache and reload from disk to confirm persistence
sessions.invalidate("unified:default")
reloaded = sessions.get_or_create("unified:default")
assert reloaded.messages == []
@@ -290,7 +243,6 @@ class TestCmdNewUnifiedSession:
@pytest.mark.asyncio
async def test_cmd_new_in_unified_mode_does_not_affect_other_sessions(self, tmp_path: Path):
"""Clearing unified:default must not touch other sessions on disk."""
sessions = SessionManager(tmp_path)
other = sessions.get_or_create("discord:999")
@@ -323,20 +275,12 @@ class TestCmdNewUnifiedSession:
assert len(sessions.get_or_create("discord:999").messages) == 1
# ---------------------------------------------------------------------------
# TestStopCommandWithUnifiedSession — /stop command integration
# ---------------------------------------------------------------------------
class TestStopCommandWithUnifiedSession:
"""Verify /stop command works correctly with unified session enabled."""
@pytest.mark.asyncio
async def test_active_tasks_use_effective_key_in_unified_mode(self, tmp_path: Path):
"""When unified_session=True, tasks are stored under UNIFIED_SESSION_KEY."""
loop = _make_loop(tmp_path, unified_session=True)
# Create a message from telegram channel
msg = _make_msg(channel="telegram", chat_id="123456")
loop._process_message = AsyncMock(return_value=None)
@@ -346,39 +290,33 @@ class TestStopCommandWithUnifiedSession:
@pytest.mark.asyncio
async def test_stop_command_finds_task_in_unified_mode(self, tmp_path: Path):
"""cmd_stop can cancel tasks when unified_session=True."""
from nanobot.command.builtin import cmd_stop
loop = _make_loop(tmp_path, unified_session=True)
# Create a long-running task stored under UNIFIED_SESSION_KEY
async def long_running():
await asyncio.sleep(10) # Will be cancelled
await asyncio.sleep(10)
task = asyncio.create_task(long_running())
loop._active_tasks[UNIFIED_SESSION_KEY] = {task}
# Create a message that would have session_key=UNIFIED_SESSION_KEY after dispatch
msg = InboundMessage(
channel="telegram",
chat_id="123456",
sender_id="user1",
content="/stop",
session_key_override=UNIFIED_SESSION_KEY, # Simulate post-dispatch state
session_key_override=UNIFIED_SESSION_KEY,
)
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
# Execute /stop
result = await cmd_stop(ctx)
# Verify task was cancelled
assert task.cancelled() or task.done()
assert "Stopped 1 task" in result.content
@pytest.mark.asyncio
async def test_stop_command_uses_effective_key_without_session_override(self, tmp_path: Path):
"""Priority /stop must cancel the unified session even before dispatch rewrites the message."""
from nanobot.command.builtin import cmd_stop
loop = _make_loop(tmp_path, unified_session=True)
@@ -403,12 +341,10 @@ class TestStopCommandWithUnifiedSession:
@pytest.mark.asyncio
async def test_stop_command_cross_channel_in_unified_mode(self, tmp_path: Path):
"""In unified mode, /stop from one channel cancels tasks from another channel."""
from nanobot.command.builtin import cmd_stop
loop = _make_loop(tmp_path, unified_session=True)
# Create tasks from different channels, all stored under UNIFIED_SESSION_KEY
async def long_running():
await asyncio.sleep(10)
@@ -416,7 +352,6 @@ class TestStopCommandWithUnifiedSession:
task2 = asyncio.create_task(long_running())
loop._active_tasks[UNIFIED_SESSION_KEY] = {task1, task2}
# /stop from discord should cancel tasks started from telegram
msg = InboundMessage(
channel="discord",
chat_id="789012",
@@ -429,5 +364,4 @@ class TestStopCommandWithUnifiedSession:
result = await cmd_stop(ctx)
# Both tasks should be cancelled
assert "Stopped 2 task" in result.content
-2
View File
@@ -1,5 +1,3 @@
"""Tests for sustained goal tools (``create_goal``, ``update_goal``)."""
from __future__ import annotations
import asyncio
-10
View File
@@ -1,5 +1,3 @@
"""Contract and security regressions for the MyTool runtime boundary."""
from __future__ import annotations
import asyncio
@@ -73,7 +71,6 @@ def wire_request(request):
max_tokens=100, temperature=0.7, reasoning_effort=None,
tool_choice=call.get("tool_choice"),
)
# Keep the protocol's real item shape, but use one name for prefix comparisons.
if "input" in body:
body["messages"] = body.pop("input")
return body
@@ -302,7 +299,6 @@ async def test_workspace_inspection_matches_registered_file_tool(
definitions = json.dumps(loop.tools.get_definitions(), sort_keys=True)
token = bind_workspace_scope(build_workspace_scope(project, mode))
try:
# Legacy display writes must not spoof the effective directory or permission.
await tool.execute(action="set", key="workspace", value=str(outside.parent))
status = tool._runtime_control.snapshot().workspace_sandbox
assert status["workspace_root"] == str(project.resolve())
@@ -320,7 +316,6 @@ async def test_workspace_inspection_matches_registered_file_tool(
assert "project marker" in await loop.tools.execute("read_file", {"path": "marker.txt"})
result = await loop.tools.execute("read_file", {"path": str(outside)})
assert ("outside allowed directory" if restricted else "outside marker") in result
# The directory and permission enter tool results, not the reusable tool schemas.
assert json.dumps(loop.tools.get_definitions(), sort_keys=True) == definitions
status["workspace_root"] = "changed snapshot"
assert tool._runtime_control.snapshot().workspace_sandbox["workspace_root"] == str(project.resolve())
@@ -429,7 +424,6 @@ async def test_workspace_context_uses_request_scope_not_active_tool_scope(
loop = _make_loop(tmp_path / "agent", sandbox=sandbox)
control = _my_tool(loop)._runtime_control
scope = build_workspace_scope(tmp_path / "new-project", mode)
# Pending user inputs are prepared while the earlier turn is still bound.
token = bind_workspace_scope(build_workspace_scope(tmp_path / "old-project", "restricted"))
try:
block = await control.workspace_context(RequestContext("websocket", "chat", workspace_scope=scope))
@@ -486,7 +480,6 @@ async def test_access_changes_refresh_only_new_message_and_preserve_prefix(tmp_p
)
calls = provider.chat_stream_with_retry.await_args_list
first, second, third = [LLMProvider._sanitize_empty_content(call.kwargs["messages"]) for call in calls]
# Access changes belong to the new request, not a rewrite of the cached history.
assert json.dumps(second[:len(first)]) == json.dumps(first)
assert "File access: project and tool-specific allowed paths only." in first[-1]["content"]
assert "File access: no workspace restriction." in second[-1]["content"]
@@ -586,7 +579,6 @@ async def test_workspace_context_compaction_reuses_serialized_prefix(
assert compact_wire[:len(first_wire)] == first_wire
assert compact["tools"] == first["tools"]
before, after = wire_request(first), wire_request(compact)
# JSON object field order is not model input; preserve every value and array order.
assert json.dumps(
after["messages"][:len(before["messages"])], sort_keys=True,
) == json.dumps(before["messages"], sort_keys=True)
@@ -616,7 +608,6 @@ async def test_workspace_context_transient_retry_keeps_exact_wire_request(
)
return LLMResponse(content="done")
# Keep the production retry policy; replace only transport and backoff waiting.
monkeypatch.setattr(provider, "chat_stream_with_context", respond)
monkeypatch.setattr(provider, "_sleep_with_heartbeat", AsyncMock())
loop.provider.chat_stream_with_retry = provider.chat_stream_with_retry
@@ -653,7 +644,6 @@ async def test_subagent_rejects_missing_action_inputs(tmp_path, runtime, params)
async def test_subagent_check_is_session_scoped(tmp_path, single_task, runtime):
loop = _make_loop(tmp_path)
manager = loop.subagents
# Queued tasks must be scoped before their runner starts.
for _ in range(manager.max_concurrent_subagents):
await manager._run_slots.acquire()
await manager.spawn("ALPHA_PRIVATE_TASK", label="ALPHA_LABEL", session_key="owner:a", runtime=runtime)
-115
View File
@@ -1,5 +1,3 @@
"""Tests for MyTool — runtime state inspection and configuration."""
from __future__ import annotations
import time
@@ -17,9 +15,6 @@ from nanobot.agent.tools.web import WebSearchConfig, WebToolsConfig
from nanobot.config.schema import ModelPresetConfig
from nanobot.providers.base import LLMUsage
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_mock_loop(**overrides):
"""Build a lightweight mock AgentLoop with the attributes MyTool reads."""
@@ -47,18 +42,15 @@ def _make_mock_loop(**overrides):
value,
)
# web_config mock — needed for check tests
loop.web_config = WebToolsConfig()
loop.web_config.search.api_key = "sk-secret-key-12345"
# Tools registry mock
loop.tools = MagicMock()
loop.tools.tool_names = ["read_file", "write_file", "exec", "web_search", "self"]
loop.tools.has.side_effect = lambda n: n in loop.tools.tool_names
loop.tools.get.return_value = None
loop.tool_names = loop.tools.tool_names
# SubagentManager mock
loop.subagents = MagicMock()
for k, v in overrides.items():
@@ -73,10 +65,6 @@ def _make_tool(loop=None):
return MyTool(runtime_control=AgentRuntimeControl(loop))
# ---------------------------------------------------------------------------
# check — no key (summary)
# ---------------------------------------------------------------------------
class TestInspectSummary:
@pytest.mark.asyncio
@@ -99,10 +87,6 @@ class TestInspectSummary:
assert "task" in result
# ---------------------------------------------------------------------------
# check — single key (direct)
# ---------------------------------------------------------------------------
class TestInspectSingleKey:
@pytest.mark.asyncio
@@ -131,15 +115,10 @@ class TestInspectSingleKey:
assert "not found" in result
# ---------------------------------------------------------------------------
# check — dot-path navigation
# ---------------------------------------------------------------------------
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")
@@ -153,7 +132,6 @@ class TestInspectPathNavigation:
@pytest.mark.asyncio
async def test_inspect_tools_returns_blocked(self):
"""tools is BLOCKED — check should return access error."""
tool = _make_tool()
result = await tool.execute(action="check", key="tools")
assert "not accessible" in result
@@ -174,11 +152,6 @@ class TestInspectPathNavigation:
assert "api_key" not in result.lower()
# ---------------------------------------------------------------------------
# set — restricted (with validation)
# ---------------------------------------------------------------------------
class TestModifyRestricted:
@pytest.mark.asyncio
@@ -236,10 +209,6 @@ class TestModifyRestricted:
assert "Error" in result
# ---------------------------------------------------------------------------
# set — blocked (minimal set)
# ---------------------------------------------------------------------------
class TestModifyBlocked:
@pytest.mark.asyncio
@@ -268,7 +237,6 @@ class TestModifyBlocked:
@pytest.mark.asyncio
async def test_modify_dotpath_leaf_dunder_blocked(self):
"""Fix 3.1: leaf segment of dot-path must also be validated."""
tool = _make_tool()
result = await tool.execute(
action="set",
@@ -279,7 +247,6 @@ class TestModifyBlocked:
@pytest.mark.asyncio
async def test_modify_dotpath_leaf_denied_attr_blocked(self):
"""Fix 3.1: leaf segment matching _DENIED_ATTRS must be rejected."""
tool = _make_tool()
result = await tool.execute(
action="set",
@@ -289,15 +256,10 @@ class TestModifyBlocked:
assert "not accessible" in result
# ---------------------------------------------------------------------------
# set — free tier (setattr priority)
# ---------------------------------------------------------------------------
class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_set_updates_runtime_setting(self):
"""Set a runtime setting through the runtime-control capability."""
tool = _make_tool()
result = await tool.execute(action="set", key="provider_retry_mode", value="persistent")
assert "Set provider_retry_mode" in result
@@ -305,7 +267,6 @@ class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_modify_new_key_stores_in_scratchpad(self):
"""Modifying an unknown key should store it in the scratchpad."""
tool = _make_tool()
result = await tool.execute(action="set", key="my_custom_var", value="hello")
assert "my_custom_var" in result
@@ -368,7 +329,6 @@ class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_modify_existing_attr_type_mismatch_rejected(self):
"""Setting a string attr to int should be rejected."""
tool = _make_tool()
result = await tool.execute(action="set", key="provider_retry_mode", value=42)
assert "Error" in result
@@ -377,22 +337,16 @@ class TestRuntimeSettingsAndScratchpad:
@pytest.mark.asyncio
async def test_modify_existing_int_attr_wrong_type_rejected(self):
"""Setting an int attr to string should be rejected."""
tool = _make_tool()
result = await tool.execute(action="set", key="max_tool_result_chars", value="big")
assert "Error" in result
assert tool._runtime_control.snapshot().max_tool_result_chars == 16000
# ---------------------------------------------------------------------------
# set — previously BLOCKED/READONLY now open
# ---------------------------------------------------------------------------
class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_tools_blocked(self):
"""tools is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_registry = MagicMock()
result = await tool.execute(action="set", key="tools", value=new_registry)
@@ -400,7 +354,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_subagents_blocked(self):
"""Subagent control is outside the self-inspection capability."""
tool = _make_tool()
new_subagents = MagicMock()
result = await tool.execute(action="set", key="subagents", value=new_subagents)
@@ -408,7 +361,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_runner_blocked(self):
"""runner is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_runner = MagicMock()
result = await tool.execute(action="set", key="runner", value=new_runner)
@@ -416,7 +368,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_sessions_blocked(self):
"""sessions is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_sessions = MagicMock()
result = await tool.execute(action="set", key="sessions", value=new_sessions)
@@ -424,7 +375,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_consolidator_blocked(self):
"""consolidator is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_consolidator = MagicMock()
result = await tool.execute(action="set", key="consolidator", value=new_consolidator)
@@ -432,7 +382,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_dream_blocked(self):
"""dream is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_dream = MagicMock()
result = await tool.execute(action="set", key="dream", value=new_dream)
@@ -440,7 +389,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_auto_compact_blocked(self):
"""auto_compact is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_auto_compact = MagicMock()
result = await tool.execute(action="set", key="auto_compact", value=new_auto_compact)
@@ -448,7 +396,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_context_blocked(self):
"""context is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_context = MagicMock()
result = await tool.execute(action="set", key="context", value=new_context)
@@ -456,7 +403,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_commands_blocked(self):
"""commands is BLOCKED — cannot be replaced."""
tool = _make_tool()
new_commands = MagicMock()
result = await tool.execute(action="set", key="commands", value=new_commands)
@@ -464,7 +410,6 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_workspace_preserves_display_compatibility(self):
"""The compatibility value is isolated from filesystem security boundaries."""
tool = _make_tool()
result = await tool.execute(action="set", key="workspace", value="/new/path")
assert "Set workspace" in result
@@ -486,30 +431,23 @@ class TestProtectedRuntimeState:
@pytest.mark.asyncio
async def test_modify_background_tasks_blocked(self):
"""_background_tasks tracks background tasks — must be blocked."""
tool = _make_tool()
result = await tool.execute(action="set", key="_background_tasks", value=[])
assert "protected" in result
@pytest.mark.asyncio
async def test_modify_wrapped_denied(self):
"""__wrapped__ allows decorator bypass — must be denied."""
tool = _make_tool()
result = await tool.execute(action="set", key="__wrapped__", value="evil")
assert "protected" in result
@pytest.mark.asyncio
async def test_modify_closure_denied(self):
"""__closure__ exposes function internals — must be denied."""
tool = _make_tool()
result = await tool.execute(action="set", key="__closure__", value="evil")
assert "protected" in result
# ---------------------------------------------------------------------------
# validate_json_safe — element counting
# ---------------------------------------------------------------------------
class TestValidateJsonSafe:
def test_single_list_passes(self):
@@ -520,10 +458,6 @@ class TestValidateJsonSafe:
assert MyTool._validate_json_safe(value) is None
# ---------------------------------------------------------------------------
# unknown action
# ---------------------------------------------------------------------------
class TestUnknownAction:
@pytest.mark.asyncio
@@ -533,10 +467,6 @@ class TestUnknownAction:
assert "Unknown action" in result
# ---------------------------------------------------------------------------
# scratchpad limits
# ---------------------------------------------------------------------------
class TestScratchpadLimits:
@pytest.mark.asyncio
@@ -558,10 +488,6 @@ class TestScratchpadLimits:
assert tool._runtime_control.snapshot().scratchpad["key_0"] == "updated"
# ---------------------------------------------------------------------------
# denied attrs (non-dunder)
# ---------------------------------------------------------------------------
class TestDeniedAttrs:
@pytest.mark.asyncio
@@ -572,15 +498,10 @@ class TestDeniedAttrs:
assert "protected" in result, f"{attr} should be blocked"
# ---------------------------------------------------------------------------
# _SubagentHook after_iteration updates status
# ---------------------------------------------------------------------------
class TestSubagentHookStatus:
@pytest.mark.asyncio
async def test_after_iteration_updates_status(self):
"""after_iteration should copy iteration, tool_events, usage to status."""
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.subagent import SubagentStatus, _SubagentHook
@@ -607,7 +528,6 @@ class TestSubagentHookStatus:
@pytest.mark.asyncio
async def test_after_iteration_with_error(self):
"""after_iteration should set status.error when context has an error."""
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.subagent import SubagentStatus, _SubagentHook
@@ -629,10 +549,6 @@ class TestSubagentHookStatus:
assert status.error == "something went wrong"
# ---------------------------------------------------------------------------
# read-only mode (tools.my.allow_set=False)
# ---------------------------------------------------------------------------
class TestReadOnlyMode:
def _make_readonly_tool(self):
@@ -659,15 +575,10 @@ class TestReadOnlyMode:
assert "READ-ONLY MODE" in tool.description
# ---------------------------------------------------------------------------
# scratchpad inspection
# ---------------------------------------------------------------------------
class TestScratchpadInspection:
@pytest.mark.asyncio
async def test_inspect_scratchpad_value_after_modify(self):
"""Design doc scenario: set then check should return the value."""
tool = _make_tool()
await tool.execute(action="set", key="user_prefers_concise", value=True)
result = await tool.execute(action="check", key="user_prefers_concise")
@@ -688,22 +599,17 @@ class TestScratchpadInspection:
assert "step" in result
assert "2" in result
# ---------------------------------------------------------------------------
# sensitive sub-field blocking (Fix #3: API key leak prevention)
# ---------------------------------------------------------------------------
class TestSensitiveSubFieldBlocking:
@pytest.mark.asyncio
async def test_inspect_api_key_blocked(self):
"""web_config.search.api_key must not be accessible."""
tool = _make_tool()
result = await tool.execute(action="check", key="web_config.search.api_key")
assert "not accessible" in result
@pytest.mark.asyncio
async def test_inspect_password_blocked(self):
"""Any field named 'password' must be blocked."""
loop = _make_mock_loop()
loop.some_config = MagicMock()
loop.some_config.password = "hunter2"
@@ -731,10 +637,8 @@ class TestSensitiveSubFieldBlocking:
@pytest.mark.asyncio
async def test_modify_api_key_blocked(self):
"""web_config is READ_ONLY, so any set under it is blocked."""
tool = _make_tool()
result = await tool.execute(action="set", key="web_config.search.api_key", value="evil")
# Blocked either by READ_ONLY (web_config) or sensitive name (api_key)
assert "read-only" in result or "not accessible" in result
@pytest.mark.asyncio
@@ -747,84 +651,69 @@ class TestSensitiveSubFieldBlocking:
@pytest.mark.asyncio
async def test_modify_sensitive_top_level_blocked(self):
"""Top-level key matching sensitive name must be blocked for set."""
tool = _make_tool()
result = await tool.execute(action="set", key="api_key", value="evil")
assert "protected" in result
# ---------------------------------------------------------------------------
# security-sensitive attribute protection (Fix #4)
# ---------------------------------------------------------------------------
class TestSecurityAttributeProtection:
@pytest.mark.asyncio
async def test_modify_restrict_to_workspace_blocked(self):
"""restrict_to_workspace is BLOCKED — cannot be toggled."""
tool = _make_tool()
result = await tool.execute(action="set", key="restrict_to_workspace", value=True)
assert "protected" in result
@pytest.mark.asyncio
async def test_modify_exec_config_blocked(self):
"""exec_config is READ_ONLY — cannot be modified."""
tool = _make_tool()
result = await tool.execute(action="set", key="exec_config", value=MagicMock())
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_web_config_blocked(self):
"""web_config is READ_ONLY — cannot be modified."""
tool = _make_tool()
result = await tool.execute(action="set", key="web_config", value=MagicMock())
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_channels_config_blocked(self):
"""channels_config is BLOCKED — cannot be modified."""
tool = _make_tool()
result = await tool.execute(action="set", key="channels_config", value={})
assert "protected" in result
@pytest.mark.asyncio
async def test_inspect_restrict_to_workspace_blocked(self):
"""restrict_to_workspace is BLOCKED — cannot be inspected."""
tool = _make_tool()
result = await tool.execute(action="check", key="restrict_to_workspace")
assert "not accessible" in result
@pytest.mark.asyncio
async def test_inspect_exec_config_allowed(self):
"""exec_config is READ_ONLY — check should work."""
tool = _make_tool()
result = await tool.execute(action="check", key="exec_config")
assert "Error" not in result
@pytest.mark.asyncio
async def test_inspect_web_config_allowed(self):
"""web_config is READ_ONLY — check should work."""
tool = _make_tool()
result = await tool.execute(action="check", key="web_config")
assert "Error" not in result
@pytest.mark.asyncio
async def test_modify_exec_config_dotpath_blocked(self):
"""exec_config.enable = False should be blocked because exec_config is READ_ONLY."""
tool = _make_tool()
result = await tool.execute(action="set", key="exec_config.enable", value=False)
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_web_config_dotpath_blocked(self):
"""web_config.enable = False should be blocked because web_config is READ_ONLY."""
tool = _make_tool()
result = await tool.execute(action="set", key="web_config.enable", value=False)
assert "read-only" in result
@pytest.mark.asyncio
async def test_modify_model_presets_dotpath_blocked(self):
"""The config-derived model preset catalog is inspectable but not mutable."""
presets = {"fast": ModelPresetConfig(model="fast-model")}
tool = _make_tool(loop=_make_mock_loop(model_presets=presets))
@@ -849,10 +738,6 @@ class TestSecurityAttributeProtection:
assert result == "model_presets.fast.model: 'fast-model'"
# ---------------------------------------------------------------------------
# request context (audit session tracking)
# ---------------------------------------------------------------------------
class TestRequestContext:
@pytest.mark.asyncio
@@ -1,5 +1,3 @@
"""Focused tests for MyTool runtime sync side effects."""
from unittest.mock import MagicMock
import pytest
@@ -1,5 +1,3 @@
"""Session tools read full canonical history independently of WebUI replay."""
from __future__ import annotations
import json
-3
View File
@@ -1,5 +1,3 @@
"""Tests for read-only persisted session tools."""
from __future__ import annotations
import json
@@ -90,7 +88,6 @@ def test_session_tools_do_not_own_runtime_context(tmp_path) -> None:
@pytest.mark.asyncio
async def test_search_sessions_has_no_hidden_content_scan_cutoff(manager):
# Seed offline on this thread; nested saves share the existing store transaction.
with manager._store.transaction():
for index in range(200):
_save_session(
-19
View File
@@ -1,5 +1,3 @@
"""Tests for subagent tool registration and wiring."""
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -25,7 +23,6 @@ def _runtime(provider: MagicMock, model: str = "test-model") -> LLMRuntime:
@pytest.mark.asyncio
async def test_run_inline_returns_result_without_announcement(tmp_path):
"""Inline subagents return directly instead of injecting a follow-up."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -59,7 +56,6 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
@pytest.mark.asyncio
async def test_run_inline_returns_structured_error(tmp_path):
"""Inline subagent failures remain tool errors for the parent runner."""
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.bus.queue import MessageBus
@@ -92,7 +88,6 @@ async def test_run_inline_returns_structured_error(tmp_path):
@pytest.mark.asyncio
async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
"""allowed_env_keys from ExecToolConfig must be forwarded to the subagent's ExecTool."""
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.shell import ExecToolConfig
from nanobot.bus.queue import MessageBus
@@ -137,7 +132,6 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
@pytest.mark.asyncio
async def test_subagent_uses_configured_max_iterations(tmp_path):
"""Subagents should honor the configured tool-iteration limit."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -178,7 +172,6 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
@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
@@ -224,7 +217,6 @@ async def test_subagent_checkpoint_updates_status_and_preserves_omitted_fields(t
@pytest.mark.asyncio
async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
"""A temperature passed to spawn() should reach the AgentRunSpec."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -262,7 +254,6 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
@pytest.mark.asyncio
async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
"""Background tasks should be accepted and start when capacity becomes available."""
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.subagent import SubagentTool
from nanobot.bus.queue import MessageBus
@@ -429,7 +420,6 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
@pytest.mark.asyncio
async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
"""Adjacent blocking consultations should share one concurrent tool batch."""
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.context import RequestContext, request_context
@@ -539,7 +529,6 @@ async def test_cancel_by_session_cancels_inline_subagent(tmp_path):
def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
"""Direct SubagentManager construction should use the agent default concurrency limit."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -556,7 +545,6 @@ def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
def test_subagent_default_max_iterations_matches_agent_defaults(tmp_path):
"""Direct SubagentManager construction should use the agent default limit."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -572,7 +560,6 @@ def test_subagent_default_max_iterations_matches_agent_defaults(tmp_path):
def test_agent_loop_passes_max_iterations_to_subagents(tmp_path):
"""AgentLoop's configured limit should be shared with spawned subagents."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -593,7 +580,6 @@ def test_agent_loop_passes_max_iterations_to_subagents(tmp_path):
@pytest.mark.asyncio
async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
"""Runtime max_iterations changes should be reflected before tool execution."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -636,7 +622,6 @@ async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
@pytest.mark.asyncio
async def test_drain_pending_no_block_when_no_subagents(tmp_path):
"""_drain_pending should not block when no sub-agents are running."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
@@ -679,14 +664,12 @@ async def test_drain_pending_no_block_when_no_subagents(tmp_path):
assert injection_callback is not None
assert terminal_injection_callback is not None
# With no sub-agents and an empty queue, both paths return immediately.
assert await asyncio.wait_for(injection_callback(), timeout=1.0) == []
assert await asyncio.wait_for(terminal_injection_callback(), timeout=1.0) == []
@pytest.mark.asyncio
async def test_terminal_drain_timeout(tmp_path):
"""The terminal drain should return empty after its shared timeout expires."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.session.manager import Session
@@ -739,7 +722,6 @@ async def test_terminal_drain_timeout(tmp_path):
assert terminal_injection_callback is not None
# Patch the timeout path without leaking the queue.get() coroutine.
async def _timeout(awaitable, timeout):
awaitable.close()
raise asyncio.TimeoutError
@@ -753,7 +735,6 @@ async def test_terminal_drain_timeout(tmp_path):
@pytest.mark.asyncio
async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
"""Repeated terminal rendezvous calls share one 300-second deadline."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
-2
View File
@@ -1,5 +1,3 @@
"""CLI app subprocesses must not inherit API keys from the parent environ."""
from __future__ import annotations
import json
@@ -1,5 +1,3 @@
"""Regression coverage for the executable Python import boundaries."""
from __future__ import annotations
import subprocess
-1
View File
@@ -121,7 +121,6 @@ async def test_new_internal_event_needs_explicit_audience(monkeypatch):
monkeypatch.setitem(NOTIFICATION_AUDIENCES, RetryStatus, "interactive")
await delivery.events.emit(event)
assert bus.outbound.get_nowait().event is event
# Routing registration alone does not authorize serialization of private fields.
assert project_notification("chat", event) is None
-2
View File
@@ -1,5 +1,3 @@
"""Shared contract tests for self-contained channel packages."""
from __future__ import annotations
import subprocess
@@ -1,5 +1,3 @@
"""Channel transports decide whether to render compaction lifecycle events."""
from __future__ import annotations
import asyncio
@@ -87,7 +85,6 @@ async def test_dispatch_forwards_all_compaction_phases_before_adapter_filtering(
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]
@@ -113,7 +110,6 @@ def test_global_notice_config_round_trip_and_rebuild(manager):
manager.config = Config.model_validate({"channels": {"showCompactionNotices": True}})
manager.config = Config.model_validate_json(manager.config.model_dump_json(by_alias=True))
assert manager._build_channel(_MockChannel, {}).show_compaction_notices is True
# Rebuilding an adapter after a config change must resolve the new default.
manager.config.channels.show_compaction_notices = False
assert manager._build_channel(_MockChannel, {}).show_compaction_notices is False
assert manager._build_channel(
@@ -179,7 +179,6 @@ async def test_pending_and_concurrent_sends_are_bounded_and_cancellable(monkeypa
assert active == 0
assert not manager._outbound_tasks
assert not manager._outbound_tails
# Cancellation returns admission permits, including tasks not yet sending.
for i in range(4):
await asyncio.wait_for(manager._queue_outbound(
channel, OutboundMessage("websocket", str(i), "b"),
@@ -1,5 +1,3 @@
"""Tests for ChannelManager delta coalescing to reduce streaming latency."""
import asyncio
from contextlib import suppress
from copy import deepcopy
@@ -111,7 +109,6 @@ def _end(
class TestDeltaCoalescing:
"""Tests for stream delta message coalescing."""
async def test_response_source_change_is_a_coalescing_boundary(self, manager, bus):
first, second = _delta("primary"), _delta("backup")
@@ -232,7 +229,6 @@ class TestDeltaCoalescing:
class TestDispatchOutboundWithCoalescing:
"""Tests for the full _dispatch_outbound flow with coalescing."""
@pytest.mark.asyncio
@pytest.mark.parametrize("end_stream", [False, True])
@@ -281,7 +277,6 @@ class TestDispatchOutboundWithCoalescing:
class TestProgressFiltering:
"""Progress filtering should honor per-channel settings."""
def test_progress_visibility_uses_global_defaults(self, manager):
assert manager._should_send_progress("mock", tool_hint=False) is True
@@ -475,7 +470,6 @@ class TestToolEventDelivery:
class TestRetryWaitFiltering:
"""Internal provider retry heartbeats must never reach channels."""
@pytest.mark.asyncio
async def test_retry_wait_message_dropped(self, manager, bus):
@@ -137,7 +137,6 @@ async def test_reasoning_end_routes_to_send_reasoning_end(manager):
@pytest.mark.asyncio
async def test_one_shot_reasoning_expands_to_delta_plus_end(manager):
"""One-shot reasoning expands to a single delta + end."""
channel = manager.channels["mock"]
msg = outbound_message_for_event(
channel="mock",
@@ -206,7 +205,6 @@ async def test_dispatch_silently_drops_reasoning_for_unknown_channel(manager):
@pytest.mark.asyncio
async def test_base_channel_reasoning_primitives_are_noop_safe():
"""Plugins that don't override the streaming primitives must not blow up."""
class _Plain(BaseChannel):
name = "plain"
@@ -224,7 +222,6 @@ async def test_base_channel_reasoning_primitives_are_noop_safe():
channel = _Plain({}, MessageBus())
assert await channel.send_reasoning_delta("c", "x") is None
assert await channel.send_reasoning_end("c") is None
# And the one-shot wrapper translates without raising.
assert await channel.send_reasoning(
OutboundMessage(channel="plain", chat_id="c", content="x", metadata={})
) is None
+10 -106
View File
@@ -1,5 +1,3 @@
"""Tests for channel package discovery, management, and config behavior."""
from __future__ import annotations
import asyncio
@@ -41,9 +39,6 @@ from nanobot.providers.transcription import GroqTranscriptionProvider as _GroqPr
from nanobot.providers.transcription import OpenAITranscriptionProvider as _OpenAIProvider
from nanobot.utils.restart import RestartNotice
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
class _FakePlugin(BaseChannel):
name = "fakeplugin"
@@ -244,10 +239,6 @@ def _stub_optional_feature_cli(
)
# ---------------------------------------------------------------------------
# ChannelsConfig extra="allow"
# ---------------------------------------------------------------------------
def test_channels_config_accepts_unknown_keys():
cfg = ChannelsConfig.model_validate({
"myplugin": {"enabled": True, "token": "abc"},
@@ -542,10 +533,6 @@ def test_channel_manager_preserves_single_instance_plugin_owned_instances(monkey
assert manager.channels["fakeplugin"].config["instances"] == ["plugin-owned-value"]
# ---------------------------------------------------------------------------
# Channel package discovery
# ---------------------------------------------------------------------------
def test_discover_plugins_loads_package_descriptors():
from nanobot.channels.registry import discover_plugins
@@ -842,18 +829,11 @@ def test_discover_plugins_handles_load_error():
assert "broken" not in result
# ---------------------------------------------------------------------------
# Runtime discovery
# ---------------------------------------------------------------------------
def test_discover_all_includes_available_channel_packages():
from nanobot.channels.registry import discover_all, discover_plugins
result = discover_all()
# discover_all() only returns channels that are actually available (dependencies installed)
# discover_plugins() returns all channel package descriptors
# So we check that all actually loaded channels are in the result
for name in result:
assert name in discover_plugins()
@@ -908,13 +888,8 @@ def test_discover_enabled_warns_for_enabled_package_import_errors():
assert "missing" in str(warning.call_args.args[2])
# ---------------------------------------------------------------------------
# Manager _init_channels with dict config
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("proxy", ["", "http://127.0.0.1:7890"])
def test_manager_loads_plugin_from_dict_config(monkeypatch, proxy):
"""Existing two-argument plugins work with or without a shared proxy configured."""
from nanobot.channels.manager import ChannelManager
fake_config = Config.model_validate({
@@ -1047,7 +1022,6 @@ async def test_base_channel_reads_current_transcription_config_each_call(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
):
"""BaseChannel.transcribe_audio resolves config at call time, not manager init time."""
from nanobot.providers import transcription as transcription_mod
config_path = tmp_path / "config.json"
@@ -1154,11 +1128,6 @@ def test_openai_transcription_provider_honors_api_base_argument():
assert custom.api_url == "http://override/v1/audio/transcriptions"
# ---------------------------------------------------------------------------
# Transcription provider HTTP tests
# ---------------------------------------------------------------------------
class _StubResponse:
status_code = 200
@@ -1192,7 +1161,6 @@ def _stub_async_client(captured: dict[str, object]):
)
@pytest.mark.asyncio
async def test_transcription_provider_includes_language(tmp_path, provider_cls, language):
"""Provider must include the 'language' field in multipart body when set."""
audio = tmp_path / "sample.wav"
audio.write_bytes(b"audio")
captured: dict[str, object] = {}
@@ -1212,7 +1180,6 @@ async def test_transcription_provider_includes_language(tmp_path, provider_cls,
)
@pytest.mark.asyncio
async def test_transcription_provider_omits_language_when_none(tmp_path, provider_cls):
"""When language is not set, the 'language' key must be absent from the multipart body."""
audio = tmp_path / "sample.wav"
audio.write_bytes(b"audio")
captured: dict[str, object] = {}
@@ -2119,7 +2086,7 @@ def test_live_runtime_status_overrides_enabled_configuration_for_webui():
decorated = with_channel_runtime_status(payload, runtime_status)
feature = decorated["features"][0]
assert feature["enabled"] is True # desired config remains visible to actions
assert feature["enabled"] is True
assert feature["running"] is False
assert feature["ready"] is False
assert feature["runtime_status"] == "failed"
@@ -2646,8 +2613,6 @@ def test_optional_dependency_metadata_for_enable():
assert "boto3>=1.43.0" not in data["project"]["dependencies"]
assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"]
# The built-in remote WebUI proxy now needs aiohttp even without channels.
# Keep the historical API extra installable for existing deployment commands.
assert "aiohttp>=3.14.3,<4.0.0" in required
assert deps["api"] == ["aiohttp>=3.9.0,<4.0.0"]
for dep_name in (
@@ -2892,12 +2857,7 @@ async def test_manager_skips_disabled_channel_package(monkeypatch):
assert "fakeplugin" not in mgr.channels
# ---------------------------------------------------------------------------
# Channel default_config() and dict-to-Pydantic conversion
# ---------------------------------------------------------------------------
def test_channel_default_config():
"""Channels expose default_config() returning a dict with 'enabled': False."""
from nanobot.channels.dingtalk.runtime import DingTalkChannel
cfg = DingTalkChannel.default_config()
assert isinstance(cfg, dict)
@@ -2906,7 +2866,6 @@ def test_channel_default_config():
def test_channel_init_from_dict():
"""Channels accept a raw dict and convert to Pydantic internally."""
from nanobot.channels.dingtalk.runtime import DingTalkChannel
bus = MessageBus()
ch = DingTalkChannel({"enabled": False, "clientId": "test-id", "allowFrom": ["*"]}, bus)
@@ -2915,61 +2874,47 @@ def test_channel_init_from_dict():
def test_channels_config_send_max_retries_default():
"""ChannelsConfig should have send_max_retries with default value of 3."""
cfg = ChannelsConfig()
assert hasattr(cfg, 'send_max_retries')
assert cfg.send_max_retries == 3
def test_channels_config_send_max_retries_upper_bound():
"""send_max_retries should be bounded to prevent resource exhaustion."""
from pydantic import ValidationError
# Value too high should be rejected
with pytest.raises(ValidationError):
ChannelsConfig(send_max_retries=100)
# Negative should be rejected
with pytest.raises(ValidationError):
ChannelsConfig(send_max_retries=-1)
# Boundary values should be allowed
cfg_min = ChannelsConfig(send_max_retries=0)
assert cfg_min.send_max_retries == 0
cfg_max = ChannelsConfig(send_max_retries=10)
assert cfg_max.send_max_retries == 10
# Value above upper bound should be rejected
with pytest.raises(ValidationError):
ChannelsConfig(send_max_retries=11)
def test_channels_config_transcription_language_pattern():
"""transcription_language must match ISO-639 format (2-3 lowercase letters) or be None."""
from pydantic import ValidationError
# Valid values
assert ChannelsConfig(transcription_language="en").transcription_language == "en"
assert ChannelsConfig(transcription_language="kor").transcription_language == "kor"
assert ChannelsConfig(transcription_language=None).transcription_language is None
# Invalid values
with pytest.raises(ValidationError):
ChannelsConfig(transcription_language="EN") # uppercase
ChannelsConfig(transcription_language="EN")
with pytest.raises(ValidationError):
ChannelsConfig(transcription_language="english") # full word
ChannelsConfig(transcription_language="english")
with pytest.raises(ValidationError):
ChannelsConfig(transcription_language="en-US") # BCP 47 tag
ChannelsConfig(transcription_language="en-US")
# ---------------------------------------------------------------------------
# _send_with_retry
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_send_with_retry_succeeds_first_try():
"""_send_with_retry should succeed on first try and not retry."""
call_count = 0
class _FailingChannel(BaseChannel):
@@ -2985,7 +2930,6 @@ async def test_send_with_retry_succeeds_first_try():
async def send(self, msg: OutboundMessage) -> None:
nonlocal call_count
call_count += 1
# Succeeds on first try
fake_config = SimpleNamespace(
channels=ChannelsConfig(send_max_retries=3),
@@ -3007,7 +2951,6 @@ async def test_send_with_retry_succeeds_first_try():
@pytest.mark.asyncio
async def test_send_with_retry_retries_on_failure():
"""_send_with_retry should retry on failure up to max_retries times."""
call_count = 0
class _FailingChannel(BaseChannel):
@@ -3039,17 +2982,15 @@ async def test_send_with_retry_retries_on_failure():
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
# Patch asyncio.sleep to avoid actual delays
with patch("nanobot.channels.manager.asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
await mgr._send_with_retry(mgr.channels["failing"], msg)
assert call_count == 3 # 3 total attempts (initial + 2 retries)
assert mock_sleep.call_count == 2 # 2 sleeps between retries
assert call_count == 3
assert mock_sleep.call_count == 2
@pytest.mark.asyncio
async def test_send_with_retry_no_retry_when_max_is_zero():
"""_send_with_retry should not retry when send_max_retries is 0."""
call_count = 0
class _FailingChannel(BaseChannel):
@@ -3084,12 +3025,11 @@ async def test_send_with_retry_no_retry_when_max_is_zero():
with patch("nanobot.channels.manager.asyncio.sleep", new_callable=AsyncMock):
await mgr._send_with_retry(mgr.channels["failing"], msg)
assert call_count == 1 # Called once but no retry (max(0, 1) = 1)
assert call_count == 1
@pytest.mark.asyncio
async def test_send_with_retry_calls_send_delta():
"""_send_with_retry should call send_delta for stream delta events."""
calls: list[tuple[str, str, str | None, bool, bool, bool]] = []
class _StreamingChannel(BaseChannel):
@@ -3103,7 +3043,7 @@ async def test_send_with_retry_calls_send_delta():
pass
async def send(self, msg: OutboundMessage) -> None:
pass # Should not be called
pass
async def send_delta(
self,
@@ -3156,7 +3096,6 @@ async def test_send_with_retry_calls_send_delta():
@pytest.mark.asyncio
async def test_send_with_retry_skips_send_when_streamed():
"""_send_with_retry should not call send for streamed response events."""
send_called = False
send_delta_called = False
@@ -3290,7 +3229,6 @@ def test_outbound_duplicate_suppression_cache_is_bounded() -> None:
@pytest.mark.asyncio
async def test_send_with_retry_propagates_cancelled_error():
"""_send_with_retry should re-raise CancelledError for graceful shutdown."""
class _CancellingChannel(BaseChannel):
name = "cancelling"
display_name = "Cancelling"
@@ -3324,7 +3262,6 @@ async def test_send_with_retry_propagates_cancelled_error():
@pytest.mark.asyncio
async def test_send_with_retry_propagates_cancelled_error_during_sleep():
"""_send_with_retry should re-raise CancelledError during sleep."""
call_count = 0
class _FailingChannel(BaseChannel):
@@ -3356,7 +3293,6 @@ async def test_send_with_retry_propagates_cancelled_error_during_sleep():
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
# Mock sleep to raise CancelledError
async def cancel_during_sleep(_):
raise asyncio.CancelledError("cancelled during sleep")
@@ -3364,14 +3300,9 @@ async def test_send_with_retry_propagates_cancelled_error_during_sleep():
with pytest.raises(asyncio.CancelledError):
await mgr._send_with_retry(mgr.channels["failing"], msg)
# Should have attempted once before sleep was cancelled
assert call_count == 1
# ---------------------------------------------------------------------------
# ChannelManager - lifecycle and getters
# ---------------------------------------------------------------------------
class _ChannelWithAllowFrom(BaseChannel):
"""Channel with configurable allow_from."""
name = "withallow"
@@ -3416,7 +3347,6 @@ class _StartableChannel(BaseChannel):
@pytest.mark.asyncio
async def test_validate_allow_from_allows_empty_list():
"""Empty allow_from is valid now — pairing store handles unapproved senders."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3427,7 +3357,6 @@ async def test_validate_allow_from_allows_empty_list():
mgr.channels = {"test": _ChannelWithAllowFrom(fake_config, None, [])}
mgr._dispatch_task = None
# Should not raise — empty list defers to pairing store
mgr._validate_allow_from()
assert list(mgr.channels) == ["test"]
assert mgr.channels["test"].config.allow_from == []
@@ -3435,7 +3364,6 @@ async def test_validate_allow_from_allows_empty_list():
@pytest.mark.asyncio
async def test_validate_allow_from_passes_with_asterisk():
"""_validate_allow_from should not raise when allow_from contains '*'."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3446,7 +3374,6 @@ async def test_validate_allow_from_passes_with_asterisk():
mgr.channels = {"test": _ChannelWithAllowFrom(fake_config, None, ["*"])}
mgr._dispatch_task = None
# Should not raise
mgr._validate_allow_from()
assert list(mgr.channels) == ["test"]
assert mgr.channels["test"].config.allow_from == ["*"]
@@ -3454,7 +3381,6 @@ async def test_validate_allow_from_passes_with_asterisk():
@pytest.mark.asyncio
async def test_validate_allow_from_allows_empty_dict_allow_from():
"""Empty dict-backed allow_from is valid — pairing store handles approval."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3472,7 +3398,6 @@ async def test_validate_allow_from_allows_empty_dict_allow_from():
@pytest.mark.asyncio
async def test_validate_allow_from_allows_missing_allow_from():
"""Omitted allowFrom is valid — channel operates in pairing-only mode."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3496,7 +3421,6 @@ async def test_validate_allow_from_allows_missing_allow_from():
mgr.channels = {"test": _NoAllowFromChannel({"enabled": True}, None)}
mgr._dispatch_task = None
# Should not raise — pairing-only mode
mgr._validate_allow_from()
assert list(mgr.channels) == ["test"]
assert "allow_from" not in mgr.channels["test"].config
@@ -3504,7 +3428,6 @@ async def test_validate_allow_from_allows_missing_allow_from():
@pytest.mark.asyncio
async def test_get_channel_returns_channel_if_exists():
"""get_channel should return the channel if it exists."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3522,7 +3445,6 @@ async def test_get_channel_returns_channel_if_exists():
@pytest.mark.asyncio
async def test_get_status_returns_running_state():
"""get_status should return enabled and running state for each channel."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3538,12 +3460,11 @@ async def test_get_status_returns_running_state():
status = mgr.get_status()
assert status["startable"]["enabled"] is True
assert status["startable"]["running"] is False # Not started yet
assert status["startable"]["running"] is False
@pytest.mark.asyncio
async def test_enabled_channels_returns_channel_names():
"""enabled_channels should return list of enabled channel names."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3567,7 +3488,6 @@ async def test_enabled_channels_returns_channel_names():
@pytest.mark.asyncio
async def test_stop_all_cancels_dispatcher_and_stops_channels():
"""stop_all should cancel the dispatch task and stop all channels."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3582,7 +3502,6 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
mgr._outbound_tasks = {}
mgr._stopping_channels = set()
# Create a real cancelled task
async def dummy_task():
while True:
await asyncio.sleep(1)
@@ -3592,15 +3511,12 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
await mgr.stop_all()
# Task should be cancelled
assert dispatch_task.cancelled()
# Channel should be stopped
assert ch.stopped is True
@pytest.mark.asyncio
async def test_start_channel_logs_error_on_failure():
"""_start_channel should log error when channel start fails."""
class _FailingChannel(BaseChannel):
name = "failing"
display_name = "Failing"
@@ -3627,7 +3543,6 @@ async def test_start_channel_logs_error_on_failure():
ch = _FailingChannel(fake_config, mgr.bus)
# Should not raise, just log error
await mgr._start_channel("failing", ch)
assert mgr.channels == {}
assert mgr._dispatch_task is None
@@ -3635,7 +3550,6 @@ async def test_start_channel_logs_error_on_failure():
@pytest.mark.asyncio
async def test_stop_all_handles_channel_exception():
"""stop_all should handle exceptions when stopping channels gracefully."""
class _StopFailingChannel(BaseChannel):
name = "stopfailing"
display_name = "Stop Failing"
@@ -3662,7 +3576,6 @@ async def test_stop_all_handles_channel_exception():
mgr._stopping_channels = set()
mgr._dispatch_task = None
# Should not raise even if channel.stop() raises
await mgr.stop_all()
assert list(mgr.channels) == ["stopfailing"]
assert mgr._dispatch_task is None
@@ -3670,7 +3583,6 @@ async def test_stop_all_handles_channel_exception():
@pytest.mark.asyncio
async def test_stop_all_handles_channel_stop_cancelled_task():
"""stop_all should treat a channel's already-cancelled internals as stopped."""
class _StopCancelledChannel(BaseChannel):
name = "stopcancelled"
@@ -3709,7 +3621,6 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
@pytest.mark.asyncio
async def test_start_all_no_channels_logs_warning():
"""start_all should log warning when no channels are enabled."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3717,10 +3628,9 @@ async def test_start_all_no_channels_logs_warning():
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
mgr.config = fake_config
mgr.channels = {} # No channels
mgr.channels = {}
mgr._dispatch_task = None
# Should return early without creating dispatch task
await mgr.start_all()
assert mgr._dispatch_task is None
@@ -3728,7 +3638,6 @@ async def test_start_all_no_channels_logs_warning():
@pytest.mark.asyncio
async def test_start_all_creates_dispatch_task():
"""start_all should create the dispatch task when channels exist."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3742,7 +3651,6 @@ async def test_start_all_creates_dispatch_task():
mgr._channel_tasks = {}
mgr._dispatch_task = None
# Cancel immediately after start to avoid running forever
async def cancel_after_start():
await asyncio.sleep(0.01)
if mgr._dispatch_task:
@@ -3761,13 +3669,11 @@ async def test_start_all_creates_dispatch_task():
except asyncio.CancelledError:
pass
# Dispatch task should have been created
assert mgr._dispatch_task is not None
@pytest.mark.asyncio
async def test_notify_restart_done_waits_until_channel_starts():
"""Restart notice should not be sent before the target channel starts."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3802,7 +3708,6 @@ async def test_notify_restart_done_waits_until_channel_starts():
@pytest.mark.asyncio
async def test_websocket_restart_notice_does_not_overwrite_recovery_state():
"""WebSocket attach/recovery events already own reconnect state."""
fake_config = SimpleNamespace(
channels=ChannelsConfig(),
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
@@ -3823,7 +3728,6 @@ async def test_websocket_restart_notice_does_not_overwrite_recovery_state():
@pytest.mark.asyncio
async def test_restart_notice_retries_until_running_channel_accepts_delivery():
"""A running flag must not make an early transport failure final."""
class _EventuallyDeliverableChannel(_StartableChannel):
def __init__(self, config, bus):
-1
View File
@@ -40,7 +40,6 @@ INTERNAL_CHANNEL_FIELDS = {
"signal": {"allowFrom"},
"weixin": {"token"},
"whatsapp": {"databasePath", "lidMappings"},
# nanobot WebUI owns this transport and intentionally has no channel dialog.
"websocket": {
"allowFrom",
"host",
-2
View File
@@ -1,5 +1,3 @@
"""Feishu/Lark QR onboarding: verification URL handling."""
from __future__ import annotations
from unittest.mock import patch
+1 -1
View File
@@ -27,7 +27,7 @@ def _make_channel(tmp_path, **config_kwargs) -> QQChannel:
app_id="test_app", secret="test_secret", media_dir=str(tmp_path), **config_kwargs,
)
channel = QQChannel(config, MessageBus())
channel._client = object() # truthy: pass the initialized check
channel._client = object()
return channel
-5
View File
@@ -1,5 +1,3 @@
"""Regression tests for QQ inbound attachment download SSRF protection."""
from __future__ import annotations
import asyncio
@@ -94,7 +92,6 @@ async def test_inbound_download_blocks_ssrf_target(url: str) -> None:
@pytest.mark.asyncio
async def test_inbound_validation_does_not_run_dns_on_the_event_loop(monkeypatch):
"""The URL guard uses blocking getaddrinfo; keep it off the gateway loop."""
loop_thread = threading.get_ident()
validation_threads = []
@@ -118,7 +115,6 @@ async def test_inbound_download_does_not_follow_redirects(
monkeypatch: pytest.MonkeyPatch,
status: int,
) -> None:
"""A redirect on an inbound attachment download must be rejected, not followed."""
monkeypatch.setattr("nanobot.channels.qq.runtime.validate_url_target", lambda _url: (True, ""))
channel = _make_channel()
fake_http = _FakeDownloadHttp(status=status)
@@ -143,7 +139,6 @@ async def test_inbound_download_saves_successful_attachment(
monkeypatch: pytest.MonkeyPatch,
url: str,
) -> None:
"""A valid 200 response still follows the normal atomic media write path."""
validated_urls: list[str] = []
def validate(target: str) -> tuple[bool, str]:
@@ -1,5 +1,3 @@
"""Regression tests for QQ WebSocket reconnect backoff."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
@@ -1,5 +1,3 @@
"""Exercise scheduled delivery through the real gateway pipeline, without external sends."""
import asyncio
import json
import os
@@ -162,11 +160,8 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
if origin == "websocket":
manager.channels["websocket"] = MagicMock(spec=BaseChannel, send=AsyncMock(), stop=AsyncMock())
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
# Legacy channel/to fields still normalize through the existing binding migration.
schedule = CronSchedule(kind="at", at_ms=4102444800000) if one_shot else CronSchedule(kind="every", every_ms=86400000)
if origin == "websocket":
# A WebUI-created task remains in its source chat even when its instructions
# explicitly request a separate send. Recovery must keep that send's target.
with request_context(RequestContext("websocket", "source", session_key="websocket:source",
metadata={"webui": True, "_wants_stream": True})):
await CronTool(cron).execute(action="add", name="Reminder", every_seconds=86400,
@@ -202,7 +197,6 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
assert DELIVERY_RUN_META not in json.dumps(calls[0]["messages"])
assert "Diagnostic result" not in calls[0]["messages"][0]["content"]
await manager.stop_all()
# A second gateway uses the saved result; no timer, agent, or model is restarted.
manager = make_manager(tmp_path, sessions)
manager.channels["whatsapp"] = channel
channel._connected = True
@@ -216,7 +210,6 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
await again._recover_scheduled()
assert channel._client.send_message.await_count == 1
assert len(calls) == count
# Existing jobs still load after delivery state is added beside them.
old_jobs = CronService(cron.store_path).list_jobs()
assert old_jobs == [] if one_shot else old_jobs[0].payload.message == job.payload.message
finally:
@@ -335,7 +328,6 @@ async def test_recovery_keeps_destination_order_and_does_not_block_other_chats(t
await manager._recover_scheduled()
await drain(manager)
assert [call.args[0].content for call in channel.send.await_args_list] == ["first", "other", "first", "second"]
# A stale queued copy must not downgrade the durable successful result.
manager._outbox.finish(first, "failed", "channel_disabled")
assert all(row["status"] == "sent" for row in rows(manager._outbox))
-3
View File
@@ -1,5 +1,3 @@
"""Reachable manager/adapter ownership contracts for outbound retries."""
import asyncio
import random
from types import SimpleNamespace
@@ -7,7 +5,6 @@ from unittest.mock import AsyncMock, Mock
import pytest
# Telegram is an optional channel dependency, as in its adapter-owned suite.
pytest.importorskip("telegram")
from telegram.error import NetworkError, RetryAfter, TimedOut
@@ -1,5 +1,3 @@
"""Behavioral delegation and executable ownership boundaries for WebSocket."""
from __future__ import annotations
import ast
@@ -144,7 +142,6 @@ def _session_namespace_literal_lines(source: str) -> list[int]:
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
@@ -157,8 +154,6 @@ def _session_namespace_literal_lines(source: str) -> list[int]:
def test_persisted_webui_session_prefix_has_one_production_owner() -> None:
# 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:
@@ -1,5 +1,3 @@
"""Regression tests for WebSocket listener health probing portability."""
from __future__ import annotations
import errno
@@ -86,7 +84,6 @@ def test_unsupported_sockopt_falls_back_to_fd_liveness(unsupported_errno: int) -
def test_listener_health_uses_unsupported_sockopt_fallback() -> None:
"""The fallback must be wired into the health check that controls readiness."""
sock = _StubSocket(fileno=3, error=OSError(errno.ENOPROTOOPT, "Protocol not available"))
server: Any = _StubServer(sock)
@@ -103,7 +100,6 @@ def test_unexpected_oserror_propagates() -> None:
def test_listener_health_rejects_invalid_socket_state() -> None:
"""``EINVAL`` can mean that a live socket isn't actually listening."""
sock = _StubSocket(fileno=3, error=OSError(errno.EINVAL, "Invalid argument"))
server: Any = _StubServer(sock)
@@ -111,7 +107,6 @@ def test_listener_health_rejects_invalid_socket_state() -> None:
def test_unsupported_sockopt_still_rejects_dead_fd() -> None:
"""The portability fallback must not mask an already-closed listener."""
sock = _StubSocket(fileno=-1, error=OSError(errno.ENOPROTOOPT, "Protocol not available"))
assert WebSocketChannel._socket_is_accepting(sock) is False
-9
View File
@@ -7,7 +7,6 @@ from nanobot.config.schema import AgentDefaults, Config
def test_bot_name_and_icon_defaults_preserve_current_branding() -> None:
"""Default values keep the existing 'nanobot' name and cat icon."""
defaults = AgentDefaults()
assert defaults.bot_name == "nanobot"
@@ -15,7 +14,6 @@ def test_bot_name_and_icon_defaults_preserve_current_branding() -> None:
def test_bot_name_and_icon_can_be_overridden_via_config() -> None:
"""camelCase keys (as used in config.json) bind to the new fields."""
config = Config.model_validate(
{"agents": {"defaults": {"botName": "mybot", "botIcon": "🤖"}}}
)
@@ -25,7 +23,6 @@ def test_bot_name_and_icon_can_be_overridden_via_config() -> None:
def test_bot_icon_accepts_empty_string_to_omit() -> None:
"""Empty bot_icon is valid and lets users opt out of the leading icon."""
config = Config.model_validate(
{"agents": {"defaults": {"botIcon": ""}}}
)
@@ -34,7 +31,6 @@ def test_bot_icon_accepts_empty_string_to_omit() -> None:
def test_stream_renderer_propagates_bot_name_to_spinner_text(capsys) -> None:
"""ThinkingSpinner uses the configured bot_name in its status text."""
spinner = ThinkingSpinner(bot_name="mybot")
# rich.Status keeps the renderable on its internal _renderable attribute;
@@ -44,20 +40,15 @@ def test_stream_renderer_propagates_bot_name_to_spinner_text(capsys) -> None:
def test_stream_renderer_header_combines_icon_and_name() -> None:
"""When bot_icon is non-empty, the header is '<icon> <name>'."""
renderer = StreamRenderer(show_spinner=False, bot_name="mybot", bot_icon="🤖")
# The header is built inline in on_delta; verify the stored fields
# so we don't depend on Live console output.
assert renderer._bot_name == "mybot"
assert renderer._bot_icon == "🤖"
def test_stream_renderer_empty_icon_omits_leading_space() -> None:
"""An empty bot_icon yields a header that is just the bot name, no leading space."""
renderer = StreamRenderer(show_spinner=False, bot_name="mybot", bot_icon="")
# Replicate the header construction used in on_delta to assert the contract.
header = (
f"{renderer._bot_icon} {renderer._bot_name}"
if renderer._bot_icon
-2
View File
@@ -1,5 +1,3 @@
"""Credential-bearing browser URLs must not enter a macOS command line."""
import ctypes
import subprocess
from unittest.mock import MagicMock
-2
View File
@@ -1,5 +1,3 @@
"""Message tools preserve target identity through gateway delivery recording."""
from functools import partial
import pytest
+1 -29
View File
@@ -30,7 +30,6 @@ def mock_prompt_session():
@pytest.mark.asyncio
async def test_read_interactive_input_async_returns_input(mock_prompt_session):
"""Test that _read_interactive_input_async returns the user input from prompt_session."""
mock_prompt_session.prompt_async.return_value = "hello world"
result = await terminal._read_interactive_input_async()
@@ -38,12 +37,11 @@ async def test_read_interactive_input_async_returns_input(mock_prompt_session):
assert result == "hello world"
mock_prompt_session.prompt_async.assert_called_once()
args, _ = mock_prompt_session.prompt_async.call_args
assert isinstance(args[0], HTML) # Verify HTML prompt is used
assert isinstance(args[0], HTML)
@pytest.mark.asyncio
async def test_read_interactive_input_async_handles_eof(mock_prompt_session):
"""Test that EOFError converts to KeyboardInterrupt."""
mock_prompt_session.prompt_async.side_effect = EOFError()
with pytest.raises(KeyboardInterrupt):
@@ -51,8 +49,6 @@ async def test_read_interactive_input_async_handles_eof(mock_prompt_session):
def test_init_prompt_session_creates_session():
"""Test that _init_prompt_session initializes the global session."""
# Ensure global is None before test
terminal._prompt_session = None
with patch("nanobot.cli.terminal.PromptSession") as mock_session_cls, \
@@ -66,15 +62,12 @@ def test_init_prompt_session_creates_session():
assert terminal._prompt_session is not None
mock_session_cls.assert_called_once()
_, kwargs = mock_session_cls.call_args
# Buffer is multiline-capable so Alt+Enter can insert newlines;
# Enter-to-submit is restored via custom key bindings.
assert kwargs["multiline"] is True
assert kwargs["enable_open_in_editor"] is False
assert kwargs.get("key_bindings") is not None
def test_cli_key_bindings_enter_submits_and_alt_enter_newlines():
"""Enter submits the buffer; Alt+Enter inserts a newline."""
from prompt_toolkit.keys import Keys
kb = terminal._build_cli_key_bindings()
@@ -84,14 +77,12 @@ def test_cli_key_bindings_enter_submits_and_alt_enter_newlines():
bound = {_keys(b): b for b in kb.bindings}
# Enter -> submit
enter = bound[(Keys.Enter.value,)]
buf = MagicMock()
enter.call(MagicMock(current_buffer=buf))
buf.validate_and_handle.assert_called_once()
buf.insert_text.assert_not_called()
# Alt+Enter (escape, enter) -> newline
alt_enter = bound[(Keys.Escape.value, Keys.Enter.value)]
buf = MagicMock()
alt_enter.call(MagicMock(current_buffer=buf))
@@ -124,7 +115,6 @@ async def test_raw_lf_enter_still_submits_like_wsl_terminals():
@pytest.mark.asyncio
async def test_alt_enter_inserts_newline_on_lf_terminals():
"""LF-as-Enter terminals send Alt+Enter as ESC + LF, which needs its own binding."""
from prompt_toolkit.application import create_app_session
from prompt_toolkit.input import create_pipe_input
from prompt_toolkit.output import DummyOutput
@@ -143,7 +133,6 @@ async def test_alt_enter_inserts_newline_on_lf_terminals():
@pytest.mark.asyncio
async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
"""CSI-u Shift+Enter inserts a newline instead of raw escape bytes."""
from prompt_toolkit.application import create_app_session
from prompt_toolkit.input import create_pipe_input
from prompt_toolkit.output import DummyOutput
@@ -157,12 +146,10 @@ async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
session.prompt_async("> ", set_exception_handler=False), timeout=10,
)
# A newline is inserted and no raw escape bytes leak into the result.
assert result == "foo\nbar"
def test_thinking_spinner_pause_stops_and_restarts():
"""Pause should stop the active spinner and restart it afterward."""
spinner = MagicMock()
mock_console = MagicMock()
mock_console.status.return_value = spinner
@@ -181,7 +168,6 @@ def test_thinking_spinner_pause_stops_and_restarts():
def test_print_cli_progress_line_pauses_spinner_before_printing():
"""CLI progress output should pause spinner to avoid garbled lines."""
order: list[str] = []
spinner = MagicMock()
spinner.start.side_effect = lambda: order.append("start")
@@ -198,7 +184,6 @@ def test_print_cli_progress_line_pauses_spinner_before_printing():
def test_thinking_spinner_clears_status_line_when_paused():
"""Stopping the spinner should erase its transient line before output."""
stream = StringIO()
stream.isatty = lambda: True # type: ignore[method-assign]
mock_console = MagicMock()
@@ -215,7 +200,6 @@ def test_thinking_spinner_clears_status_line_when_paused():
def test_stream_renderer_stops_spinner_even_after_header_printed():
"""A later answer delta must stop the spinner even when header already exists."""
stream = StringIO()
stream.isatty = lambda: True # type: ignore[method-assign]
mock_console = MagicMock()
@@ -233,7 +217,6 @@ def test_stream_renderer_stops_spinner_even_after_header_printed():
def test_print_cli_progress_line_opens_renderer_header_before_trace():
"""Trace lines should appear under the assistant header, not under You."""
order: list[str] = []
renderer = MagicMock()
renderer.console.print.side_effect = lambda *_args, **_kwargs: order.append("print")
@@ -246,7 +229,6 @@ def test_print_cli_progress_line_opens_renderer_header_before_trace():
def test_print_cli_progress_line_stops_live_before_trace():
"""A trace line should not leak the current transient Live frame."""
mock_live = MagicMock()
renderer = stream_mod.StreamRenderer(show_spinner=False)
renderer._live = mock_live
@@ -259,7 +241,6 @@ def test_print_cli_progress_line_stops_live_before_trace():
@pytest.mark.asyncio
async def test_print_interactive_progress_line_pauses_spinner_before_printing():
"""Interactive progress output should also pause spinner cleanly."""
order: list[str] = []
spinner = MagicMock()
spinner.start.side_effect = lambda: order.append("start")
@@ -309,28 +290,22 @@ def test_response_renderable_without_metadata_keeps_markdown_path():
def test_stream_renderer_stop_for_input_stops_spinner():
"""stop_for_input should stop the active spinner to avoid prompt_toolkit conflicts."""
spinner = MagicMock()
mock_console = MagicMock()
mock_console.status.return_value = spinner
# Create renderer with mocked console
with patch.object(stream_mod, "_make_console", return_value=mock_console):
renderer = stream_mod.StreamRenderer(show_spinner=True)
# Verify spinner started
spinner.start.assert_called_once()
# Stop for input
renderer.stop_for_input()
# Verify spinner stopped
spinner.stop.assert_called_once()
@pytest.mark.asyncio
async def test_on_end_writes_final_content_to_stdout_after_stopping_live():
"""on_end should stop Live (transient erases it) then print final content to stdout."""
mock_live = MagicMock()
mock_console = MagicMock()
mock_console.capture.return_value.__enter__ = MagicMock(
@@ -356,7 +331,6 @@ async def test_on_end_writes_final_content_to_stdout_after_stopping_live():
@pytest.mark.asyncio
async def test_on_end_resuming_clears_buffer_and_restarts_spinner():
"""on_end(resuming=True) should reset state for the next iteration."""
spinner = MagicMock()
mock_console = MagicMock()
mock_console.status.return_value = spinner
@@ -372,12 +346,10 @@ async def test_on_end_resuming_clears_buffer_and_restarts_spinner():
await renderer.on_end(resuming=True)
assert renderer._buf == ""
# Spinner should have been restarted (start called twice: __init__ + resuming)
assert spinner.start.call_count == 2
def test_make_console_force_terminal_when_stdout_is_tty():
"""Console should set force_terminal=True when stdout is a TTY (rich output)."""
import sys
with patch.object(sys.stdout, "isatty", return_value=True):
console = stream_mod._make_console()
+1 -11
View File
@@ -376,7 +376,6 @@ def mock_paths():
def test_onboard_fresh_install(mock_paths):
"""No existing config — should create from scratch."""
config_file, workspace_dir, mock_ws = mock_paths
result = runner.invoke(app, ["onboard"])
@@ -393,7 +392,6 @@ def test_onboard_fresh_install(mock_paths):
def test_onboard_recommends_webui(mock_paths):
"""Default onboarding should recommend the guided WebUI launcher."""
result = runner.invoke(app, ["onboard"])
assert result.exit_code == 0
@@ -401,7 +399,6 @@ def test_onboard_recommends_webui(mock_paths):
def test_onboard_existing_config_refresh(mock_paths):
"""Config exists, user declines overwrite — should refresh (load-merge-save)."""
config_file, workspace_dir, _ = mock_paths
config_file.write_text('{"existing": true}')
@@ -415,7 +412,6 @@ def test_onboard_existing_config_refresh(mock_paths):
def test_onboard_existing_config_refresh_non_interactive(mock_paths):
"""Config exists, user specifies --refresh — should refresh non-interactively (no prompt)."""
config_file, workspace_dir, _ = mock_paths
config_file.write_text('{"existing": true}')
@@ -429,7 +425,6 @@ def test_onboard_existing_config_refresh_non_interactive(mock_paths):
def test_onboard_existing_config_overwrite(mock_paths):
"""Config exists, user confirms overwrite — should reset to defaults."""
config_file, workspace_dir, _ = mock_paths
config_file.write_text('{"existing": true}')
@@ -442,7 +437,6 @@ def test_onboard_existing_config_overwrite(mock_paths):
def test_onboard_existing_workspace_safe_create(mock_paths):
"""Workspace exists — should not recreate, but still add missing templates."""
config_file, workspace_dir, _ = mock_paths
workspace_dir.mkdir(parents=True)
config_file.write_text("{}")
@@ -1286,7 +1280,6 @@ def test_config_bare_nemotron_still_auto_routes_to_configured_ollama():
def test_config_cloud_nemotron_is_not_hijacked_by_configured_ollama():
"""An explicit cloud namespace takes precedence over local keywords."""
config = Config.model_validate(
{
"agents": {
@@ -1921,7 +1914,7 @@ def test_agent_workspace_override_wins_over_config_workspace(mock_agent_runtime,
[
("", False),
("# Title\n\n## Active Tasks\n", False),
("<!--\nmulti-line\ncomment\n-->\n", False), # block comment, not tasks
("<!--\nmulti-line\ncomment\n-->\n", False),
("<!-- single line -->\n", False),
("## Active Tasks\n\n- water the plants\n", True),
("## Active Tasks\n\n### Garden\n\n- water the plants\n", True),
@@ -2129,7 +2122,6 @@ def _patch_cli_command_runtime(
) -> None:
from importlib import import_module
# Load adapter contracts before replacing runtime factories for this invocation.
import_module("nanobot.session.webui_turns")
import_module("nanobot.channels.validation")
import_module("nanobot.channels.websocket.runtime")
@@ -3835,7 +3827,6 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
def test_migrate_cron_store_moves_legacy_file(tmp_path: Path) -> None:
"""Legacy global jobs.json is moved into the workspace on first run."""
from nanobot.cli.runtime_config import _migrate_cron_store
legacy_dir = tmp_path / "global" / "cron"
@@ -3856,7 +3847,6 @@ def test_migrate_cron_store_moves_legacy_file(tmp_path: Path) -> None:
def test_migrate_cron_store_skips_when_workspace_file_exists(tmp_path: Path) -> None:
"""Migration does not overwrite an existing workspace cron store."""
from nanobot.cli.runtime_config import _migrate_cron_store
legacy_dir = tmp_path / "global" / "cron"
+1 -2
View File
@@ -216,7 +216,7 @@ def test_absent_desktop_selects_current_python(monkeypatch, capsys) -> None:
("\x1b[B\r", "python"),
("\x1b[B\x1b[A\r", "desktop"),
("\x1b[A\r", "python"),
("2\r", "desktop"), # Numeric keys no longer move the highlight.
("2\r", "desktop"),
("\x1b[B1\r", "python"),
])
def test_target_picker_accepts_real_navigation_keys(keys, expected):
@@ -253,7 +253,6 @@ def test_target_picker_cancellation_exits_without_attachment(monkeypatch, capsys
with create_pipe_input() as pipe_input:
with create_app_session(input=pipe_input, output=DummyOutput()):
if cancel == "interrupt":
# Cancel even after moving the highlight to the Python option.
pipe_input.send_text("\x1b[B\x03")
else:
pipe_input.close()
Loaded 100 of 922 files, more files were not shown because too many files have changed in this diff. Show more