refactor(webui): remove legacy message projection (#5823)

* refactor(webui): defer oversized replay traces as events

* fix(webui): type deferred trace index set

* refactor(webui): remove legacy message projection

* fix(webui): type event protocol boundaries

* test(webui): assert canonical thread events
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-20 16:48:13 +08:00
1 parent 756c8bb7ed
commit 0983762fe5
23 files changed
+943 -2839

No files matched your search

+40 -18
View File
@@ -24,8 +24,8 @@ from nanobot.providers.fallback_provider import FallbackProvider
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.transcript import (
WebUITranscriptRecorder,
append_transcript_object,
build_webui_thread_response,
replay_transcript_to_ui_messages,
webui_transcript_path,
)
@@ -64,7 +64,13 @@ def delivery(chat="chat", *, streaming=True):
@pytest.mark.parametrize("streaming", [False, True])
@pytest.mark.parametrize("failures", [0, 1, 2, 3])
async def test_actual_candidate_is_delivered_and_replayed(streaming, failures):
async def test_actual_candidate_is_delivered_and_replayed(
streaming,
failures,
tmp_path,
monkeypatch,
):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
bus, turn = delivery(streaming=streaming)
candidates = [AnswerProvider(
f"provider-{i}", fail=i < failures,
@@ -104,16 +110,29 @@ async def test_actual_candidate_is_delivered_and_replayed(streaming, failures):
recorder.prepare_event("chat", record, metadata=msg.metadata, phase="answer", include_source=True)
records.append(record)
# Completed segment is the durable record; token-sized deltas aren't needed on replay.
replay = replay_transcript_to_ui_messages([r for r in records if r["event"] != "delta"])
for record in (r for r in records if r["event"] != "delta"):
append_transcript_object("websocket:chat", record)
replay = build_webui_thread_response("websocket:chat")
if failures == 3:
assert all(not r.get("response_sources") for r in records)
assert all(not r.get("responseSources") for r in replay)
if replay is None:
return
replayed_answers = [
event for event in replay["events"]
if event["event"] in {"message", "stream_end"}
]
assert all(not event.get("response_sources") for event in replayed_answers)
else:
assert replay is not None
replayed_answers = [
event for event in replay["events"]
if event["event"] in {"message", "stream_end"}
]
expected = [{"provider": f"provider-{failures}", "model": "same-model",
"preset": ["chosen", "backup-one", "backup-two"][failures],
"fallback": failures > 0}]
assert all(r.get("response_sources") == expected for r in records)
assert replay[-1]["responseSources"] == expected
assert replayed_answers[-1]["response_sources"] == expected
async def test_fallback_flag_is_call_scoped_even_with_identical_identity():
@@ -280,8 +299,9 @@ def test_factory_captures_names_even_when_models_and_settings_are_identical():
assert make_provider(config)._fallback_preset_names == ("renamed",)
def test_old_history_and_malformed_identity_are_not_guessed():
messages = replay_transcript_to_ui_messages([
def test_old_history_and_malformed_identity_are_not_guessed(tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
records = [
{"event": "message", "text": "legacy"},
{"event": "message", "text": "invalid", "response_sources": [{"model": "gpt"}]},
{"event": "message", "text": "recorded", "response_sources": [
@@ -290,12 +310,17 @@ def test_old_history_and_malformed_identity_are_not_guessed():
{"event": "message", "text": "invalid flag", "response_sources": [
{"provider": "xai", "model": "grok", "preset": "old name", "fallback": "true"},
]},
])
assert "responseSources" not in messages[0]
assert messages[1]["responseSources"] == []
]
for record in records:
append_transcript_object("websocket:source-history", record)
replay = build_webui_thread_response("websocket:source-history")
assert replay is not None
events = replay["events"]
assert "response_sources" not in events[0]
assert events[1]["response_sources"] == []
expected = [{"provider": "xai", "model": "grok", "preset": "old name", "fallback": False}]
assert messages[2]["responseSources"] == expected
assert messages[3]["responseSources"] == expected
assert events[2]["response_sources"] == expected
assert events[3]["response_sources"] == expected
async def test_runner_records_each_provider_when_streaming_times_out_and_recovers():
@@ -350,9 +375,6 @@ async def test_websocket_wire_and_disk_replay_preserve_sources(tmp_path, monkeyp
sources[0]["preset"] = "renamed later"
replay = build_webui_thread_response("websocket:source-chat")
assert replay is not None
assert replay["messages"][0]["responseSources"][0]["preset"] == "snapshot name"
assert replay["messages"][0]["responseSources"][0]["fallback"] is True
event_replay = build_webui_thread_response("websocket:source-chat", projection="events")
assert event_replay is not None
end = next(e for e in event_replay["events"] if e["event"] == "stream_end")
assert end["response_sources"] == replay["messages"][0]["responseSources"]
end = next(e for e in replay["events"] if e["event"] == "stream_end")
assert end["response_sources"][0]["preset"] == "snapshot name"
assert end["response_sources"][0]["fallback"] is True
@@ -87,15 +87,15 @@ async def test_read_releases_raw_pages_while_preserving_global_indexes(tmp_path,
index = int(before) if before is not None else 0
calls.append(index)
start = (9 - index) * 5
messages = [
TrackedMessage(role="user", content=f"visible {start}"),
TrackedMessage(role="tool", content="private tool result"),
TrackedMessage(role="assistant", content=f"visible {start + 2}"),
TrackedMessage(role="user", content="hidden", _hidden_history=True),
TrackedMessage(role="assistant", content=""),
events = [
TrackedMessage(event="user_message", text=f"visible {start}"),
TrackedMessage(event="message", kind="progress", text="private tool result"),
TrackedMessage(event="message", text=f"visible {start + 2}"),
TrackedMessage(event="reasoning_delta", text="private reasoning"),
TrackedMessage(event="message", text=""),
]
refs.extend(weakref.ref(message) for message in messages)
return {"messages": messages, "page": {
refs.extend(weakref.ref(event) for event in events)
return {"events": events, "page": {
"has_more_before": index < 9,
"before_cursor": str(index + 1) if index < 9 else None,
}}
@@ -105,9 +105,12 @@ async def test_read_releases_raw_pages_while_preserving_global_indexes(tmp_path,
channel="websocket", chat_id="current", session_key="websocket:current",
)):
result = json.loads(await ReadSessionTool(manager).execute(session_key=key, query=query))
expected = [30, 32, 35, 37, 40, 42, 45, 47]
assert [item["message_index"] for item in result["messages"]] == expected
assert [item["content"] for item in result["messages"]] == [f"visible {i}" for i in expected]
expected_indexes = list(range(12, 20))
expected_values = [30, 32, 35, 37, 40, 42, 45, 47]
assert [item["message_index"] for item in result["messages"]] == expected_indexes
assert [item["content"] for item in result["messages"]] == [
f"visible {i}" for i in expected_values
]
assert calls == list(range(10))
assert not any(ref() is not None for ref in refs)
@@ -1,65 +0,0 @@
"""Shared characterization cases for live and persisted WebUI projection."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from nanobot.webui.transcript import replay_transcript_to_ui_messages
_FIXTURE_PATH = (
Path(__file__).parents[2]
/ "webui"
/ "src"
/ "tests"
/ "fixtures"
/ "live-replay-event-projection.json"
)
_SEMANTIC_MESSAGE_FIELDS = (
"role",
"content",
"kind",
"traces",
"toolEvents",
"fileEdits",
"images",
"media",
"cliApps",
"mcpPresets",
"sessionMentions",
"reasoning",
"latencyMs",
"source",
"turnId",
"turnPhase",
"turnSeq",
)
def _normalize_projection(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
segment_aliases: dict[str, str] = {}
normalized: list[dict[str, Any]] = []
for message in messages:
row = {
field: message[field]
for field in _SEMANTIC_MESSAGE_FIELDS
if field in message and message[field] is not None
}
segment_id = message.get("activitySegmentId")
if isinstance(segment_id, str) and segment_id:
row["activitySegmentId"] = segment_aliases.setdefault(
segment_id,
f"segment-{len(segment_aliases) + 1}",
)
normalized.append(row)
return normalized
def test_legacy_message_projection_keeps_canonical_fixture_compatibility() -> None:
"""Keep the old-client and oversized-trace fallback compatible during migration."""
fixture = json.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))
for case in fixture["cases"]:
actual = replay_transcript_to_ui_messages(case["transcript"])
assert _normalize_projection(actual) == case["expected"], case["name"]
File diff suppressed because it is too large. Load diff
-54
View File
@@ -1,54 +0,0 @@
"""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)
+5 -1
View File
@@ -202,7 +202,11 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
f"{base_url}/api/sessions/{encoded_key}/webui-thread",
token=api_token,
)
contents = [str(message.get("content") or "") for message in thread["messages"]]
contents = [
str(event.get("text") or "")
for event in thread["events"]
if event.get("event") in {"user_message", "message", "stream_end"}
]
assert "/model" in contents
assert any("Current model: `custom/smoke-model`" in text for text in contents)
assert "!printf shell-ok" in contents