feat(webui): distinguish context compaction reasons (NAN-324) (#6389)

* feat(webui): distinguish context compaction reasons (NAN-324)

* fix(webui): describe idle compaction cancellation as interruption

* docs: omit compaction notice details from configuration guide

* fix(i18n): make compaction notices read naturally

* fix(i18n): keep CJK compaction notices concise

* fix(i18n): describe idle compaction as unfinished
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 16:13:25 +08:00
1 parent 084b6bb394
commit bc5c58d239
38 files changed
+540 -23

No files matched your search

+33 -1
View File
@@ -17,7 +17,7 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.command import CommandContext
from nanobot.config.schema import AgentDefaults, Config
from nanobot.events import NO_EVENTS
from nanobot.events import NO_EVENTS, ContextCompactionEvent
from nanobot.providers.base import LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.sdk.clients import RuntimeClient
@@ -99,6 +99,7 @@ def _make_fake_compact(
max_suffix: int = 8,
trigger: str = "policy",
events=NO_EVENTS,
reason=None,
) -> str:
state["count"] += 1
session = await loop.sessions.state.get(key)
@@ -150,6 +151,37 @@ async def test_heartbeat_idle_compaction_persists_summary_without_channel_notice
assert loop.bus.outbound.empty()
@pytest.mark.parametrize("outcome", ["succeeded", "failed", "cancelled"])
async def test_idle_compaction_emits_its_real_trigger_for_each_phase(tmp_path, monkeypatch, outcome):
loop = _make_loop(tmp_path)
try:
key = "websocket:idle-reason"
session = await loop.sessions.state.get(key)
_add_turns(session, 1)
await loop.sessions.state.finish_turn(session)
clock = MagicMock(wraps=datetime)
clock.now.return_value = datetime.now() + timedelta(minutes=20)
monkeypatch.setattr("nanobot.agent.autocompact.datetime", clock)
if outcome == "succeeded":
loop.consolidator.archive_session = AsyncMock(return_value="Idle summary.")
else:
error = asyncio.CancelledError() if outcome == "cancelled" else RuntimeError("summary failed")
loop.consolidator.archive_session = AsyncMock(side_effect=error)
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await _drain_background_tasks(loop)
events = [loop.bus.outbound.get_nowait().event for _ in range(loop.bus.outbound_size)]
assert len(events) == 2
assert all(isinstance(event, ContextCompactionEvent) for event in events)
assert [event.phase for event in events] == ["started", outcome]
assert [event.reason for event in events] == ["idle", "idle"]
assert events[0].compaction_id == events[1].compaction_id
assert all(event.notify is False for event in events)
finally:
await loop.aclose()
@pytest.mark.parametrize("reopen", [False, True])
async def test_idle_compaction_skips_subagent_sessions(tmp_path, monkeypatch, reopen):
loop = _make_loop(tmp_path)
+2
View File
@@ -265,6 +265,7 @@ class TestCheckExpired:
"cli:old",
runtime=admitted,
events=NO_EVENTS,
reason="idle",
)
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])
@@ -443,6 +444,7 @@ class TestArchiveDelegates:
"cli:test",
runtime=runtime,
events=NO_EVENTS,
reason="idle",
)
@pytest.mark.asyncio
+3
View File
@@ -402,6 +402,7 @@ async def test_native_compaction_uses_provider_request_boundary(
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] == ([] if scope == "prior_context" else ["succeeded"])
assert all(event.reason == "provider_native" for event in compaction_events)
@pytest.mark.parametrize("error", [RuntimeError("checkpoint failed"), asyncio.CancelledError()])
@@ -439,6 +440,7 @@ async def test_native_checkpoint_failure_does_not_relabel_completed_compaction(m
events=EventSink(observe),
))
assert [notice.phase for notice in notices] == ["succeeded"]
assert all(notice.reason == "provider_native" for notice in notices)
async def test_runner_keeps_current_tool_exchange_outside_summary(monkeypatch):
@@ -576,6 +578,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
assert [event.phase for event in compaction_events] == [
"started", "succeeded", "started", "succeeded",
]
assert all(event.reason == "context_pressure" for event in compaction_events)
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
+2
View File
@@ -130,6 +130,7 @@ async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command)
assert started.phase == "started"
assert completed.phase == "succeeded"
assert started.compaction_id == completed.compaction_id
assert started.reason == completed.reason == "manual"
assert started.notify is True
assert completed.notify is True
@@ -421,6 +422,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop, command) ->
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 [event.reason for event in events] == ["manual", "manual"]
assert events[0].compaction_id == events[1].compaction_id
loop.sessions.invalidate(key)
reloaded = loop.sessions.get_or_create(key)
@@ -1026,6 +1026,7 @@ async def test_codex_compacts_state_at_ninety_percent_before_next_request(
)
assert timeline == ["started", "compact-request", "succeeded", "generation-request", "answer:done"]
assert all(notice.reason == "provider_native" for notice in notices)
assert len({notice.compaction_id for notice in notices}) == 1
assert response.provider_compaction_event_id == (None if inline_compaction else notices[0].compaction_id)
assert response.content == "done"
@@ -1135,6 +1136,7 @@ async def test_codex_disables_unsupported_native_compaction_and_continues(
assert response.content == "done"
assert [notice.phase for notice in notices] == ["started", "failed"]
assert all(notice.reason == "provider_native" for notice in notices)
assert len({notice.compaction_id for notice in notices}) == 1
assert len(bodies) == 2
assert bodies[0]["input"][-1] == {"type": "compaction_trigger"}
@@ -1192,6 +1194,7 @@ async def test_codex_native_compaction_terminal_survives_cancellation(monkeypatc
await task
terminal = "cancelled" if cancel_during == "compaction" else "succeeded"
assert [notice.phase for notice in notices] == ["started", terminal]
assert all(notice.reason == "provider_native" for notice in notices)
assert len({notice.compaction_id for notice in notices}) == 1
assert requests == (["compaction", "generation"] if cancel_during == "generation" else ["compaction"])
+32
View File
@@ -36,6 +36,38 @@ def test_history_preserves_phase_qualified_stream_identity(history, event) -> No
assert segment["turn_seq"] == 2
@pytest.mark.parametrize("reason", [None, "idle", "context_pressure", "manual", "provider_native"])
def test_compaction_reason_survives_sqlite_reload_and_older_page(history, tmp_path, reason) -> None:
from nanobot.session.manager import SessionManager
key = "websocket:compaction-reason"
history.append(key, {"event": "user", "chat_id": "compaction-reason", "text": "first"})
compaction = {
"event": "context_compaction", "chat_id": "compaction-reason",
"compaction_id": "compact-one", "phase": "succeeded",
"turn_id": "turn-one", "turn_seq": 1,
**({"reason": reason} if reason is not None else {}),
}
history.append(key, compaction)
history.append(key, {"event": "turn_end", "chat_id": "compaction-reason"})
_append_numbered_turn(history, key, "compaction-reason", 2)
reopened = SessionManager(tmp_path)
def build(**kwargs):
return reopened.project_history(key, lambda snapshot: transcript_module.build_webui_thread_response(
key, history=snapshot, **kwargs,
))
latest = build(limit=2, direction="latest")
assert latest is not None
older = build(limit=2, before=latest["page"]["before_cursor"])
assert older is not None
[replayed] = [event for event in older["events"] if event["event"] == "context_compaction"]
assert {field: replayed[field] for field in compaction} == compaction
if reason is None:
assert "reason" not in replayed
def test_append_stamps_created_at_ms(history, tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
monkeypatch.setattr("nanobot.webui.transcript.time.time", lambda: 1_700_000_000.0)
+5 -1
View File
@@ -8,6 +8,7 @@ from nanobot.bus.outbound_events import (
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.events import CompactionReason
from nanobot.providers.base import LLMUsage
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
from nanobot.webui.outbound_wire import (
@@ -18,12 +19,14 @@ from nanobot.webui.outbound_wire import (
)
def test_encode_context_compaction_projects_the_lifecycle() -> None:
@pytest.mark.parametrize("reason", [None, "idle", "context_pressure", "manual", "provider_native"])
def test_encode_context_compaction_projects_the_lifecycle(reason: CompactionReason | None) -> None:
payload = encode_context_compaction(
"chat-1",
ContextCompactionEvent(
compaction_id="compact-1",
phase="succeeded",
reason=reason,
),
)
@@ -32,6 +35,7 @@ def test_encode_context_compaction_projects_the_lifecycle() -> None:
"chat_id": "chat-1",
"compaction_id": "compact-1",
"phase": "succeeded",
**({"reason": reason} if reason is not None else {}),
}