diff --git a/nanobot/agent/autocompact.py b/nanobot/agent/autocompact.py index 7ba0a6903..e8b3b795f 100644 --- a/nanobot/agent/autocompact.py +++ b/nanobot/agent/autocompact.py @@ -101,6 +101,7 @@ class AutoCompact: key, runtime=runtime, events=self._bind_events(key) if self._bind_events else NO_EVENTS, + reason="idle", ) if summary: session = await self.sessions.state.get(key) diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index cfb2c7622..79a4297ad 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -533,7 +533,7 @@ class ContextGovernor: if response.provider_compaction_event_id is None: response.provider_compaction_event_id = uuid4().hex await shield_and_drain(state.events.emit(ContextCompactionEvent( - response.provider_compaction_event_id, "succeeded", + response.provider_compaction_event_id, "succeeded", reason="provider_native", ))) if ( not response.provider_compaction_applied @@ -585,7 +585,7 @@ class ContextGovernor: measured, _source = pressure compaction_id = uuid4().hex await state.events.emit( - ContextCompactionEvent(compaction_id=compaction_id, phase="started"), + ContextCompactionEvent(compaction_id=compaction_id, phase="started", reason="context_pressure"), ) try: delta_messages = await self.prepare_in_background( @@ -645,6 +645,7 @@ class ContextGovernor: ContextCompactionEvent( compaction_id=compaction_id, phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", + reason="context_pressure", ), ) raise @@ -652,6 +653,7 @@ class ContextGovernor: ContextCompactionEvent( compaction_id=compaction_id, phase="succeeded", + reason="context_pressure", ), ) return prepared diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.py index 26f0a53cb..a12bf4383 100644 --- a/nanobot/agent/memory.py +++ b/nanobot/agent/memory.py @@ -20,7 +20,7 @@ from uuid import uuid4 from loguru import logger -from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink +from nanobot.events import NO_EVENTS, CompactionReason, ContextCompactionEvent, EventSink from nanobot.llm_usage.context import llm_usage_source from nanobot.providers.base import LLMResponse, ProviderConversationState from nanobot.providers.conversation_state import ProviderConversationStateController @@ -1222,6 +1222,7 @@ class Consolidator: max_suffix: int = 0, events: EventSink = NO_EVENTS, notify: bool = False, + reason: CompactionReason | None = None, ) -> str | None: """Replace archived history with a summary checkpoint. @@ -1244,7 +1245,7 @@ class Consolidator: compaction_id = uuid4().hex await events.emit( - ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify), + ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify, reason=reason), ) archive_end = archive_start + len(messages_to_archive) try: @@ -1261,12 +1262,13 @@ class Consolidator: compaction_id=compaction_id, phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", notify=notify, + reason=reason, ), ) raise if not summary: await events.emit( - ContextCompactionEvent(compaction_id=compaction_id, phase="failed", notify=notify), + ContextCompactionEvent(compaction_id=compaction_id, phase="failed", notify=notify, reason=reason), ) return None @@ -1275,6 +1277,7 @@ class Consolidator: compaction_id=compaction_id, phase="succeeded", notify=notify, + reason=reason, ), ) diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index d5908b0cc..745c91fb0 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -3333,6 +3333,7 @@ async def test_context_compaction_is_structured_persisted_and_summary_free(histo compaction_id="compact-1", phase=phase, notify=notify, + reason="manual", ), )) @@ -3341,6 +3342,7 @@ async def test_context_compaction_is_structured_persisted_and_summary_free(histo "chat_id": "chat-compaction", "compaction_id": "compact-1", "phase": phase, + "reason": "manual", } assert _sent_ws_payloads(mock_ws) == [expected] [persisted] = history.read("websocket:chat-compaction") diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py index 6c096485c..3736ed19b 100644 --- a/nanobot/command/builtin.py +++ b/nanobot/command/builtin.py @@ -361,6 +361,7 @@ async def cmd_compact(ctx: CommandContext) -> None: runtime=runtime, events=delivery.events, notify=True, + reason="manual", ) except Exception: logger.exception("Manual context compaction failed for {}", ctx.key) diff --git a/nanobot/events.py b/nanobot/events.py index 3200a6923..39dfd8d75 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -33,6 +33,9 @@ class ResponseSourceEvent(AgentEvent): content: str | None = None +CompactionReason = Literal["idle", "context_pressure", "manual", "provider_native"] + + @dataclass(frozen=True) class ContextCompactionEvent(AgentEvent): compaction_id: str @@ -40,6 +43,7 @@ class ContextCompactionEvent(AgentEvent): # Request a chat notice (e.g. /compact), not event delivery or persistence. # Interactive clients still consume every phase when this is false. notify: bool = False + reason: CompactionReason | None = None @dataclass(frozen=True) diff --git a/nanobot/providers/openai_codex_provider.py b/nanobot/providers/openai_codex_provider.py index e23632b3e..539bf65de 100644 --- a/nanobot/providers/openai_codex_provider.py +++ b/nanobot/providers/openai_codex_provider.py @@ -369,7 +369,7 @@ class OpenAICodexProvider(LLMProvider): nonlocal native_compaction_event_id compaction_id = uuid4().hex try: - await events.emit(ContextCompactionEvent(compaction_id, "started")) + await events.emit(ContextCompactionEvent(compaction_id, "started", reason="provider_native")) compacted = await _send( request, emit_deltas=False, @@ -380,10 +380,11 @@ class OpenAICodexProvider(LLMProvider): await shield_and_drain(events.emit(ContextCompactionEvent( compaction_id, "cancelled" if isinstance(exc, asyncio.CancelledError) else "failed", + reason="provider_native", ))) raise native_compaction_event_id = compaction_id - await shield_and_drain(events.emit(ContextCompactionEvent(compaction_id, "succeeded"))) + await shield_and_drain(events.emit(ContextCompactionEvent(compaction_id, "succeeded", reason="provider_native"))) return compacted native_compaction_state = await self._responses.compact_before_request( diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py index 5df8bff4b..071d6fd75 100644 --- a/nanobot/webui/history.py +++ b/nanobot/webui/history.py @@ -39,7 +39,7 @@ _CONTENT_FIELDS = frozenset({ "session_message", "tool_events", "edits", "source", "response_sources", "resuming", "merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state", "outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message", - "transcript_incomplete", "stream_id", "compaction_id", "phase", + "transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", }) diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index 577c8bd38..cf89fd1a3 100644 --- a/nanobot/webui/outbound_wire.py +++ b/nanobot/webui/outbound_wire.py @@ -13,7 +13,7 @@ from nanobot.bus.outbound_events import ( RetryStatusEvent, TurnEndEvent, ) -from nanobot.events import AgentEvent +from nanobot.events import AgentEvent, CompactionReason from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY _JSONValue: TypeAlias = ( @@ -102,6 +102,7 @@ class ContextCompactionWirePayload(_ChatWirePayload): event: Literal["context_compaction"] compaction_id: str phase: Literal["started", "succeeded", "failed", "cancelled"] + reason: NotRequired[CompactionReason] class SubagentTaskWirePayload(_ChatWirePayload): @@ -152,6 +153,8 @@ def encode_context_compaction( "compaction_id": event.compaction_id, "phase": event.phase, } + if event.reason is not None: + payload["reason"] = event.reason return payload diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 19df05a5b..88c49e052 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -1487,12 +1487,16 @@ def _client_projection_event( or phase not in {"started", "succeeded", "failed", "cancelled"} ): return None - return { + projected = { "event": "context_compaction", **common, "compaction_id": compaction_id, "phase": phase, } + reason = record.get("reason") + if isinstance(reason, str) and reason in {"idle", "context_pressure", "manual", "provider_native"}: + projected["reason"] = reason + return projected if event == "turn_end": projected = {"event": "turn_end", **common} diff --git a/packages/client-events/fixtures.json b/packages/client-events/fixtures.json index ad31ca789..d8fb4d418 100644 --- a/packages/client-events/fixtures.json +++ b/packages/client-events/fixtures.json @@ -11,5 +11,9 @@ {"event":"retry_status","chat_id":"chat","state":"waiting","attempt":1,"max_attempts":4,"error_kind":"connection","retry_after_s":2}, {"event":"retry_status","chat_id":"chat","state":"recovered","attempt":2,"max_attempts":4,"error_kind":"connection"}, {"event":"retry_status","chat_id":"chat","state":"cleared","attempt":2,"max_attempts":4,"error_kind":"connection"}, - {"event":"retry_status","chat_id":"chat","state":"exhausted","attempt":4,"max_attempts":4,"error_kind":"connection"} + {"event":"retry_status","chat_id":"chat","state":"exhausted","attempt":4,"max_attempts":4,"error_kind":"connection"}, + {"event":"context_compaction","chat_id":"chat","compaction_id":"reason-idle","phase":"succeeded","reason":"idle"}, + {"event":"context_compaction","chat_id":"chat","compaction_id":"reason-context_pressure","phase":"succeeded","reason":"context_pressure"}, + {"event":"context_compaction","chat_id":"chat","compaction_id":"reason-manual","phase":"succeeded","reason":"manual"}, + {"event":"context_compaction","chat_id":"chat","compaction_id":"reason-provider_native","phase":"succeeded","reason":"provider_native"} ] diff --git a/packages/client-events/notifications.ts b/packages/client-events/notifications.ts index d3e59972b..d5312fa6d 100644 --- a/packages/client-events/notifications.ts +++ b/packages/client-events/notifications.ts @@ -10,7 +10,10 @@ export interface RecoveryState { failure_error_kind?: string } +export type CompactionReason = "idle" | "context_pressure" | "manual" | "provider_native" + export interface ContextCompaction { + reason?: CompactionReason id: string phase: "started" | "succeeded" | "failed" | "cancelled" } @@ -32,6 +35,7 @@ export type NotificationEvent = turn_id?: string compaction_id: string phase: ContextCompaction["phase"] + reason?: CompactionReason } function isRecord(value: unknown): value is Record { @@ -42,6 +46,10 @@ function optional(value: unknown, type: "boolean" | "number" | "string"): boolea return value === undefined || typeof value === type } +export function isCompactionReason(value: unknown): value is CompactionReason { + return value === "idle" || value === "context_pressure" || value === "manual" || value === "provider_native" +} + export function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] { return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled" } @@ -69,7 +77,9 @@ export function decodeNotification(value: unknown): NotificationEvent | null | u return isRecoveryState(value) ? value as unknown as NotificationEvent : null } return typeof value.compaction_id === "string" && value.compaction_id.length > 0 - && isCompactionPhase(value.phase) ? value as unknown as NotificationEvent : null + && isCompactionPhase(value.phase) + && (value.reason === undefined || isCompactionReason(value.reason)) + ? value as unknown as NotificationEvent : null } function isRetryStatus(value: Record): boolean { diff --git a/tests/agent/test_auto_compact.py b/tests/agent/test_auto_compact.py index cae22dcfe..3ca46e626 100644 --- a/tests/agent/test_auto_compact.py +++ b/tests/agent/test_auto_compact.py @@ -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) diff --git a/tests/agent/test_autocompact_unit.py b/tests/agent/test_autocompact_unit.py index 56dcadd6a..947cb2527 100644 --- a/tests/agent/test_autocompact_unit.py +++ b/tests/agent/test_autocompact_unit.py @@ -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 diff --git a/tests/agent/test_runner_governance.py b/tests/agent/test_runner_governance.py index e3ffeadd6..8e3f30636 100644 --- a/tests/agent/test_runner_governance.py +++ b/tests/agent/test_runner_governance.py @@ -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 diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.py index ce29a947a..c579c9533 100644 --- a/tests/command/test_compact_command.py +++ b/tests/command/test_compact_command.py @@ -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) diff --git a/tests/providers/test_openai_codex_provider.py b/tests/providers/test_openai_codex_provider.py index 7d0bb16c5..dc62a53d1 100644 --- a/tests/providers/test_openai_codex_provider.py +++ b/tests/providers/test_openai_codex_provider.py @@ -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"]) diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index 75f3d1689..3ff704f52 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -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) diff --git a/tests/webui/test_outbound_wire.py b/tests/webui/test_outbound_wire.py index 68114a172..09c783703 100644 --- a/tests/webui/test_outbound_wire.py +++ b/tests/webui/test_outbound_wire.py @@ -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 {}), } diff --git a/webui/browser/compaction-reasons.spec.ts b/webui/browser/compaction-reasons.spec.ts new file mode 100644 index 000000000..08662fecd --- /dev/null +++ b/webui/browser/compaction-reasons.spec.ts @@ -0,0 +1,90 @@ +import { readFileSync } from "node:fs"; +import { expect, test, type WebSocketRoute } from "@playwright/test"; +import { supportedLocales } from "../src/i18n/config"; +import type { ThreadProjectionEvent } from "../src/lib/types"; + +const reasons = ["idle", "context_pressure", "manual", "provider_native"] as const; +const phases = ["started", "succeeded", "failed", "cancelled"] as const; + +// Synthetic HTTP history and WebSocket delivery through the production client, +// projection, cache, and thread. No model/provider execution is involved. +for (const { code } of supportedLocales) { + test(`compaction reasons survive live updates and session reentry in ${code}`, async ({ page }, info) => { + await page.setViewportSize({ width: 390, height: 900 }); + const messages: typeof import("../src/i18n/locales/en/common.json") = JSON.parse( + readFileSync(new URL(`../src/i18n/locales/${code}/common.json`, import.meta.url), "utf8"), + ); + const copy = messages.thread.compaction; + await page.addInitScript((locale) => localStorage.setItem("nanobot.locale", locale), code); + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + let history: ThreadProjectionEvent[] = [{ event: "context_compaction", chat_id: "answer-order", + compaction_id: "legacy", phase: "succeeded", created_at_ms: 100, + projection_id: "legacy", turn_id: "legacy-turn", turn_seq: 1 }]; + await page.route("**/api/**", (route) => route.fulfill({ status: 404, json: {} })); + await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } })); + await page.route("**/api/sessions/*/webui-thread?*", (route) => route.fulfill({ json: { + schemaVersion: 3, projection: "events", has_more: false, + events: decodeURIComponent(route.request().url()).includes("websocket:answer-order/") ? history : [], + } })); + let socket!: WebSocketRoute; + const attached = new Set(); + await page.routeWebSocket("**/answer-order-socket", (route) => { + socket = route; + route.onMessage((raw) => { + const frame = JSON.parse(String(raw)); + if (frame.type === "attach") { + attached.add(frame.chat_id); + route.send(JSON.stringify({ event: "attached", chat_id: frame.chat_id })); + } + }); + }); + await page.goto("/browser/fixture.html?case=answer-order"); + await expect.poll(() => attached.has("answer-order")).toBe(true); + const notices = page.locator("[data-context-compaction]"); + await expect(notices).toHaveCount(1); + await expect(notices.first()).toHaveText(copy.succeeded); + await expect(notices.first()).not.toHaveAttribute("role", "status"); + for (const [index, reason] of reasons.entries()) { + const start: ThreadProjectionEvent = { event: "context_compaction", chat_id: "answer-order", + compaction_id: reason, phase: "started", reason, + projection_id: `${reason}-start`, turn_id: `${reason}-turn`, turn_seq: 1 }; + socket.send(JSON.stringify(start)); + const notice = notices.nth(index + 1); + await expect(notices).toHaveCount(index + 2); + await expect(notice).toHaveText(copy.reasons[reason].started); + await expect(notice).toHaveAttribute("aria-busy", "true"); + const handle = await notice.elementHandle(); + const phase = phases[index === 3 ? 1 : index + 1]!; + const finish = { ...start, phase, projection_id: `${reason}-finish`, turn_seq: 2 }; + socket.send(JSON.stringify(finish)); + await expect(notice).toHaveText(copy.reasons[reason][phase]); + await expect(notice).toHaveAttribute("aria-busy", "false"); + expect(await notice.evaluate((node, original) => node === original, handle)).toBe(true); + await expect(notices).toHaveCount(index + 2); + history = [...history, start, finish]; + } + const text = await notices.allTextContents(); + await page.getByRole("button", { name: "Switch topic" }).click(); + await expect(notices).toHaveCount(0); + await page.getByRole("button", { name: "Switch topic" }).click(); + await expect(notices).toHaveText(text); + await page.reload(); + await expect(notices).toHaveText(text); + await expect(page.locator('[data-context-compaction][role="status"]')).toHaveCount(0); + for (const theme of ["light", "dark"]) { + await page.evaluate((value) => document.documentElement.classList.toggle("dark", value === "dark"), theme); + expect(await page.locator("html").evaluate((node) => node.classList.contains("dark"))).toBe(theme === "dark"); + await expect(notices).toHaveText(text); + for (const width of [390, 1280]) { + await page.setViewportSize({ width, height: 900 }); + expect(await notices.evaluateAll((nodes) => nodes.every((node) => { + const rect = node.getBoundingClientRect(); + return rect.left >= 0 && rect.right <= innerWidth && node.scrollWidth <= node.clientWidth; + }))).toBe(true); + await page.screenshot({ path: info.outputPath(`compaction-${code}-${theme}-${width}.png`) }); + } + } + expect(errors).toEqual([]); + }); +} diff --git a/webui/src/components/thread/ContextCompactionNotice.tsx b/webui/src/components/thread/ContextCompactionNotice.tsx index ea2f64250..3c1ca8c7b 100644 --- a/webui/src/components/thread/ContextCompactionNotice.tsx +++ b/webui/src/components/thread/ContextCompactionNotice.tsx @@ -9,13 +9,9 @@ interface ContextCompactionNoticeProps { 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 title = t(compaction.reason + ? `thread.compaction.reasons.${compaction.reason}.${compaction.phase}` + : `thread.compaction.${compaction.phase}`); return (
{ + it.each(["idle", "context_pressure", "manual", "provider_native"] as const)( + "preserves explicit %s through phase updates and rehydration", (reason) => { + const start = { ...base, phase: "started", reason }; + const finish = { ...base, phase: "succeeded", reason, turn_seq: 3, created_at_ms: 456 }; + expect(decodeNotification(start)).toEqual(start); + const rows = history([start, finish]); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ id: "compaction-compact", createdAt: 123, + turnId: "turn", turnPhase: "activity", turnSeq: 3, + compaction: { id: "compact", phase: "succeeded", reason } }); + expect(rows[0].compaction?.announce).toBeUndefined(); + expect(history(JSON.parse(JSON.stringify([start, finish])))).toEqual(rows); + expect(history([{ ...finish, reason }])[0].compaction).toMatchObject({ reason, phase: "succeeded" }); + }, + ); + + it("keeps old records neutral and rejects malformed reasons at the history boundary", () => { + expect(history([{ ...base, phase: "succeeded" }])[0].compaction?.reason).toBeUndefined(); + for (const reason of ["unknown", null, 42]) { + expect(() => history([{ ...base, phase: "succeeded", reason }])).toThrow("Invalid WebUI thread projection event"); + } + }); +}); diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsx index a939b325a..fe86f9760 100644 --- a/webui/src/tests/i18n.test.tsx +++ b/webui/src/tests/i18n.test.tsx @@ -434,6 +434,15 @@ describe("webui i18n", () => { expect(notice?.textContent).toBe(copy[phase]); expect(notice).toHaveAttribute("aria-busy", String(phase === "started")); } + for (const reason of ["idle", "context_pressure", "manual", "provider_native"] as const) { + for (const phase of ["started", "succeeded", "failed", "cancelled"] as const) { + rerender(); + const notice = container.querySelector("[data-context-compaction]"); + expect(copy.reasons[reason][phase]).toBeTruthy(); + expect(notice?.textContent).toBe(copy.reasons[reason][phase]); + expect(notice).toHaveAttribute("aria-busy", String(phase === "started")); + } + } for (const compactReply of ["empty", "failed"] as const) { rerender( { expect(decodeNotification({ event: "delta", text: "hello" })).toBeUndefined(); expect(decodeNotification({ ...fixtures[0], phase: "unknown" })).toBeNull(); expect(decodeNotification({ ...fixtures[0], compaction_id: "" })).toBeNull(); + for (const reason of [null, 42, "unknown"]) { + expect(decodeNotification({ ...fixtures[0], reason })).toBeNull(); + } }); it("allows one terminal transition, including terminal-first hydration", () => { diff --git a/webui/src/tests/thread-test-payload.ts b/webui/src/tests/thread-test-payload.ts index dc7d00edd..f8edfdd72 100644 --- a/webui/src/tests/thread-test-payload.ts +++ b/webui/src/tests/thread-test-payload.ts @@ -65,6 +65,7 @@ function messageEvents(message: UIMessage): ThreadProjectionEvent[] { if (message.kind === "compaction" && message.compaction) { return [{ event: "context_compaction", + reason: message.compaction.reason, ...base, compaction_id: message.compaction.id, phase: message.compaction.phase, diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 7a545717e..dc8980b6d 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -349,7 +349,7 @@ describe("useNanobotStream", () => { act(() => fake.emit("sources", { event: "stream_end", chat_id: "sources", response_sources: [] })); expect(result.current.messages[1].responseSources).toEqual([]); }); - it.each(["succeeded", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => { + it.each(["succeeded", "failed", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => { const fake = fakeClient(); const { result } = renderHook( () => useNanobotStream("chat-compaction", EMPTY_MESSAGES), @@ -362,6 +362,7 @@ describe("useNanobotStream", () => { chat_id: "chat-compaction", compaction_id: "compact-1", phase: "started", + reason: "idle", }); }); @@ -373,6 +374,7 @@ describe("useNanobotStream", () => { compaction: { id: "compact-1", phase: "started", + reason: "idle", announce: true, }, }); @@ -383,6 +385,7 @@ describe("useNanobotStream", () => { chat_id: "chat-compaction", compaction_id: "compact-1", phase, + reason: "idle", }); }); @@ -392,6 +395,7 @@ describe("useNanobotStream", () => { createdAt, compaction: { phase, + reason: "idle", announce: true, }, });