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:
1 parent
084b6bb394
commit
bc5c58d239
38 files changed
+540
-23
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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",
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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"}
|
||||
]
|
||||
@@ -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<string, unknown> {
|
||||
@@ -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<string, unknown>): boolean {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"])
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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<string>();
|
||||
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([]);
|
||||
});
|
||||
}
|
||||
@@ -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 (
|
||||
<div
|
||||
|
||||
@@ -2020,6 +2020,32 @@
|
||||
"messages": "Message status"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Automatically compacting context after inactivity",
|
||||
"succeeded": "Context automatically compacted after inactivity",
|
||||
"failed": "Automatic context compaction failed after inactivity",
|
||||
"cancelled": "Automatic compaction after inactivity did not finish"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Compacting a long context",
|
||||
"succeeded": "Long context compacted",
|
||||
"failed": "Failed to compact a long context",
|
||||
"cancelled": "Compaction of a long context cancelled"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Manual compaction in progress",
|
||||
"succeeded": "Manual compaction complete",
|
||||
"failed": "Manual compaction failed",
|
||||
"cancelled": "Manual compaction cancelled"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Compacting context on the provider's server",
|
||||
"succeeded": "Context compacted on the provider's server",
|
||||
"failed": "Failed to compact context on the provider's server",
|
||||
"cancelled": "Context compaction cancelled on the provider's server"
|
||||
}
|
||||
},
|
||||
"cancelled": "Context compaction cancelled",
|
||||
"empty": "Nothing to compact.",
|
||||
"started": "Compressing context",
|
||||
|
||||
@@ -1815,6 +1815,32 @@
|
||||
"messages": "Estado de mensajes"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Compresión automática por inactividad en curso",
|
||||
"succeeded": "Compresión automática por inactividad completada",
|
||||
"failed": "Falló la compresión automática por inactividad",
|
||||
"cancelled": "No se completó la compresión automática por inactividad"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Comprimiendo un contexto extenso",
|
||||
"succeeded": "Contexto extenso comprimido",
|
||||
"failed": "Falló la compresión de un contexto extenso",
|
||||
"cancelled": "Compresión de un contexto extenso cancelada"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Compresión manual en curso",
|
||||
"succeeded": "Compresión manual completada",
|
||||
"failed": "Falló la compresión manual",
|
||||
"cancelled": "Compresión manual cancelada"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Comprimiendo el contexto en el servidor del proveedor",
|
||||
"succeeded": "Contexto comprimido en el servidor del proveedor",
|
||||
"failed": "Falló la compresión en el servidor del proveedor",
|
||||
"cancelled": "Compresión cancelada en el servidor del proveedor"
|
||||
}
|
||||
},
|
||||
"cancelled": "Compresión de contexto cancelada",
|
||||
"empty": "No hay contexto que comprimir.",
|
||||
"started": "Comprimiendo el contexto",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "État des messages"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Conversation inactive : compression automatique en cours",
|
||||
"succeeded": "Conversation inactive : compression automatique terminée",
|
||||
"failed": "Conversation inactive : échec de la compression automatique",
|
||||
"cancelled": "Conversation inactive : compression automatique non terminée"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Compression d’un contexte volumineux en cours",
|
||||
"succeeded": "Contexte volumineux compressé",
|
||||
"failed": "Échec de la compression d’un contexte volumineux",
|
||||
"cancelled": "Compression d’un contexte volumineux annulée"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Compression manuelle en cours",
|
||||
"succeeded": "Compression manuelle terminée",
|
||||
"failed": "Échec de la compression manuelle",
|
||||
"cancelled": "Compression manuelle annulée"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Compression en cours sur le serveur du fournisseur",
|
||||
"succeeded": "Contexte compressé sur le serveur du fournisseur",
|
||||
"failed": "Échec de la compression sur le serveur du fournisseur",
|
||||
"cancelled": "Compression annulée sur le serveur du fournisseur"
|
||||
}
|
||||
},
|
||||
"cancelled": "Compression du contexte annulée",
|
||||
"empty": "Aucun contexte à compresser.",
|
||||
"started": "Compression du contexte",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "Status pesan"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Memadatkan konteks secara otomatis saat tidak ada pesan baru",
|
||||
"succeeded": "Konteks dipadatkan otomatis saat tidak ada pesan baru",
|
||||
"failed": "Gagal memadatkan konteks secara otomatis saat tidak ada pesan baru",
|
||||
"cancelled": "Pemadatan konteks otomatis saat tidak ada pesan baru tidak selesai"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Memadatkan konteks karena sudah panjang",
|
||||
"succeeded": "Konteks yang panjang telah dipadatkan",
|
||||
"failed": "Gagal memadatkan konteks yang panjang",
|
||||
"cancelled": "Pemadatan konteks yang panjang dibatalkan"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Memadatkan konteks atas permintaan Anda",
|
||||
"succeeded": "Konteks dipadatkan atas permintaan Anda",
|
||||
"failed": "Pemadatan konteks yang Anda minta gagal",
|
||||
"cancelled": "Pemadatan konteks yang Anda minta dibatalkan"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Penyedia model sedang memadatkan konteks",
|
||||
"succeeded": "Penyedia model telah memadatkan konteks",
|
||||
"failed": "Pemadatan konteks di server penyedia model gagal",
|
||||
"cancelled": "Pemadatan konteks di server penyedia model dibatalkan"
|
||||
}
|
||||
},
|
||||
"cancelled": "Pemadatan konteks dibatalkan",
|
||||
"empty": "Tidak ada konteks yang perlu dipadatkan.",
|
||||
"started": "Memadatkan konteks",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "メッセージの状態"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "新しいメッセージがないため自動圧縮中",
|
||||
"succeeded": "新しいメッセージがない間に自動圧縮しました",
|
||||
"failed": "メッセージがない間の自動圧縮に失敗しました",
|
||||
"cancelled": "メッセージがない間の自動圧縮は完了しませんでした"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "コンテキストが長いため圧縮中",
|
||||
"succeeded": "長いコンテキストを圧縮しました",
|
||||
"failed": "長いコンテキストの圧縮に失敗しました",
|
||||
"cancelled": "長いコンテキストの圧縮をキャンセルしました"
|
||||
},
|
||||
"manual": {
|
||||
"started": "手動でコンテキストを圧縮中",
|
||||
"succeeded": "手動でコンテキストを圧縮しました",
|
||||
"failed": "手動でのコンテキスト圧縮に失敗しました",
|
||||
"cancelled": "手動でのコンテキスト圧縮をキャンセルしました"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "プロバイダー側でコンテキストを圧縮中",
|
||||
"succeeded": "プロバイダー側でコンテキストを圧縮しました",
|
||||
"failed": "プロバイダー側の圧縮に失敗しました",
|
||||
"cancelled": "プロバイダー側の圧縮をキャンセルしました"
|
||||
}
|
||||
},
|
||||
"cancelled": "コンテキストの圧縮をキャンセルしました",
|
||||
"empty": "圧縮するコンテキストはありません。",
|
||||
"started": "コンテキストを圧縮中",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "메시지 상태"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "새 메시지가 없어 컨텍스트를 자동 압축 중",
|
||||
"succeeded": "새 메시지가 없어 컨텍스트를 자동 압축했습니다",
|
||||
"failed": "새 메시지가 없을 때의 자동 압축에 실패했습니다",
|
||||
"cancelled": "새 메시지가 없을 때의 자동 압축이 완료되지 않았습니다"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "컨텍스트가 길어져 압축 중",
|
||||
"succeeded": "길어진 컨텍스트를 압축했습니다",
|
||||
"failed": "길어진 컨텍스트 압축에 실패했습니다",
|
||||
"cancelled": "길어진 컨텍스트 압축이 취소되었습니다"
|
||||
},
|
||||
"manual": {
|
||||
"started": "요청하신 대로 컨텍스트를 압축 중",
|
||||
"succeeded": "요청하신 대로 컨텍스트를 압축했습니다",
|
||||
"failed": "요청하신 컨텍스트 압축에 실패했습니다",
|
||||
"cancelled": "요청하신 컨텍스트 압축이 취소되었습니다"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "모델 제공업체에서 컨텍스트를 압축 중",
|
||||
"succeeded": "모델 제공업체에서 컨텍스트를 압축했습니다",
|
||||
"failed": "모델 제공업체의 컨텍스트 압축에 실패했습니다",
|
||||
"cancelled": "모델 제공업체의 컨텍스트 압축이 취소되었습니다"
|
||||
}
|
||||
},
|
||||
"cancelled": "컨텍스트 압축이 취소되었습니다",
|
||||
"empty": "압축할 컨텍스트가 없습니다.",
|
||||
"started": "컨텍스트 압축 중",
|
||||
|
||||
@@ -1828,6 +1828,32 @@
|
||||
"messages": "Status das mensagens"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Compactação automática por inatividade em andamento",
|
||||
"succeeded": "Compactação automática por inatividade concluída",
|
||||
"failed": "Falha na compactação automática por inatividade",
|
||||
"cancelled": "A compactação automática por inatividade não foi concluída"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Compactando um contexto longo",
|
||||
"succeeded": "Contexto longo compactado",
|
||||
"failed": "Falha ao compactar um contexto longo",
|
||||
"cancelled": "Compactação de um contexto longo cancelada"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Compactação manual em andamento",
|
||||
"succeeded": "Compactação manual concluída",
|
||||
"failed": "Falha na compactação manual",
|
||||
"cancelled": "Compactação manual cancelada"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Compactando o contexto no servidor do provedor",
|
||||
"succeeded": "Contexto compactado no servidor do provedor",
|
||||
"failed": "Falha na compactação no servidor do provedor",
|
||||
"cancelled": "Compactação cancelada no servidor do provedor"
|
||||
}
|
||||
},
|
||||
"cancelled": "Compactação do contexto cancelada",
|
||||
"empty": "Não há contexto para compactar.",
|
||||
"started": "Compactando contexto",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "Trạng thái tin nhắn"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Đang tự động nén ngữ cảnh khi không có tin nhắn mới",
|
||||
"succeeded": "Đã tự động nén ngữ cảnh khi không có tin nhắn mới",
|
||||
"failed": "Không thể tự động nén ngữ cảnh khi không có tin nhắn mới",
|
||||
"cancelled": "Quá trình tự động nén ngữ cảnh khi không có tin nhắn mới không hoàn tất"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Đang nén vì ngữ cảnh đã dài",
|
||||
"succeeded": "Đã nén ngữ cảnh dài",
|
||||
"failed": "Nén ngữ cảnh dài không thành công",
|
||||
"cancelled": "Đã hủy nén ngữ cảnh dài"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Đang nén ngữ cảnh theo yêu cầu của bạn",
|
||||
"succeeded": "Đã nén ngữ cảnh theo yêu cầu của bạn",
|
||||
"failed": "Không thể nén ngữ cảnh theo yêu cầu của bạn",
|
||||
"cancelled": "Đã hủy lần nén ngữ cảnh bạn yêu cầu"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Nhà cung cấp mô hình đang nén ngữ cảnh",
|
||||
"succeeded": "Nhà cung cấp mô hình đã nén ngữ cảnh",
|
||||
"failed": "Nén ngữ cảnh trên máy chủ nhà cung cấp không thành công",
|
||||
"cancelled": "Đã hủy nén ngữ cảnh trên máy chủ nhà cung cấp"
|
||||
}
|
||||
},
|
||||
"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",
|
||||
|
||||
@@ -2020,6 +2020,32 @@
|
||||
"messages": "消息状态"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "会话空闲,正在自动压缩上下文",
|
||||
"succeeded": "会话空闲,已自动压缩上下文",
|
||||
"failed": "空闲时自动压缩上下文失败",
|
||||
"cancelled": "空闲期间的自动压缩未完成"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "上下文较长,正在压缩",
|
||||
"succeeded": "上下文较长,已自动压缩",
|
||||
"failed": "上下文较长,自动压缩失败",
|
||||
"cancelled": "上下文较长,压缩已取消"
|
||||
},
|
||||
"manual": {
|
||||
"started": "正在手动压缩",
|
||||
"succeeded": "手动压缩完成",
|
||||
"failed": "手动压缩失败",
|
||||
"cancelled": "手动压缩已取消"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "模型服务正在压缩上下文",
|
||||
"succeeded": "模型服务已压缩上下文",
|
||||
"failed": "模型服务未能完成上下文压缩",
|
||||
"cancelled": "模型服务的上下文压缩已取消"
|
||||
}
|
||||
},
|
||||
"cancelled": "上下文压缩已取消",
|
||||
"empty": "无需压缩上下文",
|
||||
"started": "正在压缩上下文",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "訊息狀態"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "對話閒置,正在自動壓縮上下文",
|
||||
"succeeded": "對話閒置,已自動壓縮上下文",
|
||||
"failed": "閒置時自動壓縮上下文失敗",
|
||||
"cancelled": "閒置期間的自動壓縮未完成"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "上下文較長,正在壓縮",
|
||||
"succeeded": "上下文較長,已自動壓縮",
|
||||
"failed": "上下文較長,自動壓縮失敗",
|
||||
"cancelled": "上下文較長,壓縮已取消"
|
||||
},
|
||||
"manual": {
|
||||
"started": "正在手動壓縮",
|
||||
"succeeded": "手動壓縮完成",
|
||||
"failed": "手動壓縮失敗",
|
||||
"cancelled": "手動壓縮已取消"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "模型服務正在壓縮上下文",
|
||||
"succeeded": "模型服務已壓縮上下文",
|
||||
"failed": "模型服務未能完成上下文壓縮",
|
||||
"cancelled": "模型服務的上下文壓縮已取消"
|
||||
}
|
||||
},
|
||||
"cancelled": "上下文壓縮已取消",
|
||||
"empty": "無需壓縮上下文",
|
||||
"started": "正在壓縮上下文…",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications";
|
||||
import type {
|
||||
ApiServicePayload,
|
||||
AutomationChatsPayload,
|
||||
@@ -380,7 +381,9 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|
||||
if (value.text !== undefined && typeof value.text !== "string") break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "context_compaction":
|
||||
if (typeof value.compaction_id !== "string" || typeof value.phase !== "string") break;
|
||||
if (typeof value.compaction_id !== "string" || !value.compaction_id
|
||||
|| !isCompactionPhase(value.phase)
|
||||
|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "turn_end":
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
|
||||
@@ -1007,6 +1007,7 @@ export function projectThreadEvent(
|
||||
compaction: {
|
||||
id: event.compaction_id,
|
||||
phase: event.phase,
|
||||
reason: event.reason,
|
||||
...(!options.persisted ? { announce: true } : {}),
|
||||
},
|
||||
...positionedTurnFields(state.messages[existing], turnFieldsForProjection(state, event, "activity"), options),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decodeNotification } from "../../../packages/client-events/notifications";
|
||||
import { parseWebuiThreadPayload } from "@/lib/api";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
|
||||
const base = { event: "context_compaction", chat_id: "chat", compaction_id: "compact",
|
||||
turn_id: "turn", turn_phase: "activity", turn_seq: 2, created_at_ms: 123 };
|
||||
|
||||
function history(events: unknown[]) {
|
||||
return projectThreadEvents(parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events }).events);
|
||||
}
|
||||
|
||||
describe("compaction reason wire to history projection", () => {
|
||||
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");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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(<ContextCompactionNotice compaction={{ id: "compact-1", reason, phase, announce: true }} />);
|
||||
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(<MessageBubble message={{
|
||||
id: "reply", role: "assistant", content: "original command reply",
|
||||
|
||||
@@ -22,6 +22,9 @@ describe("shared notification contract", () => {
|
||||
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", () => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user