Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(loop): restore /new immediate return with safe background consolidation
chengyongru9820c87537e2
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex 2c0d29ab3..9f69e5bd0 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -380,24 +380,29 @@ class AgentLoop:# Slash commandscmd = msg.content.strip().lower()if cmd == "/new":- try:- if not await self.memory_consolidator.archive_unconsolidated(session):- return OutboundMessage(- channel=msg.channel,- chat_id=msg.chat_id,- content="Memory archival failed, session not cleared. Please try again.",- )- except Exception:- logger.exception("/new archival failed for {}", session.key)- return OutboundMessage(- channel=msg.channel,- chat_id=msg.chat_id,- content="Memory archival failed, session not cleared. Please try again.",- )+ # Capture messages before clearing for background archival+ messages_to_archive = session.messages[session.last_consolidated:]+ # Immediately clear session and returnsession.clear()self.sessions.save(session)self.sessions.invalidate(session.key)++ # Schedule background archival (serialized with normal consolidation via lock)+ if messages_to_archive:++ async def _archive_in_background():+ lock = self.memory_consolidator.get_lock(session.key)+ async with lock:+ try:+ success = await self.memory_consolidator.consolidate_messages(messages_to_archive)+ if not success:+ logger.warning("/new background archival failed for {}", session.key)+ except Exception:+ logger.exception("/new background archival error for {}", session.key)++ asyncio.create_task(_archive_in_background())+return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id,content="New session started.")if cmd == "/help":diff --git a/tests/test_consolidate_offset.py b/tests/test_consolidate_offset.pyindex 7d12338aa..aafaeaf8f 100644--- a/tests/test_consolidate_offset.py+++ b/tests/test_consolidate_offset.py@@ -505,7 +505,8 @@ class TestNewCommandArchival:return loop@pytest.mark.asyncio- async def test_new_does_not_clear_session_when_archive_fails(self, tmp_path: Path) -> None:+ async def test_new_clears_session_immediately_even_if_archive_fails(self, tmp_path: Path) -> None:+ """/new clears session immediately, archive failure only logs warning."""from nanobot.bus.events import InboundMessageloop = self._make_loop(tmp_path)@@ -514,7 +515,6 @@ class TestNewCommandArchival:session.add_message("user", f"msg{i}")session.add_message("assistant", f"resp{i}")loop.sessions.save(session)- before_count = len(session.messages)async def _failing_consolidate(_messages) -> bool:return False@@ -524,9 +524,13 @@ class TestNewCommandArchival:new_msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/new")response = await loop._process_message(new_msg)+ # /new returns immediately with success messageassert response is not None- assert "failed" in response.content.lower()- assert len(loop.sessions.get_or_create("cli:test").messages) == before_count+ assert "new session started" in response.content.lower()++ # Session is cleared immediately, even though archive will fail in background+ session_after = loop.sessions.get_or_create("cli:test")+ assert len(session_after.messages) == 0@pytest.mark.asyncioasync def test_new_archives_only_unconsolidated_messages(self, tmp_path: Path) -> None:@@ -541,10 +545,12 @@ class TestNewCommandArchival:loop.sessions.save(session)archived_count = -1+ archive_done = asyncio.Event()async def _fake_consolidate(messages) -> bool:nonlocal archived_countarchived_count = len(messages)+ archive_done.set()return Trueloop.memory_consolidator.consolidate_messages = _fake_consolidate # type: ignore[method-assign]@@ -554,6 +560,9 @@ class TestNewCommandArchival:assert response is not Noneassert "new session started" in response.content.lower()++ # Wait for background archival to complete+ await asyncio.wait_for(archive_done.wait(), timeout=1.0)assert archived_count == 3@pytest.mark.asyncio