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(channels): make automatic compaction notices follow send_progress
L4XB92f151ae6741
diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.pyindex 531e8bd01..851462e54 100644--- a/nanobot/agent/memory.py+++ b/nanobot/agent/memory.py@@ -1165,6 +1165,7 @@ class Consolidator:runtime: LLMRuntime,max_suffix: int = 0,events: EventSink = NO_EVENTS,+ manual: bool = False,) -> str | None:"""Replace archived history with a summary checkpoint.@@ -1187,7 +1188,7 @@ class Consolidator:compaction_id = uuid4().hexawait events.emit(- ContextCompactionEvent(compaction_id=compaction_id, phase="started"),+ ContextCompactionEvent(compaction_id=compaction_id, phase="started", manual=manual),)last_active = session.updated_atarchive_end = archive_start + len(messages_to_archive)@@ -1207,19 +1208,21 @@ class Consolidator:await events.emit(ContextCompactionEvent(compaction_id=compaction_id,+ manual=manual,phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",),)raiseif not summary:await events.emit(- ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),+ ContextCompactionEvent(compaction_id=compaction_id, phase="failed", manual=manual),)return Noneawait events.emit(ContextCompactionEvent(compaction_id=compaction_id,+ manual=manual,phase="succeeded",),)diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.pyindex 1da6aad9a..281b091f8 100644--- a/nanobot/channels/manager.py+++ b/nanobot/channels/manager.py@@ -15,6 +15,7 @@ from loguru import loggerfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import (+ ContextCompactionEvent,ProgressEvent,RetryWaitEvent,RuntimeModelUpdatedEvent,@@ -810,6 +811,18 @@ class ChannelManager:):continue+ # Automatic compaction notices are maintenance chatter, so they+ # follow the channel's progress setting like other progress+ # text. A user-requested ``/compact`` and a failed compaction+ # are still reported.+ if (+ isinstance(event, ContextCompactionEvent)+ and not event.manual+ and event.phase != "failed"+ and not self._should_send_progress(msg.channel)+ ):+ continue+if isinstance(event, RetryWaitEvent):continuediff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.pyindex 27021b9b5..5d542d44c 100644--- a/nanobot/command/builtin.py+++ b/nanobot/command/builtin.py@@ -357,6 +357,7 @@ async def cmd_compact(ctx: CommandContext) -> None:ctx.key,runtime=runtime,events=delivery.events,+ manual=True,)except Exception:logger.exception("Manual context compaction failed for {}", ctx.key)diff --git a/nanobot/events.py b/nanobot/events.pyindex e4308f768..729544feb 100644--- a/nanobot/events.py+++ b/nanobot/events.py@@ -17,6 +17,9 @@ class AgentEvent:class ContextCompactionEvent(AgentEvent):compaction_id: strphase: Literal["started", "succeeded", "failed", "cancelled"]+ # True when the user asked for the compaction (``/compact``). Automatic+ # compaction is routine maintenance and its notices follow ``send_progress``.+ manual: bool = False@dataclass(frozen=True)diff --git a/tests/channels/test_channel_manager_compaction_notices.py b/tests/channels/test_channel_manager_compaction_notices.pynew file mode 100644index 000000000..50697585e--- /dev/null+++ b/tests/channels/test_channel_manager_compaction_notices.py@@ -0,0 +1,110 @@+"""Automatic context-compaction notices follow the channel's ``send_progress``.++Idle auto-compaction emits ``ContextCompactionEvent`` start/finish notices.+They are maintenance chatter, so a channel that has progress disabled must+not receive them; a user-requested ``/compact`` and a failed compaction are+still delivered (#5719).+"""++from __future__ import annotations++import asyncio+from unittest.mock import AsyncMock++import pytest++from nanobot.bus.outbound_events import (+ ContextCompactionEvent,+ outbound_message_for_event,+)+from nanobot.bus.queue import MessageBus+from nanobot.channels.base import BaseChannel+from nanobot.channels.manager import ChannelManager+from nanobot.config.schema import Config+++class _MockChannel(BaseChannel):+ name = "mock"+ display_name = "Mock"++ def __init__(self, config, bus):+ super().__init__(config, bus)+ self._send_mock = AsyncMock()++ async def start(self): # pragma: no cover - not exercised+ pass++ async def stop(self): # pragma: no cover - not exercised+ pass++ async def send(self, msg):+ return await self._send_mock(msg)+++def manager() -> ChannelManager:+ config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})+ mgr = ChannelManager(config, MessageBus())+ mgr.channels["mock"] = _MockChannel({}, mgr.bus)+ return mgr+++async def _dispatch_until(manager: ChannelManager, expected: int) -> None:+ task = asyncio.create_task(manager._dispatch_outbound())+ try:+ for _ in range(40):+ if manager.channels["mock"]._send_mock.await_count >= expected:+ break+ await asyncio.sleep(0.05)+ finally:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+++def _compaction(phase: str, *, manual: bool = False):+ return outbound_message_for_event(+ channel="mock",+ chat_id="c1",+ event=ContextCompactionEvent(compaction_id="cmp-1", phase=phase, manual=manual),+ )+++async def test_auto_compaction_notices_are_dropped_when_progress_is_off(manager):+ channel = manager.channels["mock"]+ channel.send_progress = False+ await manager.bus.publish_outbound(_compaction("started"))+ await manager.bus.publish_outbound(_compaction("succeeded"))++ await _dispatch_until(manager, expected=1)++ channel._send_mock.assert_not_awaited()+++async def test_auto_compaction_notices_are_delivered_when_progress_is_on(manager):+ channel = manager.channels["mock"]+ channel.send_progress = True+ await manager.bus.publish_outbound(_compaction("started"))+ await manager.bus.publish_outbound(_compaction("succeeded"))++ await _dispatch_until(manager, expected=2)++ contents = [call.args[0].content for call in channel._send_mock.await_args_list]+ assert contents == ["Compressing context…", "Context compacted."]+++async def test_manual_and_failed_compaction_notices_bypass_the_progress_setting(manager):+ channel = manager.channels["mock"]+ channel.send_progress = False+ await manager.bus.publish_outbound(_compaction("started", manual=True))+ await manager.bus.publish_outbound(_compaction("failed"))++ await _dispatch_until(manager, expected=2)++ contents = [call.args[0].content for call in channel._send_mock.await_args_list]+ assert contents == ["Compressing context…", "Unable to compact context."]diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.pyindex 2c36a8ffe..1c38188c2 100644--- a/tests/command/test_compact_command.py+++ b/tests/command/test_compact_command.py@@ -71,6 +71,9 @@ async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command)assert started.phase == "started"assert completed.phase == "succeeded"assert started.compaction_id == completed.compaction_id+ # A user-requested compaction is reported even on channels with progress off.+ assert started.manual is True+ assert completed.manual is Trueloop.sessions.invalidate("cli:test")reloaded = loop.sessions.get_or_create("cli:test")