diff --git a/nanobot/agent/autocompact.py b/nanobot/agent/autocompact.py index dc79d9512..a02b579ef 100644 --- a/nanobot/agent/autocompact.py +++ b/nanobot/agent/autocompact.py @@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutine from loguru import logger +from nanobot.bus.outbound_events import ContextCompactionCallback from nanobot.session.manager import MIN_COMPACTED_REPLAY_MESSAGES, Session, SessionManager from nanobot.session.summary import SessionSummary, session_summary_from_metadata @@ -15,18 +16,22 @@ if TYPE_CHECKING: from nanobot.agent.memory import Consolidator from nanobot.utils.llm_runtime import LLMRuntime +IdleCompactionCallback = Callable[[str], ContextCompactionCallback | None] + class AutoCompact: _RECENT_SUFFIX_MESSAGES = MIN_COMPACTED_REPLAY_MESSAGES _INTERNAL_SESSION_PREFIXES = ("dream:",) def __init__(self, sessions: SessionManager, consolidator: Consolidator, - session_ttl_minutes: int = 0): + session_ttl_minutes: int = 0, + bind_compaction: IdleCompactionCallback | None = None): self.sessions = sessions self.consolidator = consolidator self._ttl = session_ttl_minutes self._archiving: set[str] = set() self._summaries: dict[str, SessionSummary] = {} + self._bind_compaction = bind_compaction def _is_expired(self, ts: datetime | str | None, now: datetime | None = None) -> bool: @@ -48,7 +53,10 @@ class AutoCompact: def _has_unarchived_messages(self, key: str) -> bool: session = self.sessions.get_or_create(key) - return session.last_archived < len(session.messages) + return any( + not message.get("_command") + for message in session.messages[session.last_archived:] + ) @classmethod def _is_internal_session(cls, key: str) -> bool: @@ -88,6 +96,7 @@ class AutoCompact: key, runtime=runtime, max_suffix=self._RECENT_SUFFIX_MESSAGES, + on_compaction=self._bind_compaction(key) if self._bind_compaction else None, ) if summary and summary != "(nothing)": session = self.sessions.get_or_create(key) diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index afcc69f82..fef4c4b5c 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -8,16 +8,23 @@ session history list in place. from __future__ import annotations +import asyncio from collections.abc import Awaitable, Callable from copy import deepcopy from dataclasses import dataclass, replace from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any, cast +from uuid import uuid4 from loguru import logger from nanobot.agent.context import TranscriptInput +from nanobot.bus.outbound_events import ( + ContextCompactionCallback, + ContextCompactionEvent, + emit_context_compaction, +) from nanobot.providers.base import ( LLMResponse, LLMUsage, @@ -198,6 +205,7 @@ class ModelRequestState: tool_definitions: list[dict[str, Any]] | None = None compaction: ContextCompactionState | None = None provider_compaction_applied: bool = False + compaction_callback: ContextCompactionCallback | None = None class ContextGovernor: @@ -412,33 +420,6 @@ class ContextGovernor: return None return measured, source - def fit_request( - self, - config: ContextGovernanceConfig, - messages: list[dict[str, Any]], - usage: LLMUsage | None, - *, - usage_matches_messages: bool, - tool_definitions: list[dict[str, Any]] | None, - request_context_tokens: int | None = None, - ) -> tuple[list[dict[str, Any]], bool]: - """Fit the request when its measured or estimated input is pressured.""" - pressure = self.request_pressure( - config, - messages, - usage, - usage_matches_messages=usage_matches_messages, - tool_definitions=tool_definitions, - request_context_tokens=request_context_tokens, - ) - if pressure is None: - return messages, False - return self.fit_to_budget( - config, - messages, - tool_definitions=tool_definitions, - ), True - @staticmethod def _summary_transcript( compaction: ContextCompactionState, @@ -493,18 +474,44 @@ class ContextGovernor: ) return - summary = await compaction.consolidate_provider_compaction( - response.provider_compaction_state, - deepcopy(accepted_messages), - compaction.active_summary, + compaction_id = uuid4().hex + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent(compaction_id=compaction_id, phase="started"), ) + try: + summary = await compaction.consolidate_provider_compaction( + response.provider_compaction_state, + deepcopy(accepted_messages), + compaction.active_summary, + ) + except (Exception, asyncio.CancelledError) as exc: + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent( + compaction_id=compaction_id, + phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", + ), + ) + raise if not summary: + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent(compaction_id=compaction_id, phase="failed"), + ) return compaction.active_summary = summary compaction.summary_checkpoint = SessionSummaryCheckpoint( summary=summary, transcript_boundary=transcript_boundary, ) + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent( + compaction_id=compaction_id, + phase="succeeded", + ), + ) async def _compact_request_history( self, @@ -516,46 +523,68 @@ class ContextGovernor: tool_definitions: list[dict[str, Any]] | None, ) -> list[dict[str, Any]]: """Replace accepted history H with a checkpoint while preserving delta.""" - delta_messages = compaction.delta_after_accepted(messages) - consolidation_prefix = self.prepare_messages_for_model( - state.config, - compaction.accepted_messages, + measured, _source = pressure + compaction_id = uuid4().hex + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent(compaction_id=compaction_id, phase="started"), ) - summary = await compaction.consolidate_history( - deepcopy(consolidation_prefix), - compaction.active_summary, - ) - if not summary: - measured, source = pressure - raise ContextWindowExceededError( - session_key=state.config.session_key, - estimated_tokens=measured, - input_budget=self.input_budget(state.config), - source=source, + try: + delta_messages = compaction.delta_after_accepted(messages) + consolidation_prefix = self.prepare_messages_for_model( + state.config, + compaction.accepted_messages, ) + summary = await compaction.consolidate_history( + deepcopy(consolidation_prefix), + compaction.active_summary, + ) + if not summary: + raise ContextWindowExceededError( + session_key=state.config.session_key, + estimated_tokens=measured, + input_budget=self.input_budget(state.config), + source=_source, + ) - compaction.active_summary = summary - prepared = self.prepare_messages_for_model( - state.config, - [ - *self._summary_transcript(compaction, summary), - {"role": "user", "content": SUMMARY_CONTINUATION_TEXT}, - *delta_messages, - ], - ) - # Responses-style state is append-only. Replacing H with a - # checkpoint requires a fresh request; a successful response may - # establish a new provider-owned state at the rewritten boundary. - state.conversation.replace_transcript(compaction.raw_messages) - state.usage = None - prepared = self.ensure_request_fits( - state.config, - prepared, - tool_definitions=tool_definitions, - ) - compaction.summary_checkpoint = SessionSummaryCheckpoint( - summary=summary, - transcript_boundary=compaction.raw_accepted_boundary, + compaction.active_summary = summary + prepared = self.prepare_messages_for_model( + state.config, + [ + *self._summary_transcript(compaction, summary), + {"role": "user", "content": SUMMARY_CONTINUATION_TEXT}, + *delta_messages, + ], + ) + # Responses-style state is append-only. Replacing H with a + # checkpoint requires a fresh request; a successful response may + # establish a new provider-owned state at the rewritten boundary. + state.conversation.replace_transcript(compaction.raw_messages) + state.usage = None + prepared = self.ensure_request_fits( + state.config, + prepared, + tool_definitions=tool_definitions, + ) + compaction.summary_checkpoint = SessionSummaryCheckpoint( + summary=summary, + transcript_boundary=compaction.raw_accepted_boundary, + ) + except (Exception, asyncio.CancelledError) as exc: + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent( + compaction_id=compaction_id, + phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", + ), + ) + raise + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent( + compaction_id=compaction_id, + phase="succeeded", + ), ) return prepared @@ -590,7 +619,7 @@ class ContextGovernor: request_was_fitted = False compaction = state.compaction if compaction is None: - prepared, request_was_fitted = self.fit_request( + pressure = self.request_pressure( state.config, prepared, state.usage, @@ -598,6 +627,29 @@ class ContextGovernor: tool_definitions=tool_definitions, request_context_tokens=request_context_tokens, ) + if pressure is not None: + compaction_id = uuid4().hex + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent(compaction_id=compaction_id, phase="started"), + ) + try: + prepared = self.fit_to_budget( + state.config, + prepared, + tool_definitions=tool_definitions, + ) + except Exception: + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent(compaction_id=compaction_id, phase="failed"), + ) + raise + await emit_context_compaction( + state.compaction_callback, + ContextCompactionEvent(compaction_id=compaction_id, phase="succeeded"), + ) + request_was_fitted = True else: pressure = self.request_pressure( state.config, diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 27aaa88d3..14846f0be 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -50,10 +50,14 @@ from nanobot.agent.turn_delivery import ( from nanobot.agent.turn_delivery import TurnRoute as TurnRoute from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage -from nanobot.bus.outbound_events import StreamedResponseEvent +from nanobot.bus.outbound_events import ( + ContextCompactionCallback, + StreamedResponseEvent, +) from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import RuntimeEventBus from nanobot.command import CommandContext, CommandRouter, register_builtin_commands +from nanobot.command.router import normalize_command_text from nanobot.config.schema import AgentDefaults, ModelPresetConfig from nanobot.llm_usage.context import source_from_request from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState @@ -456,6 +460,7 @@ class AgentLoop: sessions=self.sessions, consolidator=self.consolidator, session_ttl_minutes=session_ttl_minutes, + bind_compaction=self._idle_compaction_callback, ) self._idle_compact_check_interval_s = idle_compact_check_interval_seconds self._next_idle_compact_check_at = time.monotonic() @@ -798,6 +803,14 @@ class AgentLoop: dispatch_fn: Callable[[CommandContext], Awaitable[OutboundMessage | None]], ) -> None: """Dispatch a command directly from the run() loop and publish the result.""" + if normalize_command_text(raw).lower() == "/compact": + # Compaction must wait for the active turn to commit its session. + task = asyncio.create_task(self._dispatch(msg)) + self._track_active_task(key, task) + # Enter dispatch's cancellation handler before consuming a queued /stop. + await asyncio.sleep(0) + return + async def dispatch_and_publish() -> None: ctx = CommandContext(msg=msg, session=None, key=key, raw=raw, loop=self) result = await dispatch_fn(ctx) @@ -909,18 +922,27 @@ class AgentLoop: return UNIFIED_SESSION_KEY return msg.session_key - def _remember_unified_session_route( + def _idle_compaction_callback( + self, + session_key: str, + ) -> ContextCompactionCallback | None: + """Bind one idle compaction to its current user-facing destination.""" + session = self.sessions.get_or_create(session_key) + return self.turn_delivery_factory.session_compaction_callback( + session_key, session.metadata, + ) + + def _remember_session_route( self, session: Session, msg: InboundMessage, *, + delivery: TurnDelivery, is_user_turn: bool, ) -> None: - """Remember the latest user-facing route for unified-session delivery.""" + """Remember the latest user-facing destination, including channel threads.""" if ( - not self._unified_session - or session.key != UNIFIED_SESSION_KEY - or not is_user_turn + not is_user_turn or msg.channel in {"cli", "system"} or msg.sender_id == "subagent" ): @@ -928,7 +950,9 @@ class AgentLoop: _, automation_metadata = automation_history_overrides(msg.metadata) if automation_metadata: return - remember_last_channel(session.metadata, msg.channel, msg.chat_id) + delivery.remember_session_route(session.metadata) + if self._unified_session and session.key == UNIFIED_SESSION_KEY: + remember_last_channel(session.metadata, msg.channel, msg.chat_id) async def _run_agent_loop( self, @@ -937,6 +961,7 @@ class AgentLoop: on_stream: Callable[[str], Awaitable[None]] | None = None, on_stream_end: Callable[..., Awaitable[None]] | None = None, on_retry_wait: Callable[[str], Awaitable[None]] | None = None, + on_context_compaction: ContextCompactionCallback | None = None, *, runtime: LLMRuntime, session: Session | None = None, @@ -1222,6 +1247,7 @@ class AgentLoop: channel=request_ctx.channel, metadata=request_metadata, ), + compaction_callback=on_context_compaction, )) finally: turn_scope_stack.close() @@ -1419,6 +1445,7 @@ class AgentLoop: delivery = self.turn_delivery_factory.unrouted(msg, session_key) pending: asyncio.Queue[InboundMessage] | None = None + completion_published = False try: async with lock, gate: # Only the task that owns the session lock may publish the @@ -1443,6 +1470,7 @@ class AgentLoop: response, publish_completion=not continuing, ) + completion_published = not continuing for _, coordinator in self._automation_turn_coordinators: coordinator.complete(msg, response=response) except asyncio.CancelledError: @@ -1520,6 +1548,10 @@ class AgentLoop: if not turn_continuation.internal_continuation_pending(msg.metadata): await delivery.idle() await self._publish_next_deferred_automation_turn(session_key) + except asyncio.CancelledError: + if not completion_published and normalize_command_text(msg.content).lower() == "/compact": + await delivery.complete(None, publish_completion=True) + raise finally: if ( recovery_task_registered @@ -1811,9 +1843,10 @@ class AgentLoop: else: logger.info("Processing message from {}:{}: [content hidden]", msg.channel, msg.sender_id) - self._remember_unified_session_route( + self._remember_session_route( session, msg, + delivery=ctx.delivery, is_user_turn=ctx.original_user_text is not None, ) await ctx.delivery.started() @@ -1859,6 +1892,9 @@ class AgentLoop: turn_scopes=ctx.turn_scopes, ) result = await self.commands.dispatch(cmd_ctx) + if cmd_ctx.raw.lower() == "/compact": + # Compaction reports through events, not an archiveable command reply. + return True if result is not None: ctx.outbound = result # Shortcut commands skip BUILD and SAVE, so we must persist the @@ -2022,6 +2058,7 @@ class AgentLoop: tools=ctx.tools, request_context=ctx.request_context, provider_state=ctx.provider_state, + on_context_compaction=ctx.delivery.context_compaction, ) ctx.final_content = result.final_content ctx.all_messages = result.messages diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.py index 51a726dad..37046aa8d 100644 --- a/nanobot/agent/memory.py +++ b/nanobot/agent/memory.py @@ -17,9 +17,15 @@ from contextlib import suppress from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Iterator, cast +from uuid import uuid4 from loguru import logger +from nanobot.bus.outbound_events import ( + ContextCompactionCallback, + ContextCompactionEvent, + emit_context_compaction, +) from nanobot.llm_usage.context import llm_usage_source from nanobot.providers.base import ProviderCallContext, ProviderConversationState from nanobot.runtime_context import public_history_messages @@ -930,9 +936,8 @@ class MemoryArchiver: if not summary: logger.warning("Memory archive provider summary was not safe to replay, raw-dumping") return raw_fallback() - if summary == "(nothing)": - return "(nothing)" - self.store.append_history(summary, session_key=session_key) + if summary != "(nothing)": + self.store.append_history(summary, session_key=session_key) return summary async def archive_session( @@ -944,7 +949,10 @@ class MemoryArchiver: input_token_budget: int, ) -> str | None: """Archive a captured session prefix without mutating the session.""" - messages = list(session.messages[session.last_archived:archive_end]) + messages = [ + message for message in session.messages[session.last_archived:archive_end] + if not message.get("_command") + ] if not messages: return None session_summary = session_summary_from_metadata( @@ -1184,6 +1192,7 @@ class Consolidator: *, runtime: LLMRuntime, max_suffix: int = MIN_COMPACTED_REPLAY_MESSAGES, + on_compaction: ContextCompactionCallback | None = None, ) -> str | None: """Archive the full idle tail while keeping recent messages replayable. @@ -1205,25 +1214,56 @@ class Consolidator: archive_start = session.last_archived messages_to_archive = list(session.messages[archive_start:]) - if not messages_to_archive: + if not any(not message.get("_command") for message in messages_to_archive): return "" + compaction_id = uuid4().hex + await emit_context_compaction( + on_compaction, + ContextCompactionEvent(compaction_id=compaction_id, phase="started"), + ) last_active = session.updated_at archive_end = archive_start + len(messages_to_archive) - summary = await self.archive_session( - session, - archive_end=archive_end, - runtime=runtime, - ) + try: + summary = await self.archive_session( + session, + archive_end=archive_end, + runtime=runtime, + ) + if summary is not None: + self._set_last_summary( + session, + summary, + last_active=last_active, + ) + + # A turn can append while the provider call is in flight. Advance only + # through the captured batch so new messages remain eligible next time. + session.last_archived = archive_end + self.sessions.save(session) + except (Exception, asyncio.CancelledError) as exc: + await emit_context_compaction( + on_compaction, + ContextCompactionEvent( + compaction_id=compaction_id, + phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", + ), + ) + raise if summary is None: + await emit_context_compaction( + on_compaction, + ContextCompactionEvent(compaction_id=compaction_id, phase="failed"), + ) return None - self._set_last_summary(session, summary, last_active=last_active) - - # A turn can append while the provider call is in flight. Advance only - # through the captured batch so new messages remain eligible next time. - session.last_archived = archive_end - self.sessions.save(session) + await emit_context_compaction( + on_compaction, + ContextCompactionEvent( + compaction_id=compaction_id, + phase="succeeded", + ), + ) visible = session.get_history( max_messages=MIN_COMPACTED_REPLAY_MESSAGES, diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py index 41a048c54..69aed146e 100644 --- a/nanobot/agent/runner.py +++ b/nanobot/agent/runner.py @@ -27,6 +27,7 @@ from nanobot.agent.context_governance import ( from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext from nanobot.agent.tools.execution import execute_tool_calls from nanobot.agent.tools.registry import ToolRegistry +from nanobot.bus.outbound_events import ContextCompactionCallback from nanobot.llm_usage.context import ( LLMUsageSource, bind_llm_usage_source, @@ -116,6 +117,7 @@ class AgentRunSpec: finalize_on_max_iterations: bool = True provider_state: ProviderConversationState | None = None llm_usage_source: LLMUsageSource | None = None + compaction_callback: ContextCompactionCallback | None = None @dataclass(slots=True) @@ -431,6 +433,7 @@ class AgentRunner: config=governance_config, conversation=conversation_state, compaction=compaction, + compaction_callback=spec.compaction_callback, ) for iteration in range(spec.max_iterations): diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.py index 92a22af71..a5a08af3b 100644 --- a/nanobot/agent/turn_delivery.py +++ b/nanobot/agent/turn_delivery.py @@ -5,11 +5,14 @@ from __future__ import annotations import dataclasses import time from collections.abc import Awaitable, Callable +from copy import deepcopy from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, cast from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.outbound_events import ( + ContextCompactionCallback, + ContextCompactionEvent, RetryWaitEvent, StreamDeltaEvent, StreamedResponseEvent, @@ -20,6 +23,7 @@ from nanobot.bus.progress import build_bus_progress_callback from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import RuntimeEventBus, RuntimeEventPublisher from nanobot.providers.base import LLMUsage +from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata if TYPE_CHECKING: from nanobot.utils.llm_runtime import LLMRuntime @@ -43,7 +47,7 @@ RetryWaitCallback = Callable[[str], Awaitable[None]] class TurnDeliveryFactory: - """Create per-turn delivery objects from an optional edge-owned route policy.""" + """Route turn delivery and session-level notifications.""" def __init__( self, @@ -91,6 +95,45 @@ class TurnDeliveryFactory: ), ) + def session_compaction_callback( + self, + session_key: str, + session_metadata: dict[str, Any], + ) -> ContextCompactionCallback | None: + """Bind idle notifications to one route without acquiring a turn owner.""" + saved_route = session_metadata.get("_compaction_route") + if isinstance(saved_route, dict): + saved_route = cast(dict[str, Any], saved_route) + channel, chat_id = saved_route.get("channel"), saved_route.get("chat_id") + metadata = saved_route.get("metadata", {}) + if not isinstance(channel, str) or not isinstance(chat_id, str): + return + if not isinstance(metadata, dict): + return + metadata = cast(dict[str, Any], metadata) + else: + # Older sessions have no route snapshot. Only direct clients have a + # session key that is also an unambiguous delivery address. + route = ( + last_channel_from_metadata(session_metadata) + if session_key == UNIFIED_SESSION_KEY + else tuple(session_key.split(":", 1)) + ) + if not route or len(route) != 2 or route[0] not in {"websocket", "cli"}: + return + channel, chat_id = route + metadata = {} + metadata = deepcopy(metadata) + + async def publish(event: ContextCompactionEvent) -> None: + await self.bus.publish_outbound( + outbound_message_for_event( + channel=channel, chat_id=chat_id, event=event, metadata=metadata, + ) + ) + + return publish + @staticmethod def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute: if msg.channel != "system": @@ -174,6 +217,41 @@ class TurnDelivery: return _on_retry_wait + async def context_compaction(self, event: ContextCompactionEvent) -> None: + """Publish one compaction transition without completing the active turn.""" + await self.bus.publish_outbound( + outbound_message_for_event( + channel=self.delivery_message.channel, + chat_id=self.delivery_message.chat_id, + event=event, + metadata=self.delivery_message.metadata, + ) + ) + + def remember_session_route(self, session_metadata: dict[str, Any]) -> None: + """Keep only routing fields needed to deliver a later idle notification.""" + source = self.route.metadata + channel_type = self.route.channel.split(".", 1)[0] + fields = { + "telegram": ("message_thread_id",), + "matrix": ("thread_root_event_id", "thread_reply_to_event_id"), + "feishu": ("message_id", "thread_id", "chat_type"), + }.get(channel_type, ()) + metadata = { + key: source[key] for key in fields if key in source + } + if channel_type in {"slack", "mattermost"}: + nested = source.get(channel_type) + if isinstance(nested, dict): + nested = cast(dict[str, Any], nested) + fields = ("thread_ts",) if channel_type == "slack" else ("root_id", "thread_ts") + metadata[channel_type] = {key: nested[key] for key in fields if key in nested} + session_metadata["_compaction_route"] = { + "channel": self.route.channel, + "chat_id": self.route.chat_id, + "metadata": metadata, + } + async def started(self) -> None: if self.route.publish_lifecycle: await self.runtime_event_publisher.session_turn_started( diff --git a/nanobot/bus/outbound_events.py b/nanobot/bus/outbound_events.py index fcc000e4e..04a3654e2 100644 --- a/nanobot/bus/outbound_events.py +++ b/nanobot/bus/outbound_events.py @@ -7,9 +7,11 @@ message's explicit ``event`` field rather than in reserved metadata flags. from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass, replace -from typing import Any, cast +from typing import Any, Literal, cast + +from loguru import logger from nanobot.bus.events import OutboundMessage from nanobot.providers.base import LLMUsage @@ -114,6 +116,30 @@ class TurnModelUpdatedEvent(OutboundEvent): fallback: bool = False +@dataclass(frozen=True) +class ContextCompactionEvent(OutboundEvent): + """A channel-safe transition for one logical context compaction.""" + + compaction_id: str + phase: Literal["started", "succeeded", "failed", "cancelled"] + + +ContextCompactionCallback = Callable[[ContextCompactionEvent], Awaitable[None]] + + +async def emit_context_compaction( + callback: ContextCompactionCallback | None, + event: ContextCompactionEvent, +) -> None: + """Notify observers without allowing delivery failure to alter compaction.""" + if callback is None: + return + try: + await callback(event) + except Exception: + logger.exception("Failed to publish context compaction event") + + def outbound_message_for_event( *, channel: str, @@ -162,6 +188,14 @@ def _event_content(event: OutboundEvent) -> str: ProgressEvent | RetryWaitEvent | StreamDeltaEvent | StreamEndEvent | UserInputEvent, ): return event.content + if isinstance(event, ContextCompactionEvent): + if event.phase == "started": + return "Compressing context…" + if event.phase == "failed": + return "Unable to compact context." + if event.phase == "cancelled": + return "Context compaction cancelled." + return "Context compacted." return "" diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index dc45c9699..89e82a125 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -1388,7 +1388,14 @@ class WebSocketChannel(BaseChannel): """Persist as requested, frame, and fan out one encoded WebUI payload.""" conns = list(self._subs.get(chat_id, ())) body: dict[str, Any] = dict(payload) - if persistence == "turn_complete": + if persistence == "turn_activity": + self._persist_turn_transcript_event( + chat_id, + body, + metadata=metadata, + phase="activity", + ) + elif persistence == "turn_complete": canonical_webui_turn = (metadata or {}).get("webui") is True prior_persistence_failure = ( canonical_webui_turn diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index c803459b8..0e5e4ac6a 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -24,6 +24,7 @@ from nanobot.bus.events import ( OutboundMessage, ) from nanobot.bus.outbound_events import ( + ContextCompactionEvent, GoalStateSyncEvent, GoalStatusEvent, ProgressEvent, @@ -2805,6 +2806,68 @@ async def test_send_turn_end_emits_turn_end_event() -> None: ] +@pytest.mark.asyncio +async def test_context_compaction_started_is_live_only() -> None: + bus = MagicMock() + channel = WebSocketChannel( + {"enabled": True, "allowFrom": ["*"]}, + bus, + gateway=_basic_handler(bus), + ) + mock_ws = AsyncMock() + channel._attach(mock_ws, "chat-compaction-started") + + await channel.send(OutboundMessage( + channel="websocket", + chat_id="chat-compaction-started", + content="Compressing context…", + event=ContextCompactionEvent( + compaction_id="compact-started", + phase="started", + ), + )) + + assert _sent_ws_payloads(mock_ws) == [{ + "event": "context_compaction", + "chat_id": "chat-compaction-started", + "compaction_id": "compact-started", + "phase": "started", + }] + assert read_transcript_lines("websocket:chat-compaction-started") == [] + + +@pytest.mark.asyncio +async def test_context_compaction_is_structured_persisted_and_summary_free() -> None: + bus = MagicMock() + channel = WebSocketChannel( + {"enabled": True, "allowFrom": ["*"]}, + bus, + gateway=_basic_handler(bus), + ) + mock_ws = AsyncMock() + channel._attach(mock_ws, "chat-compaction") + + await channel.send(OutboundMessage( + channel="websocket", + chat_id="chat-compaction", + content="Context compacted · LLM summary", + event=ContextCompactionEvent( + compaction_id="compact-1", + phase="succeeded", + ), + )) + + expected = { + "event": "context_compaction", + "chat_id": "chat-compaction", + "compaction_id": "compact-1", + "phase": "succeeded", + } + assert _sent_ws_payloads(mock_ws) == [expected] + [persisted] = read_transcript_lines("websocket:chat-compaction") + assert {key: persisted[key] for key in expected} == expected + + @pytest.mark.asyncio async def test_recovery_state_is_a_structured_event_not_assistant_text() -> None: bus = MagicMock() diff --git a/nanobot/cli/terminal.py b/nanobot/cli/terminal.py index 3ec728732..03f71c44e 100644 --- a/nanobot/cli/terminal.py +++ b/nanobot/cli/terminal.py @@ -24,6 +24,7 @@ from rich.text import Text from nanobot import __logo__ from nanobot.bus.outbound_events import ( + ContextCompactionEvent, ProgressEvent, RetryWaitEvent, outbound_event_from_message, @@ -369,6 +370,9 @@ async def _maybe_print_interactive_progress( reasoning_buffer: _ReasoningBuffer | None = None, ) -> bool: event = outbound_event_from_message(msg) + if isinstance(event, ContextCompactionEvent): + await _print_interactive_progress_line(msg.content, thinking, renderer) + return True if isinstance(event, RetryWaitEvent): await _print_interactive_progress_line(msg.content, thinking, renderer) return True diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py index be85a7f9c..29be24be8 100644 --- a/nanobot/command/builtin.py +++ b/nanobot/command/builtin.py @@ -11,6 +11,8 @@ from contextlib import suppress from dataclasses import dataclass, replace from typing import TYPE_CHECKING, Any, Literal, cast +from loguru import logger + from nanobot import __version__ from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text @@ -71,6 +73,12 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = ( "square-pen", lifecycle="finalize_active_turn", ), + BuiltinCommandSpec( + "/compact", + "Compact context", + "Compact this chat's context and continue the conversation.", + "archive", + ), BuiltinCommandSpec( "/stop", "Stop current task", @@ -337,6 +345,29 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage: ) +async def cmd_compact(ctx: CommandContext) -> None: + """Compact the current session without resetting the conversation.""" + loop = ctx.loop + session = ctx.session or loop.sessions.get_or_create(ctx.key) + runtime = ctx.runtime or loop.runtime_for_session(session) + delivery = loop.turn_delivery_factory.create(ctx.msg, ctx.key) + + try: + summary = await loop.consolidator.compact_idle_session( + ctx.key, + runtime=runtime, + on_compaction=delivery.context_compaction, + ) + except Exception: + logger.exception("Manual context compaction failed for {}", ctx.key) + return + + if summary: + refreshed = loop.sessions.get_or_create(ctx.key) + refreshed.provider_state = None + loop.sessions.save(refreshed) + + def _format_preset_names(names: list[str]) -> str: return ", ".join(f"`{name}`" for name in names) if names else "(none configured)" @@ -1044,6 +1075,7 @@ def register_builtin_commands(router: CommandRouter) -> None: router.priority("/restart", cmd_restart) router.priority("/status", cmd_status) router.exact("/new", cmd_new) + router.exact("/compact", cmd_compact) router.exact("/status", cmd_status) router.exact("/model", cmd_model) router.prefix("/model ", cmd_model) diff --git a/nanobot/webui/outbound_projection.py b/nanobot/webui/outbound_projection.py index 27d525300..f1d3aa7d0 100644 --- a/nanobot/webui/outbound_projection.py +++ b/nanobot/webui/outbound_projection.py @@ -8,6 +8,7 @@ from loguru import logger from nanobot.bus.events import OutboundMessage from nanobot.bus.outbound_events import ( + ContextCompactionEvent, GoalStateSyncEvent, GoalStatusEvent, ProgressEvent, @@ -28,6 +29,7 @@ from nanobot.webui.metadata import ( from nanobot.webui.outbound_wire import ( WebUIWirePayload, WebUIWirePersistence, + encode_context_compaction, encode_recovery_state, encode_turn_end, ) @@ -152,6 +154,7 @@ class WebUIOutboundProjector: SessionUpdatedEvent, GoalStatusEvent, GoalStateSyncEvent, + ContextCompactionEvent, ) log = ( logger.debug @@ -187,6 +190,14 @@ class WebUIOutboundProjector: persistence="transient", ) return + if isinstance(event, ContextCompactionEvent): + await self._transport.send_payload( + msg.chat_id, + encode_context_compaction(msg.chat_id, event), + persistence="transient" if event.phase == "started" else "turn_activity", + metadata=msg.metadata, + ) + return if isinstance(event, GoalStateSyncEvent): if conns: await self._transport.send_goal_state( diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index 662e6930b..0cd5af283 100644 --- a/nanobot/webui/outbound_wire.py +++ b/nanobot/webui/outbound_wire.py @@ -5,7 +5,11 @@ from __future__ import annotations from collections.abc import Mapping from typing import Any, Literal, NotRequired, TypeAlias, TypedDict -from nanobot.bus.outbound_events import RecoveryStateEvent, TurnEndEvent +from nanobot.bus.outbound_events import ( + ContextCompactionEvent, + RecoveryStateEvent, + TurnEndEvent, +) from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY @@ -32,8 +36,20 @@ class TurnEndWirePayload(_ChatWirePayload): context_window_tokens: NotRequired[int] -WebUIWirePayload: TypeAlias = RecoveryStateWirePayload | TurnEndWirePayload -WebUIWirePersistence: TypeAlias = Literal["transient", "turn_complete"] +class ContextCompactionWirePayload(_ChatWirePayload): + event: Literal["context_compaction"] + compaction_id: str + phase: str + + +WebUIWirePayload: TypeAlias = ( + ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload +) +WebUIWirePersistence: TypeAlias = Literal[ + "transient", + "turn_activity", + "turn_complete", +] def encode_recovery_state( @@ -55,6 +71,20 @@ def encode_recovery_state( return payload +def encode_context_compaction( + chat_id: str, + event: ContextCompactionEvent, +) -> ContextCompactionWirePayload: + """Project one summary-free compaction transition onto its stable wire shape.""" + payload: ContextCompactionWirePayload = { + "event": "context_compaction", + "chat_id": chat_id, + "compaction_id": event.compaction_id, + "phase": event.phase, + } + return payload + + def encode_turn_end( chat_id: str, event: TurnEndEvent, diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 405ce6410..de0f8a0b5 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -2321,6 +2321,48 @@ def replay_transcript_to_ui_messages( close_reasoning(messages) continue + if ev == "context_compaction": + compaction_id = rec.get("compaction_id") + phase = rec.get("phase") + if ( + not isinstance(compaction_id, str) + or not compaction_id + or phase not in {"started", "succeeded", "failed", "cancelled"} + ): + continue + compaction: dict[str, Any] = { + "id": compaction_id, + "phase": phase, + } + payload: dict[str, Any] = { + "id": f"compaction-{compaction_id}", + "role": "assistant", + "content": "", + "kind": "compaction", + "createdAt": _created_at_ms(rec, idx), + "compaction": compaction, + **_turn_fields(rec, "activity"), + } + existing = next( + ( + message_index + for message_index, message in enumerate(messages) + if message.get("id") == payload["id"] + ), + None, + ) + if existing is None: + messages.append(payload) + else: + payload["createdAt"] = messages[existing].get( + "createdAt", + payload["createdAt"], + ) + messages[existing] = payload + active_activity_segment_id = None + active_file_edit_segment_id = None + continue + if ev == "message": if suppress_until_turn_end and rec.get("kind") in ( "tool_hint", diff --git a/tests/agent/test_auto_compact.py b/tests/agent/test_auto_compact.py index c1cfc89c6..9fcbd599b 100644 --- a/tests/agent/test_auto_compact.py +++ b/tests/agent/test_auto_compact.py @@ -83,7 +83,14 @@ def _make_fake_compact( ): state = {"count": 0} - async def _fake_compact(key: str, *, runtime, max_suffix: int = 8) -> str: + async def _fake_compact( + key: str, + *, + runtime, + max_suffix: int = 8, + trigger: str = "policy", + on_compaction=None, + ) -> str: state["count"] += 1 session = loop.sessions.get_or_create(key) @@ -884,7 +891,7 @@ class TestProactiveAutoCompact: started = asyncio.Event() block_forever = asyncio.Event() - async def _slow_compact(key, *, runtime, max_suffix=8): + async def _slow_compact(key, *, runtime, max_suffix=8, **_kwargs): nonlocal archive_count archive_count += 1 started.set() @@ -916,7 +923,7 @@ class TestProactiveAutoCompact: session.updated_at = datetime.now() - timedelta(minutes=20) loop.sessions.save(session) - async def _failing_compact(key, *, runtime, max_suffix=8): + async def _failing_compact(key, *, runtime, max_suffix=8, **_kwargs): raise RuntimeError("LLM down") loop.consolidator.compact_idle_session = _failing_compact diff --git a/tests/agent/test_autocompact_unit.py b/tests/agent/test_autocompact_unit.py index aee1c90bd..7a66aa8d1 100644 --- a/tests/agent/test_autocompact_unit.py +++ b/tests/agent/test_autocompact_unit.py @@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest from nanobot.agent.autocompact import AutoCompact +from nanobot.bus.outbound_events import ContextCompactionEvent from nanobot.session.manager import Session, SessionManager @@ -268,6 +269,7 @@ class TestCheckExpired: "cli:old", runtime=admitted, max_suffix=ac._RECENT_SUFFIX_MESSAGES, + on_compaction=None, ) @pytest.mark.parametrize("resolution_error", [KeyError, ValueError]) @@ -443,8 +445,39 @@ class TestArchiveDelegates: "cli:test", runtime=runtime, max_suffix=ac._RECENT_SUFFIX_MESSAGES, + on_compaction=None, ) + @pytest.mark.asyncio + async def test_forwards_timeout_compaction_events_with_session_key(self): + sessions = MagicMock(spec=SessionManager) + consolidator = MagicMock() + observed: list[tuple[str, ContextCompactionEvent]] = [] + + def bind(key: str): + async def publish(event: ContextCompactionEvent) -> None: + observed.append((key, event)) + return publish + + async def compact(key: str, **kwargs): + event = ContextCompactionEvent(compaction_id="compact-1", phase="started") + await kwargs["on_compaction"](event) + return "Summary." + + consolidator.compact_idle_session = AsyncMock(side_effect=compact) + ac = AutoCompact( + sessions=sessions, + consolidator=consolidator, + session_ttl_minutes=15, + bind_compaction=bind, + ) + + await ac._archive("cli:test", runtime=_runtime()) + + assert len(observed) == 1 + assert observed[0][0] == "cli:test" + assert observed[0][1].phase == "started" + @pytest.mark.asyncio async def test_dream_session_is_ignored(self): ac = _make_autocompact() diff --git a/tests/agent/test_consolidator.py b/tests/agent/test_consolidator.py index 6f5d11829..5e11942b7 100644 --- a/tests/agent/test_consolidator.py +++ b/tests/agent/test_consolidator.py @@ -10,6 +10,7 @@ from nanobot.agent.memory import ( Consolidator, MemoryStore, ) +from nanobot.bus.outbound_events import ContextCompactionEvent from nanobot.providers.base import ( GenerationSettings, LLMResponse, @@ -141,7 +142,7 @@ class TestTurnTranscriptSummary: content="replacement checkpoint", ) - summary = await consolidator.summarize_transcript( + result = await consolidator.summarize_transcript( accepted, "previous checkpoint", runtime=runtime, @@ -149,7 +150,7 @@ class TestTurnTranscriptSummary: tools=tools, ) - assert summary == "replacement checkpoint" + assert result == "replacement checkpoint" call = mock_provider.chat_with_retry.await_args.kwargs assert call["messages"][:-1] == accepted assert call["messages"][-1]["role"] == "user" @@ -172,7 +173,7 @@ class TestTurnTranscriptSummary: content="replacement checkpoint", ) - summary = await consolidator.summarize_provider_compaction( + result = await consolidator.summarize_provider_compaction( state, accepted, "previous checkpoint", @@ -181,7 +182,7 @@ class TestTurnTranscriptSummary: tools=[{"type": "function", "function": {"name": "inspect"}}], ) - assert summary == "replacement checkpoint" + assert result == "replacement checkpoint" call = mock_provider.chat_with_retry.await_args.kwargs assert call["messages"][0] == accepted[0] assert call["messages"][-1]["content"] == _ARCHIVE_PROMPT @@ -242,7 +243,7 @@ class TestConsolidatorSummarize: async def test_summarize_appends_to_history( self, consolidator, mock_provider, store, runtime ): - """Consolidator should call LLM to summarize, then append to HISTORY.md.""" + """Consolidator should persist the LLM summary in history.jsonl.""" mock_provider.chat_with_retry.return_value = MagicMock( content="User fixed a bug in the auth module." ) @@ -555,6 +556,56 @@ class TestCompactIdleSession: assert "last_active" in meta assert reloaded.updated_at == old_ts + @pytest.mark.asyncio + async def test_emits_manual_compaction_lifecycle( + self, real_consolidator, mock_provider, runtime + ): + mock_provider.chat_with_retry.return_value = MagicMock( + content="Summary.", finish_reason="stop" + ) + session = real_consolidator.sessions.get_or_create("cli:events") + session.add_message("user", "question") + session.add_message("assistant", "answer") + real_consolidator.sessions.save(session) + events: list[ContextCompactionEvent] = [] + + async def observe(event: ContextCompactionEvent) -> None: + events.append(event) + + result = await real_consolidator.compact_idle_session( + "cli:events", + runtime=runtime, + on_compaction=observe, + ) + + assert result == "Summary." + assert [event.phase for event in events] == ["started", "succeeded"] + assert events[0].compaction_id == events[1].compaction_id + + @pytest.mark.asyncio + async def test_event_callback_failure_does_not_abort_compaction( + self, real_consolidator, mock_provider, runtime + ): + mock_provider.chat_with_retry.return_value = MagicMock( + content="Summary.", finish_reason="stop" + ) + session = real_consolidator.sessions.get_or_create("cli:event-callback-failure") + session.add_message("user", "question") + real_consolidator.sessions.save(session) + + async def fail_observer(_event: ContextCompactionEvent) -> None: + raise RuntimeError("channel unavailable") + + result = await real_consolidator.compact_idle_session( + "cli:event-callback-failure", + runtime=runtime, + on_compaction=fail_observer, + ) + + assert result == "Summary." + reloaded = real_consolidator.sessions.get_or_create("cli:event-callback-failure") + assert reloaded.last_archived == 1 + @pytest.mark.asyncio async def test_short_idle_session_archives_once( self, real_consolidator, mock_provider, store, runtime @@ -894,6 +945,8 @@ class TestCompactIdleSession: mock_provider.chat_with_retry.side_effect = RuntimeError("LLM unavailable") sessions = real_consolidator.sessions session = sessions.get_or_create("cli:fail") + session.add_message("user", "/compact", _command=True) + session.add_message("assistant", "Nothing to compact.", _command=True) for i in range(10): session.add_message("user", f"u{i}") session.add_message("assistant", f"a{i}") @@ -907,12 +960,11 @@ class TestCompactIdleSession: # raw_archive should have been called (history.jsonl gets an entry) entries = store.read_unprocessed_history(since_cursor=0) - assert any("[RAW]" in e["content"] for e in entries) + assert entries[0]["content"].startswith("[RAW] 20 messages") reloaded = sessions.get_or_create("cli:fail") - assert len(reloaded.messages) == 20 - assert reloaded.messages[0]["content"] == "u0" - assert reloaded.last_archived == 20 + assert reloaded.messages == session.messages + assert reloaded.last_archived == 22 assert reloaded.metadata["_last_summary"]["text"] == result assert [m["content"] for m in reloaded.get_history(max_messages=20)] == [ "u6", @@ -1356,6 +1408,7 @@ class TestArchivePersistence: ) persisted = store.read_unprocessed_history(since_cursor=0)[0]["content"] + assert summary is not None assert summary == persisted == "safe summary" async def test_oversized_summary_uses_history_emergency_cap( @@ -1376,4 +1429,5 @@ class TestArchivePersistence: entry = store.read_unprocessed_history(since_cursor=0)[0] assert len(entry["content"]) <= _HISTORY_ENTRY_HARD_CAP + 50 + assert summary is not None assert summary == entry["content"] diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py index 25a391c44..47ed4c68e 100644 --- a/tests/agent/test_loop_save_turn.py +++ b/tests/agent/test_loop_save_turn.py @@ -1197,6 +1197,9 @@ async def test_process_message_persists_unified_session_delivery_route(tmp_path: loop.sessions.invalidate(UNIFIED_SESSION_KEY) persisted = loop.sessions.get_or_create(UNIFIED_SESSION_KEY) assert persisted.metadata[LAST_CHANNEL_METADATA_KEY] == "feishu:oc_123" + assert persisted.metadata["_compaction_route"] == { + "channel": "feishu", "chat_id": "oc_123", "metadata": {}, + } @pytest.mark.parametrize( @@ -1251,7 +1254,10 @@ def test_unified_session_route_ignores_non_user_destinations( session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY) session.metadata[LAST_CHANNEL_METADATA_KEY] = "telegram:existing" - loop._remember_unified_session_route(session, msg, is_user_turn=is_user_turn) + loop._remember_session_route( + session, msg, is_user_turn=is_user_turn, + delivery=loop.turn_delivery_factory.unrouted(msg, session.key), + ) assert session.metadata[LAST_CHANNEL_METADATA_KEY] == "telegram:existing" diff --git a/tests/agent/test_runner_governance.py b/tests/agent/test_runner_governance.py index ff2e6701e..ad292dc6f 100644 --- a/tests/agent/test_runner_governance.py +++ b/tests/agent/test_runner_governance.py @@ -13,8 +13,10 @@ from nanobot.agent.context_governance import ( ContextGovernanceConfig, ContextGovernor, ContextWindowExceededError, + ModelRequestState, ) from nanobot.agent.runner import AgentRunner, AgentRunSpec +from nanobot.bus.outbound_events import ContextCompactionEvent from nanobot.config.schema import AgentDefaults from nanobot.providers.base import ( LLMProvider, @@ -23,6 +25,7 @@ from nanobot.providers.base import ( ProviderConversationState, ToolCallRequest, ) +from nanobot.providers.conversation_state import ProviderConversationStateController from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT _MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars @@ -369,7 +372,13 @@ async def test_native_compaction_uses_provider_request_boundary( lambda *_args: (100, "test-counter"), ) consolidate = AsyncMock(return_value="portable checkpoint") - consolidate_native = AsyncMock(return_value="portable checkpoint") + consolidate_native = AsyncMock( + return_value="portable checkpoint" + ) + compaction_events: list[ContextCompactionEvent] = [] + + async def observe_compaction(event: ContextCompactionEvent) -> None: + compaction_events.append(event) result = await AgentRunner().run(make_run_spec( provider, @@ -391,6 +400,7 @@ async def test_native_compaction_uses_provider_request_boundary( max_tokens=100, max_iterations=2, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, + compaction_callback=observe_compaction, )) consolidate.assert_not_awaited() @@ -405,6 +415,10 @@ async def test_native_compaction_uses_provider_request_boundary( assert result.provider_compaction_applied is True assert any(message.get("content") == "inspect the project" for message in result.messages) assert any(message.get("content") == "complete tool result" for message in result.messages) + assert [event.phase for event in compaction_events] == ["started", "succeeded"] + assert {event.compaction_id for event in compaction_events} == { + compaction_events[0].compaction_id + } async def test_runner_keeps_current_tool_exchange_outside_summary(monkeypatch): @@ -506,7 +520,14 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch): "nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate, ) - consolidate = AsyncMock(side_effect=["checkpoint-1", "checkpoint-2"]) + consolidate = AsyncMock(side_effect=[ + "checkpoint-1", + "checkpoint-2", + ]) + compaction_events: list[ContextCompactionEvent] = [] + + async def observe_compaction(event: ContextCompactionEvent) -> None: + compaction_events.append(event) result = await AgentRunner().run(make_run_spec( provider, @@ -521,6 +542,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch): max_tokens=100, max_iterations=3, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, + compaction_callback=observe_compaction, )) assert consolidate.await_count == 2 @@ -533,6 +555,13 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch): assert result.summary_checkpoint is not None assert result.summary_checkpoint.summary == "checkpoint-2" assert result.summary_checkpoint.transcript_boundary == 4 + assert [event.phase for event in compaction_events] == [ + "started", "succeeded", "started", "succeeded", + ] + first_id, second_id = compaction_events[0].compaction_id, compaction_events[2].compaction_id + assert first_id == compaction_events[1].compaction_id + assert second_id == compaction_events[3].compaction_id + assert first_id != second_id async def test_runner_refuses_checkpoint_that_cannot_fit_with_delta(monkeypatch): @@ -874,7 +903,7 @@ async def test_runner_fits_max_iteration_finalization_before_dispatch(monkeypatc ("input_tokens", "expected_fitted"), [(500, True), (100, False)], ) -def test_matching_reported_provider_usage_avoids_local_estimate( +async def test_matching_reported_provider_usage_avoids_local_estimate( monkeypatch, input_tokens, expected_fitted, @@ -901,18 +930,25 @@ def test_matching_reported_provider_usage_avoids_local_estimate( governor = ContextGovernor() monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: []) - _messages, fitted = governor.fit_request( - _governance_config(provider, tools, spec), + state = ModelRequestState( + config=_governance_config(provider, tools, spec), + conversation=ProviderConversationStateController( + provider=provider, model=spec.runtime.model, messages=spec.initial_messages, + ), + usage=LLMUsage.reported(input_tokens=input_tokens, output_tokens=10), + messages=spec.initial_messages, + tool_definitions=[], + ) + messages, _context = await governor.prepare_request( + state, spec.initial_messages, - LLMUsage.reported(input_tokens=input_tokens, output_tokens=10), - usage_matches_messages=True, tool_definitions=tools.get_definitions(), ) - assert fitted is expected_fitted + assert messages == ([] if expected_fitted else spec.initial_messages) -def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch): +async def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch): provider = MagicMock(spec=LLMProvider) tools = MagicMock() tools.get_definitions.return_value = [] @@ -934,15 +970,22 @@ def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch): governor = ContextGovernor() monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: []) - _messages, fitted = governor.fit_request( - _governance_config(provider, tools, spec), + state = ModelRequestState( + config=_governance_config(provider, tools, spec), + conversation=ProviderConversationStateController( + provider=provider, model=spec.runtime.model, messages=spec.initial_messages, + ), + usage=LLMUsage.reported(input_tokens=900, output_tokens=10), + messages=[{"role": "user", "content": "previous request"}], + tool_definitions=[], + ) + messages, _context = await governor.prepare_request( + state, spec.initial_messages, - LLMUsage.reported(input_tokens=900, output_tokens=10), - usage_matches_messages=False, tool_definitions=tools.get_definitions(), ) - assert fitted is True + assert messages == [] estimate.assert_called_once() diff --git a/tests/agent/test_turn_delivery.py b/tests/agent/test_turn_delivery.py index 69c9767ca..10e862288 100644 --- a/tests/agent/test_turn_delivery.py +++ b/tests/agent/test_turn_delivery.py @@ -4,6 +4,7 @@ import pytest from nanobot.agent.turn_delivery import TurnDeliveryFactory from nanobot.bus.events import InboundMessage +from nanobot.bus.outbound_events import ContextCompactionEvent from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import RuntimeEventBus from nanobot.session.manager import SessionManager @@ -14,6 +15,80 @@ from nanobot.webui.metadata import ( ) +@pytest.mark.parametrize("unified", [False, True]) +@pytest.mark.parametrize(("key", "channel", "chat_id", "metadata"), [ + ("slack:C123:1700000000.000100", "slack", "C123", + {"slack": {"thread_ts": "1700000000.000100"}}), + ("telegram:-100123:topic:42", "telegram", "-100123", {"message_thread_id": 42}), + ("discord:456:thread:777", "discord", "777", {}), + ("mattermost:channel:root", "mattermost", "channel", {"mattermost": {"root_id": "root"}}), + ("matrix:!room:example.org:thread:$root", "matrix", "!room:example.org", + {"thread_root_event_id": "$root", "thread_reply_to_event_id": "$reply"}), + ("feishu:chat:thread:root", "feishu", "chat", + {"message_id": "reply", "thread_id": "root", "chat_type": "group"}), + ("dingtalk:group:conversation:user", "dingtalk", "group:conversation", {}), +]) +async def test_idle_compaction_uses_the_session_delivery_route( + key, channel, chat_id, metadata, unified, +) -> None: + factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus()) + event = ContextCompactionEvent(compaction_id="compact-1", phase="started") + key = "unified:default" if unified else key + msg = InboundMessage( + channel=channel, sender_id="user", chat_id=chat_id, content="hello", + metadata={ + "webui_turn_id": "turn-1", "sender_name": "User", + "message_id": "received-1", "thread_id": "received-thread", **metadata, + }, + ) + delivery = factory.create(msg, key) + session_metadata = {} + delivery.remember_session_route(session_metadata) + + callback = factory.session_compaction_callback(key, session_metadata) + assert callback is not None + await callback(event) + + outbound = factory.bus.outbound.get_nowait() + assert (outbound.channel, outbound.chat_id, outbound.metadata) == (channel, chat_id, metadata) + assert outbound.event is event + + +async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None: + factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus()) + key = "unified:default" + session_metadata = {} + original = InboundMessage( + channel="slack", sender_id="user", chat_id="C123", content="hello", + metadata={"slack": {"thread_ts": "1700000000.000100"}}, + ) + factory.create(original, key).remember_session_route(session_metadata) + callback = factory.session_compaction_callback(key, session_metadata) + assert callback is not None + await callback(ContextCompactionEvent("compact-1", "started")) + + latest = InboundMessage( + channel="telegram", sender_id="user", chat_id="42", content="next question", + ) + factory.create(latest, key).remember_session_route(session_metadata) + await callback(ContextCompactionEvent("compact-1", "succeeded")) + + events = [factory.bus.outbound.get_nowait() for _ in range(2)] + assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [ + ("slack", "C123", {"slack": {"thread_ts": "1700000000.000100"}}), + ] * 2 + + +async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> None: + factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus()) + event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded") + callback = factory.session_compaction_callback("websocket:chat", {}) + assert callback is not None + await callback(event) + outbound = factory.bus.outbound.get_nowait() + assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event) + + def test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None: factory = TurnDeliveryFactory( MessageBus(), diff --git a/tests/bus/test_outbound_events.py b/tests/bus/test_outbound_events.py index 99eb259c3..f6a60b98e 100644 --- a/tests/bus/test_outbound_events.py +++ b/tests/bus/test_outbound_events.py @@ -2,6 +2,7 @@ from __future__ import annotations from nanobot.bus.events import OutboundMessage from nanobot.bus.outbound_events import ( + ContextCompactionEvent, GoalStateSyncEvent, GoalStatusEvent, ProgressEvent, @@ -18,6 +19,18 @@ from nanobot.bus.outbound_events import ( ) +def test_compaction_events_have_readable_channel_fallbacks() -> None: + for event, expected in [ + (ContextCompactionEvent("1", "started"), "Compressing context…"), + (ContextCompactionEvent("1", "succeeded"), "Context compacted."), + (ContextCompactionEvent("1", "failed"), "Unable to compact context."), + (ContextCompactionEvent("1", "cancelled"), "Context compaction cancelled."), + ]: + msg = outbound_message_for_event(channel="cli", chat_id="direct", event=event) + assert msg.content == expected + assert msg.event is event + + def test_progress_event_lives_on_outbound_message_event_field() -> None: tool_events = [{"phase": "start", "name": "read_file"}] file_edit_events = [{"phase": "end", "path": "app.py"}] diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.py new file mode 100644 index 000000000..8d5ba2586 --- /dev/null +++ b/tests/command/test_compact_command.py @@ -0,0 +1,208 @@ +"""Manual context compaction command behavior.""" + +import asyncio +from datetime import datetime, timedelta +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from nanobot.agent.loop import AgentLoop +from nanobot.bus.events import InboundMessage +from nanobot.bus.outbound_events import ContextCompactionEvent +from nanobot.bus.queue import MessageBus +from nanobot.bus.runtime_events import TurnCompleted +from nanobot.command.builtin import cmd_stop +from nanobot.command.router import CommandContext +from nanobot.providers.base import GenerationSettings, LLMResponse, ProviderConversationState + + +@pytest.fixture +async def loop(tmp_path): + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + provider.generation = GenerationSettings(max_tokens=100) + provider.can_resume_conversation_state.return_value = True + provider.chat_with_retry = AsyncMock(return_value=LLMResponse( + content="Portable checkpoint.", + finish_reason="stop", + )) + loop = AgentLoop( + bus=bus, + provider=provider, + workspace=tmp_path, + model="test-model", + context_window_tokens=128_000, + ) + loop.tools.get_definitions = MagicMock(return_value=[]) + try: + yield loop + finally: + await loop.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("command", ["/compact", " /COMPACT@nanobot "]) +async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command) -> None: + bus = loop.bus + session = loop.sessions.get_or_create("cli:test") + session.add_message("user", "important question") + session.add_message("assistant", "important answer") + session.provider_state = ProviderConversationState( + kind="openai_responses", + provider="openai:test", + model="test-model", + version=1, + payload={"items": []}, + ) + loop.sessions.save(session) + + msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content=command) + response = await loop._process_message(msg, runtime=loop.llm_runtime()) + + assert response is None + assert bus.outbound_size == 2 + started = bus.outbound.get_nowait().event + completed = bus.outbound.get_nowait().event + assert isinstance(started, ContextCompactionEvent) + assert isinstance(completed, ContextCompactionEvent) + assert started.phase == "started" + assert completed.phase == "succeeded" + assert started.compaction_id == completed.compaction_id + + loop.sessions.invalidate("cli:test") + reloaded = loop.sessions.get_or_create("cli:test") + assert reloaded.provider_state is None + assert reloaded.messages == session.messages + assert reloaded.last_archived == 2 + assert len(loop.consolidator.store.read_unprocessed_history(0)) == 1 + + response = await loop._process_message(msg, runtime=loop.llm_runtime()) + assert response is None + assert bus.outbound_size == 0 + loop.provider.chat_with_retry.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy_commands", [False, True]) +async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archive( + loop, legacy_commands, +) -> None: + key = "websocket:test" + session = loop.sessions.get_or_create(key) + session.add_message("user", "already archived") + session.add_message("assistant", "old answer") + session.last_archived = 2 + if legacy_commands: + session.add_message("user", "/compact", _command=True) + session.add_message("assistant", "Nothing to compact.", _command=True) + loop.sessions.save(session) + completions = [] + loop.runtime_events.subscribe(completions.append, TurnCompleted) + + await loop._dispatch(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/compact", + metadata={"webui_turn_id": "compact-turn"}, + )) + + assert loop.bus.outbound_size == 0 + assert len(completions) == 1 + assert completions[0].context.metadata["webui_turn_id"] == "compact-turn" + loop.sessions.invalidate(key) + reloaded = loop.sessions.get_or_create(key) + assert reloaded.messages == session.messages + assert reloaded.last_archived == 2 + assert loop.consolidator.store.read_unprocessed_history(0) == [] + + reloaded.updated_at = datetime.now() - timedelta(minutes=30) + loop.sessions.save(reloaded) + loop.auto_compact._ttl = 1 + schedule = MagicMock() + loop.auto_compact.check_expired(schedule, loop.runtime_for_session) + schedule.assert_not_called() + + +@pytest.mark.asyncio +async def test_compact_during_active_turn_waits_for_the_session_lock(loop) -> None: + key = "websocket:test" + msg = InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/COMPACT@nanobot", + ) + lock = loop._get_session_lock(key) + async with lock: + await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch) + tasks = list(loop._active_tasks[key]) + assert len(tasks) == 1 + await asyncio.sleep(0) + assert not tasks[0].done() + assert loop.bus.outbound_size == 0 + session = loop.sessions.get_or_create(key) + session.add_message("user", "active turn question") + session.add_message("assistant", "active turn answer") + loop.sessions.save(session) + + await asyncio.wait_for(asyncio.gather(*tasks), timeout=5) + assert loop.bus.outbound_size == 2 + assert loop.sessions.get_or_create(key).last_archived == 2 + loop.provider.chat_with_retry.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loop) -> None: + key = "websocket:test" + msg = InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/compact", + metadata={"webui_turn_id": "queued-compact"}, + ) + completions = [] + loop.runtime_events.subscribe(completions.append, TurnCompleted) + async with loop._get_session_lock(key): + await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch) + reply = await cmd_stop(CommandContext( + msg=msg, session=None, key=key, raw="/stop", loop=loop, + )) + assert reply.content == "Stopped 1 task(s)." + assert len(completions) == 1 + assert completions[0].context.metadata["webui_turn_id"] == "queued-compact" + + +@pytest.mark.asyncio +async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None: + key = "websocket:test" + session = loop.sessions.get_or_create(key) + session.add_message("user", "important question") + session.add_message("assistant", "important answer") + loop.sessions.save(session) + entered = asyncio.Event() + + async def wait_for_cancel(**_kwargs): + entered.set() + await asyncio.Event().wait() + + loop.provider.chat_with_retry.side_effect = wait_for_cancel + completions = [] + loop.runtime_events.subscribe(completions.append, TurnCompleted) + msg = InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/compact", + metadata={"webui_turn_id": "compact-turn"}, + ) + task = asyncio.create_task(loop._dispatch(msg)) + loop._track_active_task(key, task) + await asyncio.wait_for(entered.wait(), timeout=5) + + reply = await cmd_stop(CommandContext( + msg=msg, session=session, key=key, raw="/stop", loop=loop, + )) + + assert reply.content == "Stopped 1 task(s)." + assert task.cancelled() + assert len(completions) == 1 + assert completions[0].context.metadata["webui_turn_id"] == "compact-turn" + events = [loop.bus.outbound.get_nowait().event for _ in range(loop.bus.outbound_size)] + assert all(isinstance(event, ContextCompactionEvent) for event in events) + assert [event.phase for event in events] == ["started", "cancelled"] + assert events[0].compaction_id == events[1].compaction_id + loop.sessions.invalidate(key) + reloaded = loop.sessions.get_or_create(key) + assert reloaded.messages == session.messages + assert reloaded.last_archived == 0 diff --git a/tests/webui/test_context_compaction.py b/tests/webui/test_context_compaction.py new file mode 100644 index 000000000..aca8ca7ee --- /dev/null +++ b/tests/webui/test_context_compaction.py @@ -0,0 +1,54 @@ +"""WebUI replay behavior for structured context-compaction events.""" + +import pytest + +from nanobot.webui.transcript import replay_transcript_to_ui_messages + + +@pytest.mark.parametrize("phase", ["succeeded", "cancelled"]) +def test_replay_folds_compaction_lifecycle_into_one_stable_message(phase) -> None: + messages = replay_transcript_to_ui_messages([ + { + "event": "context_compaction", + "compaction_id": "compact-1", + "phase": "started", + "created_at_ms": 1_700_000_000_000, + }, + { + "event": "context_compaction", + "compaction_id": "compact-1", + "phase": phase, + "created_at_ms": 1_700_000_001_000, + }, + ]) + + assert messages == [{ + "id": "compaction-compact-1", + "role": "assistant", + "content": "", + "kind": "compaction", + "createdAt": 1_700_000_000_000, + "turnPhase": "activity", + "compaction": { + "id": "compact-1", + "phase": phase, + }, + }] + + +def test_replay_keeps_distinct_compactions_in_one_turn() -> None: + messages = replay_transcript_to_ui_messages([ + { + "event": "context_compaction", + "compaction_id": compaction_id, + "phase": phase, + } + for compaction_id in ("compact-1", "compact-2") + for phase in ("started", "succeeded") + ]) + + assert [message["id"] for message in messages] == [ + "compaction-compact-1", + "compaction-compact-2", + ] + assert all(message["compaction"]["phase"] == "succeeded" for message in messages) diff --git a/tests/webui/test_outbound_wire.py b/tests/webui/test_outbound_wire.py index 76b5b674b..72c04da87 100644 --- a/tests/webui/test_outbound_wire.py +++ b/tests/webui/test_outbound_wire.py @@ -1,9 +1,34 @@ from __future__ import annotations -from nanobot.bus.outbound_events import RecoveryStateEvent, TurnEndEvent +from nanobot.bus.outbound_events import ( + ContextCompactionEvent, + RecoveryStateEvent, + TurnEndEvent, +) from nanobot.providers.base import LLMUsage from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY -from nanobot.webui.outbound_wire import encode_recovery_state, encode_turn_end +from nanobot.webui.outbound_wire import ( + encode_context_compaction, + encode_recovery_state, + encode_turn_end, +) + + +def test_encode_context_compaction_projects_the_lifecycle() -> None: + payload = encode_context_compaction( + "chat-1", + ContextCompactionEvent( + compaction_id="compact-1", + phase="succeeded", + ), + ) + + assert payload == { + "event": "context_compaction", + "chat_id": "chat-1", + "compaction_id": "compact-1", + "phase": "succeeded", + } def test_encode_recovery_state_omits_absent_optional_fields() -> None: diff --git a/tui/src/app.test.ts b/tui/src/app.test.ts index 87e7b3dce..a9ebd0c01 100644 --- a/tui/src/app.test.ts +++ b/tui/src/app.test.ts @@ -2878,6 +2878,136 @@ describe("NanobotTui layout", () => { expect(ui.status.plainText).not.toContain("attempt") }) + test.each([ + ["succeeded", "Conversation compacted"], + ["cancelled", "Conversation compaction cancelled"], + ] as const)("updates idle compaction in place to %s", async (phase, copy) => { + setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" }) + const app = mount(setup) + const ui = app as unknown as { + activeTurn: boolean + transcript: Transcript + composer: TextareaRenderable + } + ui.composer.setText("unfinished draft") + const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const + app.accept({ ...event, phase: "started" }) + await setup.renderOnce() + expect(setup.captureCharFrame()).toContain("Compacting conversation…") + const rows = ui.transcript.root.getChildren() + app.accept({ ...event, phase }) + app.accept({ ...event, phase }) + app.accept({ ...event, phase: "started" }) + app.accept({ ...event, chat_id: "another-chat", compaction_id: "other", phase: "failed" }) + await setup.renderOnce() + const frame = setup.captureCharFrame() + expect(occurrences(frame, copy)).toBe(1) + expect(frame).not.toContain("Compacting conversation") + expect(frame).not.toContain("Could not compact") + expect(ui.transcript.root.getChildren()).toEqual(rows) + expect(ui.activeTurn).toBe(false) + expect(ui.composer.plainText).toBe("unfinished draft") + }) + + test("keeps compaction separate from progress and streamed answers", async () => { + setup = await createRenderer({ width: 80, height: 30, screenMode: "alternate-screen" }) + const app = mount(setup) + app.accept({ event: "delta", chat_id: "chat", text: "Answer before " }) + app.accept({ event: "message", chat_id: "chat", text: "First step", kind: "progress" }) + const event = { event: "context_compaction", chat_id: "chat", compaction_id: "capacity" } as const + app.accept({ ...event, phase: "started" }) + app.accept({ event: "message", chat_id: "chat", text: "Second step", kind: "progress" }) + app.accept({ ...event, phase: "succeeded" }) + app.accept({ event: "delta", chat_id: "chat", text: "and after compaction" }) + expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true) + app.accept({ event: "stream_end", chat_id: "chat" }) + app.accept({ event: "turn_end", chat_id: "chat" }) + await setup.flush() + const frame = setup.captureCharFrame() + expect(frame).toContain("Answer before and after compaction") + expect(frame.indexOf("First step")).toBeLessThan(frame.indexOf("Conversation compacted")) + expect(frame.indexOf("Conversation compacted")).toBeLessThan(frame.indexOf("Second step")) + expect(occurrences(frame, "Conversation compacted")).toBe(1) + }) + + test("preserves compaction rows through pagination, theming, and session reset", async () => { + setup = await createRenderer({ width: 80, height: 28, screenMode: "alternate-screen" }) + const app = mount(setup) + const ui = app as unknown as { + transcript: Transcript + palette: { error: string } + } + ui.transcript.history([ + { role: "activity", content: "", compaction: { id: "recent", phase: "succeeded" } }, + { role: "assistant", content: "Recent answer" }, + ]) + await setup.flush() + await ui.transcript.prependHistory([ + { role: "assistant", content: "Earlier answer" }, + { role: "activity", content: "", compaction: { id: "older", phase: "failed" } }, + { role: "activity", content: "", compaction: { id: "recent", phase: "started" } }, + ]) + await setup.flush() + ui.transcript.scrollToEdge("top") + await setup.renderOnce() + const frame = setup.captureCharFrame() + expect(occurrences(frame, "Conversation compacted")).toBe(1) + expect(frame).not.toContain("Compacting conversation") + expect(frame).toContain("Earlier answer") + expect(frame.indexOf("Earlier answer")).toBeLessThan(frame.indexOf("Could not compact conversation")) + expect(frame).toContain("Recent answer") + expect(frame.indexOf("Could not compact conversation")).toBeLessThan(frame.indexOf("Recent answer")) + setup.renderer.emit(CliRenderEvents.THEME_MODE, "light") + await setup.flush() + const failure = ui.transcript.root.getChildren() + .flatMap((row) => row.getChildren()) + .find((child) => child instanceof TextRenderable && child.plainText.includes("Could not compact")) + expect(failure).toBeInstanceOf(TextRenderable) + expect((failure as TextRenderable).fg.toInts().slice(0, 3)).toEqual([ + 1, 3, 5, + ].map((offset) => Number.parseInt(ui.palette.error.slice(offset, offset + 2), 16))) + ui.transcript.reset({ model: "model", workspace: "workspace", version: "test", access: "workspace" }) + app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "recent", phase: "started" }) + await setup.renderOnce() + expect(setup.captureCharFrame()).toContain("Compacting conversation…") + expect(setup.captureCharFrame()).not.toContain("Conversation compacted") + }) + + test("deduplicates compaction history against events queued during hydration", async () => { + setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" }) + const original = globalThis.fetch + let resolveFetch: (value: Response) => void = () => undefined + globalThis.fetch = (() => new Promise((resolve) => { + resolveFetch = resolve + })) as unknown as typeof fetch + const app = NanobotTui.mount( + setup.renderer, + { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" }, + client(), + new MockTreeSitterClient({ autoResolveTimeout: 0 }), + ) + try { + app.accept({ event: "attached", chat_id: "chat" }) + const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const + app.accept({ ...event, phase: "started" }) + app.accept({ ...event, phase: "succeeded" }) + resolveFetch(Response.json({ + messages: [{ + role: "assistant", kind: "compaction", content: "", + compaction: { id: "idle", phase: "succeeded" }, + }], + })) + await waitUntil(() => (app as unknown as { ready: boolean }).ready) + await setup.renderOnce() + const frame = setup.captureCharFrame() + expect(occurrences(frame, "Conversation compacted")).toBe(1) + expect(frame).not.toContain("Compacting conversation") + expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false) + } finally { + globalThis.fetch = original + } + }) + test("replays events after asynchronous history hydration", async () => { setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" }) const original = globalThis.fetch diff --git a/tui/src/app.ts b/tui/src/app.ts index facf5d07a..bb7fc2c5f 100644 --- a/tui/src/app.ts +++ b/tui/src/app.ts @@ -1063,6 +1063,9 @@ export class NanobotTui { } switch (event.event) { + case "context_compaction": + this.transcript.compaction({ id: event.compaction_id, phase: event.phase }) + return case "message_accepted": this.reconcileTurnOwnership(event) return diff --git a/tui/src/protocol.test.ts b/tui/src/protocol.test.ts index 571ff0501..00a8952df 100644 --- a/tui/src/protocol.test.ts +++ b/tui/src/protocol.test.ts @@ -706,6 +706,54 @@ describe("gateway protocol", () => { } }) + test("receives compaction phases and rejects malformed compaction events", () => { + const original = globalThis.WebSocket + let socket: FakeSocket | undefined + Object.defineProperty(globalThis, "WebSocket", { + configurable: true, + value: class extends FakeSocket { + constructor() { + super() + socket = this + } + }, + }) + const events: InboundEvent[] = [] + const statuses: string[] = [] + const client = new NanobotClient({ + url: "ws://nanobot.test/ws", + onEvent: (event) => events.push(event), + onStatus: (status, detail) => statuses.push(`${status}:${detail || ""}`), + }) + try { + client.connect() + if (!socket) throw new Error("socket was not created") + const base = { event: "context_compaction", chat_id: "chat", compaction_id: "compact-1" } + for (const phase of ["started", "succeeded", "failed", "cancelled"]) { + socket.emit("message", { data: JSON.stringify({ + ...base, phase, + }) }) + } + for (const invalid of [ + { phase: "unknown" }, + { phase: "started", compaction_id: "" }, + { phase: "started", compaction_id: 42 }, + { phase: "started", compaction_id: undefined }, + { phase: "started", chat_id: undefined }, + ]) { + socket.emit("message", { data: JSON.stringify({ ...base, ...invalid }) }) + } + expect(events.map((event) => event.event)).toEqual(Array(4).fill("context_compaction")) + expect(events.map((event) => "phase" in event ? event.phase : null)).toEqual([ + "started", "succeeded", "failed", "cancelled", + ]) + expect(statuses.filter((status) => status.includes("invalid event"))).toHaveLength(5) + } finally { + client.close() + Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original }) + } + }) + test("validates nested unified diff payloads at the websocket boundary", () => { const original = globalThis.WebSocket let socket: FakeSocket | undefined @@ -927,6 +975,43 @@ describe("gateway protocol", () => { } }) + test("loads compaction history as activity rows", async () => { + const original = globalThis.fetch + globalThis.fetch = Object.assign(async () => Response.json({ + messages: [ + { role: "assistant", content: "before" }, + ...["started", "succeeded", "failed", "cancelled"].map((phase) => ({ + role: "assistant", + kind: "compaction", + content: "", + compaction: { id: phase, phase }, + })), + { role: "assistant", kind: "compaction", content: "invalid", compaction: null }, + { + role: "assistant", kind: "compaction", content: "invalid", + compaction: { id: "", phase: "succeeded" }, + }, + { + role: "assistant", kind: "compaction", content: "invalid", + compaction: { id: "unknown", phase: "unknown" }, + }, + { role: "assistant", content: "after" }, + ], + }), { preconnect: original.preconnect }) + try { + const history = await fetchHistory("http://nanobot.test", "token", "chat") + expect(history.messages).toEqual([ + { role: "assistant", content: "before", forkIndex: 0 }, + ...(["started", "succeeded", "failed", "cancelled"] as const).map((phase) => ({ + role: "activity" as const, content: "", compaction: { id: phase, phase }, + })), + { role: "assistant", content: "after", forkIndex: 0 }, + ]) + } finally { + globalThis.fetch = original + } + }) + test("loads the explainable session context projection", async () => { const original = globalThis.fetch globalThis.fetch = (() => Promise.resolve(new Response(JSON.stringify({ diff --git a/tui/src/protocol.ts b/tui/src/protocol.ts index a9d867104..0724726d3 100644 --- a/tui/src/protocol.ts +++ b/tui/src/protocol.ts @@ -86,6 +86,11 @@ export interface RecoveryState { can_continue?: boolean } +export interface ContextCompaction { + id: string + phase: "started" | "succeeded" | "failed" | "cancelled" +} + export type InboundEvent = | { event: "ready"; chat_id: string; client_id: string } | { @@ -152,6 +157,12 @@ export type InboundEvent = } | { event: "goal_state"; chat_id: string; goal_state: Record } | ({ event: "recovery_state"; chat_id: string } & RecoveryState) + | { + event: "context_compaction" + chat_id: string + compaction_id: string + phase: ContextCompaction["phase"] + } | { event: "session_updated" chat_id: string @@ -234,6 +245,7 @@ export interface HistoryMessage { media?: MediaAttachment[] toolEvents?: ToolProgressEvent[] fileEdits?: FileEditEvent[] + compaction?: ContextCompaction forkIndex?: number } @@ -356,6 +368,7 @@ const CHAT_EVENTS = new Set([ "goal_status", "goal_state", "recovery_state", + "context_compaction", "session_updated", "turn_model_updated", "error", @@ -369,6 +382,10 @@ function optional(value: unknown, type: "boolean" | "number" | "string"): boolea return value === undefined || typeof value === type } +function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] { + return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled" +} + function isToolEvent(value: unknown): value is ToolProgressEvent { if (!isRecord(value)) return false return optional(value.version, "number") @@ -544,6 +561,12 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined { if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null if (name === "goal_state" && !isRecord(record.goal_state)) return null if (name === "recovery_state" && !isRecoveryState(record)) return null + if ( + name === "context_compaction" + && (typeof record.compaction_id !== "string" + || !record.compaction_id + || !isCompactionPhase(record.phase)) + ) return null if ( name === "session_updated" && (!optional(record.scope, "string") @@ -608,6 +631,20 @@ export async function fetchHistory( for (const message of payload.messages || []) { const role = message.role const content = message.content + if (message.kind === "compaction") { + const compaction = message.compaction + if (isRecord(compaction) + && typeof compaction.id === "string" + && compaction.id + && isCompactionPhase(compaction.phase)) { + messages.push({ + role: "activity", + content: "", + compaction: { id: compaction.id, phase: compaction.phase }, + }) + } + continue + } if (role === "tool" && message.kind === "trace") { const traces = Array.isArray(message.traces) ? message.traces.filter((value): value is string => typeof value === "string") diff --git a/tui/src/transcript.ts b/tui/src/transcript.ts index ff3dd1de8..026f137eb 100644 --- a/tui/src/transcript.ts +++ b/tui/src/transcript.ts @@ -14,6 +14,7 @@ import { } from "@opentui/core" import type { + ContextCompaction, FileEditEvent, HistoryMessage, MediaAttachment, @@ -126,6 +127,10 @@ export class Transcript { }> = [] private readonly markdown = new Set() private readonly activities = new Set() + private readonly compactions = new Map() private readonly frames = new Set() private readonly userRows = new Set() private readonly userMessages = new Set<{ @@ -181,6 +186,9 @@ export class Transcript { this.theme = theme this.codeRailColor = RGBA.fromHex(theme.border) for (const { renderable, tone } of this.styledText) renderable.fg = theme[tone] + for (const { text, phase } of this.compactions.values()) { + text.fg = phase === "failed" ? theme.error : theme.muted + } for (const message of this.userMessages) { message.renderable.content = this.userMessageContent( message.content, @@ -243,6 +251,7 @@ export class Transcript { this.styledText.length = 0 this.markdown.clear() this.activities.clear() + this.compactions.clear() this.frames.clear() this.userRows.clear() this.userMessages.clear() @@ -257,7 +266,8 @@ export class Transcript { history(messages: HistoryMessage[]): void { for (const message of messages) { - if (message.role === "user") { + if (message.compaction) this.compaction(message.compaction) + else if (message.role === "user") { this.user(message.content, message.turnId, message.media) } else if (message.role === "assistant") this.assistant(message.content) @@ -273,7 +283,9 @@ export class Transcript { const previousHeight = this.root.scrollHeight let index = 1 // Keep the launch header first. for (const message of messages) { - if (message.role === "user") { + if (message.compaction) { + if (this.compaction(message.compaction, index)) index += 1 + } else if (message.role === "user") { if (message.turnId && this.userTurnIds.has(message.turnId)) continue this.writeUser(message.content, message.media, index++) if (message.turnId) this.userTurnIds.add(message.turnId) @@ -328,6 +340,36 @@ export class Transcript { this.writeRole(error ? "×" : "·", content, error ? "error" : "muted") } + compaction(compaction: ContextCompaction, index?: number): boolean { + let entry = this.compactions.get(compaction.id) + // Hydration can replay a terminal state before an already queued start event. + if (entry && (entry.phase !== "started" || entry.phase === compaction.phase)) return false + const added = !entry + if (index === undefined) { + this.noteOutput() + if (added) this.finishActivity() + } + if (!entry) { + const row = this.createRow("compaction") + const text = this.createText("", "muted", false, "compaction-status") + row.add(text) + this.root.add(row, index) + this.wrote = true + entry = { phase: compaction.phase, text } + this.compactions.set(compaction.id, entry) + } + entry.phase = compaction.phase + entry.text.content = compaction.phase === "started" + ? " ≋ Compacting conversation…" + : compaction.phase === "succeeded" + ? " ✓ Conversation compacted" + : compaction.phase === "cancelled" + ? " · Conversation compaction cancelled" + : " × Could not compact conversation" + entry.text.fg = compaction.phase === "failed" ? this.theme.error : this.theme.muted + return added + } + stream(delta: string): void { if (!delta) return this.noteOutput() @@ -416,6 +458,7 @@ export class Transcript { this.pendingStream = "" this.live = null this.activity = null + this.compactions.clear() this.frames.clear() this.userRows.clear() this.userMessages.clear() diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 18e0a74cd..6f10cfe5a 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -25,6 +25,7 @@ import { ImageLightbox } from "@/components/ImageLightbox"; import { MarkdownText } from "@/components/MarkdownText"; import { SlashCommandText } from "@/components/SlashCommandText"; import { ReasoningRow } from "@/components/thread/activity/ReasoningRow"; +import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice"; import { UserMessageText } from "@/components/UserMessageText"; import { Tooltip, @@ -343,6 +344,10 @@ export function MessageBubble({ [mcpPresets, message.mcpPresets], ); + if (message.kind === "compaction" && message.compaction) { + return ; + } + if (message.kind === "trace") { return ; } @@ -440,7 +445,12 @@ export function MessageBubble({ ); } - const empty = message.content.trim().length === 0; + const assistantContent = message.compactReply === "empty" + ? t("thread.compaction.empty") + : message.compactReply === "failed" + ? t("thread.compaction.failed") + : message.content; + const empty = assistantContent.trim().length === 0; const media = message.media ?? []; const reasoning = message.role === "assistant" ? message.reasoning ?? "" : ""; const reasoningStreaming = !!(message.role === "assistant" && message.reasoningStreaming); @@ -507,7 +517,7 @@ export function MessageBubble({ preserveStreamingLayout onOpenFilePreview={onOpenFilePreview} > - {message.content} + {assistantContent} {media.length > 0 ? : null} @@ -528,7 +538,7 @@ export function MessageBubble({ )} > {showCopyButton ? ( - + ) : null} {showForkButton ? ( diff --git a/webui/src/components/thread/ContextCompactionNotice.tsx b/webui/src/components/thread/ContextCompactionNotice.tsx new file mode 100644 index 000000000..4fbfafc15 --- /dev/null +++ b/webui/src/components/thread/ContextCompactionNotice.tsx @@ -0,0 +1,51 @@ +import { Archive, CircleAlert, LoaderCircle } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { cn } from "@/lib/utils"; +import type { UIContextCompaction } from "@/lib/types"; + +interface ContextCompactionNoticeProps { + compaction: UIContextCompaction; +} + +export function ContextCompactionNotice({ compaction }: ContextCompactionNoticeProps) { + const { t } = useTranslation(); + const title = compaction.phase === "started" + ? t("thread.compaction.started", { defaultValue: "Compressing context…" }) + : compaction.phase === "failed" + ? t("thread.compaction.failed", { defaultValue: "Context compaction failed" }) + : compaction.phase === "cancelled" + ? t("thread.compaction.cancelled", { defaultValue: "Context compaction cancelled" }) + : t("thread.compaction.succeeded", { defaultValue: "Context compacted" }); + const Icon = compaction.phase === "started" + ? LoaderCircle + : compaction.phase === "failed" + ? CircleAlert + : Archive; + + return ( +
+ + + +

{title}

+
+ ); +} diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx index 6541390fd..ea47cb651 100644 --- a/webui/src/components/thread/ThreadComposer.tsx +++ b/webui/src/components/thread/ThreadComposer.tsx @@ -21,6 +21,7 @@ import { import { INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight"; import { Activity, + Archive, ArrowUp, BookOpen, Brain, @@ -235,6 +236,7 @@ interface ThreadComposerProps { const COMMAND_ICONS: Record = { activity: Activity, + archive: Archive, "book-open": BookOpen, brain: Brain, "circle-help": CircleHelp, diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx index 0e286d47f..3e43b7ffb 100644 --- a/webui/src/components/thread/ThreadMessages.tsx +++ b/webui/src/components/thread/ThreadMessages.tsx @@ -39,6 +39,16 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] { hasLaterUnitBeforeUser = false; continue; } + if ( + unit.type === "message" + && unit.message.role === "assistant" + && unit.message.kind === "compaction" + ) { + // Compaction notices are session lifecycle markers, not assistant answers. + // They must neither expose nor displace the answer-level fork action. + flags[i] = false; + continue; + } if (unit.type === "message" && unit.message.role === "assistant") { flags[i] = !hasLaterUnitBeforeUser; } diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 83bc6856d..d7a44357b 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -771,6 +771,35 @@ export function useNanobotStream( return; } const sideChannelEvent = isSideChannelEvent(ev); + if (ev.event === "context_compaction") { + flushPendingStreamEvents({ closeAnswerSegment: true }); + clearActivitySegment(); + const compaction = { + id: ev.compaction_id, + phase: ev.phase, + announce: true, + }; + setMessages((prev) => { + const id = `compaction-${ev.compaction_id}`; + const existing = prev.findIndex((message) => message.id === id); + const next = { + id, + role: "assistant" as const, + content: "", + kind: "compaction" as const, + createdAt: Date.now(), + compaction, + ...turnFieldsFromEvent(ev, "activity"), + }; + if (existing < 0) return [...prev, next]; + return prev.map((message, index) => ( + index === existing + ? { ...next, createdAt: message.createdAt } + : message + )); + }); + return; + } if (ev.event === "delta") { if (suppressStreamUntilTurnEndRef.current) return; const chunk = typeof ev.text === "string" ? ev.text : ""; @@ -854,6 +883,7 @@ export function useNanobotStream( } if (ev.event === "turn_end") { + if (typeof ev.turn_id === "string") sideChannelTurnIdsRef.current.delete(ev.turn_id); if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") { setGoalState(ev.goal_state); } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 4bb51e35c..c3b598d4b 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1083,6 +1083,13 @@ "error": "Connection error" }, "thread": { + "compaction": { + "cancelled": "Context compaction cancelled", + "empty": "Nothing to compact.", + "started": "Compressing context…", + "failed": "Context compaction failed", + "succeeded": "Context compacted" + }, "loadingConversation": "Loading conversation…", "empty": { "greetings": { @@ -1277,6 +1284,10 @@ "title": "New chat", "description": "Reset this chat and start a fresh conversation." }, + "compact": { + "title": "Compact context", + "description": "Compact this chat's context and continue the conversation." + }, "stop": { "title": "Stop current task", "description": "Cancel the active agent turn for this chat." diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index d9fce3880..1c6f5f9b3 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -1070,6 +1070,13 @@ "error": "Error de conexión" }, "thread": { + "compaction": { + "cancelled": "Compresión de contexto cancelada", + "empty": "No hay contexto que comprimir.", + "started": "Comprimiendo el contexto…", + "failed": "La compresión del contexto falló", + "succeeded": "Contexto comprimido" + }, "loadingConversation": "Cargando conversación…", "empty": { "greetings": { @@ -1254,6 +1261,10 @@ "title": "Nuevo chat", "description": "Restablece este chat e inicia una conversación nueva." }, + "compact": { + "title": "Compactar contexto", + "description": "Compacta el contexto de este chat y continúa la conversación." + }, "stop": { "title": "Detener tarea actual", "description": "Cancela el turno activo del agente en este chat." diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 73d63aa8d..bcba5654f 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -1069,6 +1069,13 @@ "error": "Erreur de connexion" }, "thread": { + "compaction": { + "cancelled": "Compression du contexte annulée", + "empty": "Aucun contexte à compresser.", + "started": "Compression du contexte…", + "failed": "Échec de la compression du contexte", + "succeeded": "Contexte compressé" + }, "loadingConversation": "Chargement de la conversation…", "empty": { "greetings": { @@ -1253,6 +1260,10 @@ "title": "Nouvelle discussion", "description": "Réinitialiser cette discussion et démarrer une nouvelle conversation." }, + "compact": { + "title": "Compacter le contexte", + "description": "Compacter le contexte de cette discussion et poursuivre la conversation." + }, "stop": { "title": "Arrêter la tâche en cours", "description": "Annuler le tour actif de l’agent pour cette discussion." diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index ab13fb0d6..2e96dfc33 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -1069,6 +1069,13 @@ "error": "Kesalahan koneksi" }, "thread": { + "compaction": { + "cancelled": "Pemadatan konteks dibatalkan", + "empty": "Tidak ada konteks yang perlu dipadatkan.", + "started": "Memadatkan konteks…", + "failed": "Pemadatan konteks gagal", + "succeeded": "Konteks dipadatkan" + }, "loadingConversation": "Memuat percakapan…", "empty": { "greetings": { @@ -1253,6 +1260,10 @@ "title": "Obrolan baru", "description": "Reset chat ini dan mulai percakapan baru." }, + "compact": { + "title": "Ringkas konteks", + "description": "Ringkas konteks chat ini, lalu lanjutkan percakapan." + }, "stop": { "title": "Hentikan tugas saat ini", "description": "Batalkan giliran agen yang sedang aktif di chat ini." diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 09291c941..094a2166d 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1069,6 +1069,13 @@ "error": "接続エラー" }, "thread": { + "compaction": { + "cancelled": "コンテキストの圧縮をキャンセルしました", + "empty": "圧縮するコンテキストはありません。", + "started": "コンテキストを圧縮中…", + "failed": "コンテキストの圧縮に失敗しました", + "succeeded": "コンテキストを圧縮しました" + }, "loadingConversation": "会話を読み込み中…", "empty": { "greetings": { @@ -1253,6 +1260,10 @@ "title": "新しいチャット", "description": "このチャットをリセットして、新しい会話を開始します。" }, + "compact": { + "title": "コンテキストを圧縮", + "description": "このチャットのコンテキストを圧縮して、会話を続けます。" + }, "stop": { "title": "現在のタスクを停止", "description": "このチャットで実行中のエージェントのターンをキャンセルします。" diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index d5f1681ed..934d15a88 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1069,6 +1069,13 @@ "error": "연결 오류" }, "thread": { + "compaction": { + "cancelled": "컨텍스트 압축이 취소되었습니다", + "empty": "압축할 컨텍스트가 없습니다.", + "started": "컨텍스트 압축 중…", + "failed": "컨텍스트 압축 실패", + "succeeded": "컨텍스트를 압축했습니다" + }, "loadingConversation": "대화 불러오는 중…", "empty": { "greetings": { @@ -1253,6 +1260,10 @@ "title": "새 채팅", "description": "이 채팅을 초기화하고 새 대화를 시작합니다." }, + "compact": { + "title": "컨텍스트 압축", + "description": "이 채팅의 컨텍스트를 압축하고 대화를 계속합니다." + }, "stop": { "title": "현재 작업 중지", "description": "이 채팅에서 실행 중인 에이전트 턴을 취소합니다." diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 8e5b970ae..52a81ea77 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1083,6 +1083,13 @@ "error": "Erro de conexão" }, "thread": { + "compaction": { + "cancelled": "Compactação do contexto cancelada", + "empty": "Não há contexto para compactar.", + "started": "Compactando contexto…", + "failed": "Falha ao compactar o contexto", + "succeeded": "Contexto compactado" + }, "loadingConversation": "Carregando conversa…", "empty": { "greetings": { @@ -1277,6 +1284,10 @@ "title": "Nova conversa", "description": "Reinicia esta conversa e inicia uma conversa nova." }, + "compact": { + "title": "Compactar contexto", + "description": "Compacte o contexto desta conversa e continue conversando." + }, "stop": { "title": "Parar tarefa atual", "description": "Cancela o turno ativo do agente nesta conversa." diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index d305dcb57..63a88a6d9 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -1069,6 +1069,13 @@ "error": "Lỗi kết nối" }, "thread": { + "compaction": { + "cancelled": "Đã hủy nén ngữ cảnh", + "empty": "Không có ngữ cảnh cần nén.", + "started": "Đang nén ngữ cảnh…", + "failed": "Nén ngữ cảnh không thành công", + "succeeded": "Đã nén ngữ cảnh" + }, "loadingConversation": "Đang tải cuộc trò chuyện…", "empty": { "greetings": { @@ -1253,6 +1260,10 @@ "title": "Cuộc trò chuyện mới", "description": "Đặt lại cuộc trò chuyện này và bắt đầu một cuộc trò chuyện mới." }, + "compact": { + "title": "Nén ngữ cảnh", + "description": "Nén ngữ cảnh của cuộc trò chuyện này và tiếp tục hội thoại." + }, "stop": { "title": "Dừng tác vụ hiện tại", "description": "Hủy lượt của tác nhân đang chạy trong cuộc trò chuyện này." diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index cf443e047..30cfaf8b0 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1083,6 +1083,13 @@ "error": "连接出错" }, "thread": { + "compaction": { + "cancelled": "上下文压缩已取消", + "empty": "无需压缩上下文", + "started": "正在压缩上下文…", + "failed": "上下文压缩失败", + "succeeded": "上下文已压缩" + }, "loadingConversation": "正在加载话题…", "empty": { "greetings": { @@ -1276,6 +1283,10 @@ "title": "新建话题", "description": "重置当前话题,并开始一个新的话题。" }, + "compact": { + "title": "压缩上下文", + "description": "压缩当前对话的上下文并继续对话。" + }, "stop": { "title": "停止当前任务", "description": "取消这个对话中正在运行的智能体回合。" diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 20b8ffb2a..e4d7ac358 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1069,6 +1069,13 @@ "error": "連線錯誤" }, "thread": { + "compaction": { + "cancelled": "上下文壓縮已取消", + "empty": "無需壓縮上下文", + "started": "正在壓縮上下文…", + "failed": "上下文壓縮失敗", + "succeeded": "上下文已壓縮" + }, "loadingConversation": "正在載入話題…", "empty": { "greetings": { @@ -1253,6 +1260,10 @@ "title": "新增話題", "description": "重置目前話題,並開始新的話題。" }, + "compact": { + "title": "壓縮上下文", + "description": "壓縮目前對話的上下文並繼續對話。" + }, "stop": { "title": "停止目前任務", "description": "取消這個對話中正在執行的智能體回合。" diff --git a/webui/src/lib/activity-timeline.ts b/webui/src/lib/activity-timeline.ts index 86a8f7cad..aa03c6fd0 100644 --- a/webui/src/lib/activity-timeline.ts +++ b/webui/src/lib/activity-timeline.ts @@ -175,6 +175,16 @@ function projectOrderedTurn( }; for (const message of messages) { + if (message.kind === "compaction") { + flushActivity(); + flushAnswers(); + units.push({ + type: "message", + message, + sourceMessageCount: 1 + claimLeadingNoops(), + }); + continue; + } if (isCompletedDisplayNoop(message)) { absorbDisplayNoop(); continue; diff --git a/webui/src/lib/thread-display-compat.ts b/webui/src/lib/thread-display-compat.ts index 39933fa84..0bb69041c 100644 --- a/webui/src/lib/thread-display-compat.ts +++ b/webui/src/lib/thread-display-compat.ts @@ -62,6 +62,23 @@ function deriveAssistantCompletionTimes(messages: UIMessage[]): UIMessage[] { }); } +function identifyCompactReplies(messages: UIMessage[]): UIMessage[] { + const turns = new Set(messages.flatMap((message) => ( + message.role === "user" && message.content.trim().toLowerCase() === "/compact" && message.turnId + ? [message.turnId] + : [] + ))); + return messages.map((message) => { + if (message.role !== "assistant" || message.kind || message.isStreaming + || !message.turnId || !turns.has(message.turnId)) return message; + if (message.content === "Nothing to compact.") return { ...message, compactReply: "empty" }; + if (message.content === "Unable to compact context. Check the logs and try again.") { + return { ...message, compactReply: "failed" }; + } + return message; + }); +} + export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] { const normalized = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages(messages)); const hiddenTurns = new Set(normalized.flatMap((message) => ( @@ -75,5 +92,5 @@ export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] { && !(message.role === "user" && isModelCommandText(message.content)) && !(message.role === "assistant" && isModelCommandResponseText(message.content)) )); - return deriveAssistantCompletionTimes(visible); + return deriveAssistantCompletionTimes(identifyCompactReplies(visible)); } diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 481f696a2..e9aee6c87 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -2,7 +2,14 @@ type Role = "user" | "assistant" | "tool" | "system"; /** "trace" rows are intermediate agent breadcrumbs (tool-call hints, * progress pings) that should not be rendered as conversational replies. */ -type MessageKind = "message" | "trace"; +type MessageKind = "message" | "trace" | "compaction"; + +export interface UIContextCompaction { + id: string; + phase: "started" | "succeeded" | "failed" | "cancelled"; + /** Live wire transitions announce; hydrated transcript rows stay silent. */ + announce?: boolean; +} export type UITurnPhase = "user" | "reasoning" | "activity" | "answer" | "complete"; export type MessageDeliveryStatus = "sending" | "accepted" | "failed"; @@ -86,6 +93,10 @@ export interface UIMessage { /** Internal projection marker for assistant text emitted before a later tool. * It is not a wire message and is rendered as a compact activity row. */ activityKind?: "model"; + /** Context-compaction lifecycle rendered as a standalone channel notice. */ + compaction?: UIContextCompaction; + /** Display-only localization marker for fixed /compact command replies. */ + compactReply?: "empty" | "failed"; /** User turn: optimistic blob URLs for preview. Replay: placeholder chips. */ images?: UIImage[]; /** Signed or local UI-renderable media attachments. */ @@ -1375,6 +1386,12 @@ export type InboundEvent = event: "recovery_state"; chat_id: string; } & RecoveryState) + | ({ + event: "context_compaction"; + chat_id: string; + compaction_id: string; + phase: UIContextCompaction["phase"]; + } & InboundTurnMetadata) | ({ event: "file_edit"; chat_id: string; diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsx index db2b4a6bb..317b2a18f 100644 --- a/webui/src/tests/i18n.test.tsx +++ b/webui/src/tests/i18n.test.tsx @@ -2,13 +2,15 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { runInNewContext } from "node:vm"; -import { act, render, screen, waitFor } from "@testing-library/react"; +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { LanguageSwitcher } from "@/components/LanguageSwitcher"; +import { MessageBubble } from "@/components/MessageBubble"; +import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; -import { resources } from "@/i18n"; +import { resources, setAppLanguage } from "@/i18n"; import { LOCALE_STORAGE_KEY, resolveInitialLocale, @@ -20,6 +22,7 @@ const IMAGE_QUICK_ACTION_KEYS = ["icon", "sticker", "poster", "product", "portra const HERO_GREETING_KEYS = ["workOn", "start", "build", "tackle"]; const SLASH_COMMAND_KEYS = [ "new", + "compact", "stop", "restart", "status", @@ -418,6 +421,30 @@ describe("webui i18n", () => { ); }); + it.each(supportedLocales)("localizes compaction states in $code", async ({ code }) => { + await setAppLanguage(code); + const copy = resources[code].common.thread.compaction; + const { container, rerender } = render( + , + ); + for (const phase of ["started", "succeeded", "failed", "cancelled"] as const) { + rerender(); + const notice = container.querySelector("[data-context-compaction]"); + expect(copy[phase]).toBeTruthy(); + expect(notice?.textContent).toBe(copy[phase]); + expect(notice).toHaveAttribute("aria-busy", String(phase === "started")); + } + for (const compactReply of ["empty", "failed"] as const) { + rerender(); + expect(screen.getByText(copy[compactReply])).toBeInTheDocument(); + } + }); + it("keeps preboot copy aligned with every registered locale", () => { for (const { code } of supportedLocales) { const result = runPrebootLocale(code); @@ -499,6 +526,36 @@ describe("webui i18n", () => { expect(screen.getByLabelText("メッセージ入力欄")).toBeInTheDocument(); }); + it("localizes a backend-provided compact slash command", async () => { + await act(async () => { + const { setAppLanguage } = await import("@/i18n"); + await setAppLanguage("zh-CN"); + }); + + render( + , + ); + + fireEvent.change(screen.getByLabelText("消息输入框"), { + target: { value: "/co" }, + }); + + expect(screen.getByRole("listbox", { name: "斜杠命令" })).toBeInTheDocument(); + expect(screen.getByText("压缩上下文")).toBeInTheDocument(); + expect(screen.getByText("压缩当前对话的上下文并继续对话。")).toBeInTheDocument(); + expect(screen.getByText("/compact")).toBeInTheDocument(); + }); + it("keeps empty landing resources localized for every registered locale", () => { for (const resource of Object.values(resources)) { const empty = resource.common.thread.empty; diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx index 44589a22c..729fe73d0 100644 --- a/webui/src/tests/message-bubble.test.tsx +++ b/webui/src/tests/message-bubble.test.tsx @@ -2,6 +2,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react" import { describe, expect, it, vi } from "vitest"; import { MessageBubble } from "@/components/MessageBubble"; +import { setAppLanguage } from "@/i18n"; import { fmtDateTime, formatMessageEndTime } from "@/lib/format"; import type { CliAppInfo, @@ -95,6 +96,46 @@ const SLASH_COMMANDS: SlashCommand[] = [ ]; describe("MessageBubble", () => { + it("copies the localized compact reply instead of the stored English text", async () => { + await setAppLanguage("zh-CN"); + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + render(); + expect(screen.getByText("无需压缩上下文")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "复制" })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith("无需压缩上下文")); + }); + + it("renders a compacted context notice", () => { + const message: UIMessage = { + id: "compaction-1", + role: "assistant", + content: "", + kind: "compaction", + createdAt: Date.now(), + compaction: { + id: "compact-1", + phase: "succeeded", + announce: true, + }, + }; + + const { container } = render(); + + const notice = container.querySelector("[data-context-compaction='succeeded']"); + expect(notice).toHaveAttribute("role", "status"); + expect(notice).toHaveAttribute("aria-live", "polite"); + expect(screen.getByText("Context compacted")).toBeInTheDocument(); + expect(notice).toHaveTextContent(/^Context compacted$/); + expect(notice?.querySelector(".lucide-archive")).toBeInTheDocument(); + }); + it("renders user messages as right-aligned pills", () => { const message: UIMessage = { id: "u1", diff --git a/webui/src/tests/thread-display-compat.test.ts b/webui/src/tests/thread-display-compat.test.ts index f1b7b1096..086f795a3 100644 --- a/webui/src/tests/thread-display-compat.test.ts +++ b/webui/src/tests/thread-display-compat.test.ts @@ -66,6 +66,26 @@ describe("normalizeLegacyLongTaskMessages", () => { }); describe("projectWebuiThreadMessages", () => { + it("marks only fixed replies belonging to a compact command turn", () => { + const rows = [ + message("user", { content: " /COMPACT ", turnId: "compact" }), + message("assistant", { content: "Nothing to compact.", turnId: "compact" }), + message("assistant", { + content: "Unable to compact context. Check the logs and try again.", turnId: "compact", + }), + message("assistant", { content: "Nothing to compact.", turnId: "unrelated" }), + message("assistant", { content: "Nothing to compact." }), + message("assistant", { content: "Nothing to compact.", turnId: "compact", isStreaming: true }), + message("assistant", { content: "Quoted: Nothing to compact.", turnId: "compact" }), + ]; + const projected = projectWebuiThreadMessages(rows); + expect(projected.map(({ compactReply }) => compactReply)).toEqual([ + undefined, "empty", "failed", undefined, undefined, undefined, undefined, + ]); + expect(projected.map(({ content }) => content)).toEqual(rows.map(({ content }) => content)); + expect(projectWebuiThreadMessages(projected)).toEqual(projected); + }); + it("derives replayed completion time from the matching user turn", () => { const firstOutputAt = STARTED_AT + 5_000; const latencyMs = 13_000; diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsx index fa9a85355..0793769d1 100644 --- a/webui/src/tests/thread-messages.test.tsx +++ b/webui/src/tests/thread-messages.test.tsx @@ -1678,4 +1678,32 @@ describe("ThreadMessages", () => { ["a3", true], ]); }); + + it("keeps compaction notices out of assistant fork selection", () => { + const units = buildDisplayUnits([ + { id: "u1", role: "user", content: "one", createdAt: 1 }, + { id: "a1", role: "assistant", content: "answer", createdAt: 2 }, + { + id: "compaction-1", + role: "assistant", + content: "", + kind: "compaction", + createdAt: 3, + compaction: { + id: "compact-1", + phase: "succeeded", + }, + }, + ]); + + const flags = assistantForkFlags(units); + expect(units.map((unit, index) => [ + unit.type === "message" ? unit.message.id : "activity", + flags[index], + ])).toEqual([ + ["u1", true], + ["a1", true], + ["compaction-1", false], + ]); + }); }); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index c3a2d3931..a9bf860fa 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -197,6 +197,54 @@ async function flushStreamFrame() { } describe("useNanobotStream", () => { + it.each(["succeeded", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => { + const fake = fakeClient(); + const { result } = renderHook( + () => useNanobotStream("chat-compaction", EMPTY_MESSAGES), + { wrapper: wrap(fake.client) }, + ); + + act(() => { + fake.emit("chat-compaction", { + event: "context_compaction", + chat_id: "chat-compaction", + compaction_id: "compact-1", + phase: "started", + }); + }); + + expect(result.current.messages).toHaveLength(1); + const createdAt = result.current.messages[0].createdAt; + expect(result.current.messages[0]).toMatchObject({ + id: "compaction-compact-1", + kind: "compaction", + compaction: { + id: "compact-1", + phase: "started", + announce: true, + }, + }); + + act(() => { + fake.emit("chat-compaction", { + event: "context_compaction", + chat_id: "chat-compaction", + compaction_id: "compact-1", + phase, + }); + }); + + expect(result.current.messages).toHaveLength(1); + expect(result.current.messages[0]).toMatchObject({ + id: "compaction-compact-1", + createdAt, + compaction: { + phase, + announce: true, + }, + }); + }); + it("batches answer deltas into one animation-frame update", async () => { const fake = fakeClient(); const requestFrame = vi.spyOn(window, "requestAnimationFrame");