refactor(webui): extract outbound wire encoding (NAN-102)

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-04 17:09:45 +08:00
1 parent e2df7df9f4
commit e93b92c2d0
5 files changed
+228 -90

No files matched your search

+31 -67
View File
@@ -49,13 +49,13 @@ from nanobot.webui.metadata import (
WEBUI_TURN_METADATA_KEY,
)
from nanobot.webui.outbound_projection import WebUIOutboundProjector
from nanobot.webui.outbound_wire import WebUIWirePayload, WebUIWirePersistence
from nanobot.webui.session_identity import is_valid_webui_chat_id
from nanobot.webui.transcript import WEBUI_TRANSCRIPT_INCOMPLETE_KEY
from nanobot.webui.websocket_logging import websockets_server_logger
if TYPE_CHECKING:
from nanobot.bus.outbound_events import ProgressEvent, RecoveryStateEvent
from nanobot.providers.base import LLMUsage
from nanobot.bus.outbound_events import ProgressEvent
# Plain HTTP WebUI routes also run through websockets.process_request.
_WEBUI_HTTP_OPEN_TIMEOUT_S = 360.0
@@ -1376,82 +1376,46 @@ class WebSocketChannel(BaseChannel):
for connection in conns:
await self._safe_send_to(connection, raw, label=" stream ")
async def send_turn_end(
async def send_payload(
self,
chat_id: str,
latency_ms: int | None = None,
payload: WebUIWirePayload,
*,
goal_state: dict[str, Any] | None = None,
usage: LLMUsage | None = None,
round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
persistence: WebUIWirePersistence,
metadata: dict[str, Any] | None = None,
turn_owner: str | None = None,
) -> None:
"""Signal that the agent has fully finished processing the current turn."""
"""Persist as requested, frame, and fan out one encoded WebUI payload."""
conns = list(self._subs.get(chat_id, ()))
body: dict[str, Any] = {"event": "turn_end", "chat_id": chat_id}
turn_id = (metadata or {}).get(WEBUI_TURN_METADATA_KEY)
if isinstance(turn_id, str) and turn_id:
body["turn_id"] = turn_id
if latency_ms is not None:
body["latency_ms"] = int(latency_ms)
if goal_state is not None:
body["goal_state"] = goal_state
if usage is not None:
body["usage"] = usage.to_turn_dict()
if round_usages:
body["round_usages"] = [item.to_turn_dict() for item in round_usages]
if context_window_tokens is not None:
body["context_window_tokens"] = int(context_window_tokens)
canonical_webui_turn = (metadata or {}).get("webui") is True
prior_persistence_failure = (
canonical_webui_turn
and websocket_turn_transcript_persistence_failed(chat_id, turn_owner)
)
persisted = self._persist_turn_transcript_event(
chat_id,
body,
metadata=metadata,
phase="complete",
transcript_overrides=(
{WEBUI_TRANSCRIPT_INCOMPLETE_KEY: True}
if prior_persistence_failure
else None
),
)
if persisted:
# A successful completion either has a complete transcript or now
# carries a durable incomplete marker. The HTTP replay path can
# recover the latter from session history after a gateway restart.
clear_websocket_turn_if_current(chat_id, turn_owner)
self._clear_stream_buffers(chat_id)
body: dict[str, Any] = dict(payload)
if persistence == "turn_complete":
canonical_webui_turn = (metadata or {}).get("webui") is True
prior_persistence_failure = (
canonical_webui_turn
and websocket_turn_transcript_persistence_failed(chat_id, turn_owner)
)
persisted = self._persist_turn_transcript_event(
chat_id,
body,
metadata=metadata,
phase="complete",
transcript_overrides=(
{WEBUI_TRANSCRIPT_INCOMPLETE_KEY: True}
if prior_persistence_failure
else None
),
)
if persisted:
# A successful completion either has a complete transcript or now
# carries a durable incomplete marker. The HTTP replay path can
# recover the latter from session history after a gateway restart.
clear_websocket_turn_if_current(chat_id, turn_owner)
self._clear_stream_buffers(chat_id)
raw = json.dumps(body, ensure_ascii=False)
if not conns:
return
for connection in conns:
await self._safe_send_to(connection, raw, label=" turn_end ")
async def send_recovery_state(
self,
chat_id: str,
event: RecoveryStateEvent,
) -> None:
"""Publish one structured recovery transition without chat pollution."""
body: dict[str, Any] = {
"event": "recovery_state",
"chat_id": chat_id,
"status": event.status,
"recovery_id": event.recovery_id,
"attempts": event.attempts,
}
if event.reason:
body["reason"] = event.reason
if event.can_continue is not None:
body["can_continue"] = event.can_continue
raw = json.dumps(body, ensure_ascii=False)
for connection in list(self._subs.get(chat_id, ())):
await self._safe_send_to(connection, raw, label=" recovery_state ")
await self._safe_send_to(connection, raw, label=f" {body['event']} ")
async def send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
"""Push persisted goal-state snapshot for *chat_id* (multi-chat isolation)."""
@@ -2815,6 +2815,7 @@ async def test_recovery_state_is_a_structured_event_not_assistant_text() -> None
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
channel._persist_turn_transcript_event = MagicMock(return_value=True)
await channel.send(OutboundMessage(
channel="websocket",
@@ -2836,6 +2837,7 @@ async def test_recovery_state_is_a_structured_event_not_assistant_text() -> None
"reason": "tool_state_unknown",
"attempts": 1,
}]
channel._persist_turn_transcript_event.assert_not_called()
@pytest.mark.asyncio
+23 -23
View File
@@ -25,14 +25,18 @@ from nanobot.webui.metadata import (
WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
WEBUI_TURN_METADATA_KEY,
)
from nanobot.webui.outbound_wire import (
WebUIWirePayload,
WebUIWirePersistence,
encode_recovery_state,
encode_turn_end,
)
from nanobot.webui.session_identity import webui_session_key
from nanobot.webui.session_projection import WebUISessionProjection
if TYPE_CHECKING:
from websockets.asyncio.server import ServerConnection
from nanobot.providers.base import LLMUsage
class WebUIOutboundTransport(Protocol):
"""Wire operations required by the outbound application projector."""
@@ -65,7 +69,15 @@ class WebUIOutboundTransport(Protocol):
provenance: dict[str, Any],
) -> None: ...
async def send_recovery_state(self, chat_id: str, event: RecoveryStateEvent) -> None: ...
async def send_payload(
self,
chat_id: str,
payload: WebUIWirePayload,
*,
persistence: WebUIWirePersistence,
metadata: dict[str, Any] | None = None,
turn_owner: str | None = None,
) -> None: ...
async def send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None: ...
@@ -78,19 +90,6 @@ class WebUIOutboundTransport(Protocol):
turn_id: str | None = None,
) -> None: ...
async def send_turn_end(
self,
chat_id: str,
latency_ms: int | None = None,
*,
goal_state: dict[str, Any] | None = None,
usage: LLMUsage | None = None,
round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
metadata: dict[str, Any] | None = None,
turn_owner: str | None = None,
) -> None: ...
async def send_session_updated(self, chat_id: str, *, scope: str | None = None) -> None: ...
async def send_file_edit_events(
@@ -182,7 +181,11 @@ class WebUIOutboundProjector:
return
if isinstance(event, RecoveryStateEvent):
if conns:
await self._transport.send_recovery_state(msg.chat_id, event)
await self._transport.send_payload(
msg.chat_id,
encode_recovery_state(msg.chat_id, event),
persistence="transient",
)
return
if isinstance(event, GoalStateSyncEvent):
if conns:
@@ -221,13 +224,10 @@ class WebUIOutboundProjector:
else "thread"
)
turn_owner = (msg.metadata or {}).get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
await self._transport.send_turn_end(
await self._transport.send_payload(
msg.chat_id,
latency_ms=event.latency_ms,
goal_state=event.goal_state,
usage=event.usage,
round_usages=event.round_usages,
context_window_tokens=event.context_window_tokens,
encode_turn_end(msg.chat_id, event, msg.metadata),
persistence="turn_complete",
metadata=msg.metadata,
turn_owner=turn_owner if isinstance(turn_owner, str) else None,
)
+81
View File
@@ -0,0 +1,81 @@
"""Encode typed outbound events for the WebUI wire protocol."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
from nanobot.bus.outbound_events import RecoveryStateEvent, TurnEndEvent
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
class _ChatWirePayload(TypedDict):
chat_id: str
turn_id: NotRequired[str]
class RecoveryStateWirePayload(_ChatWirePayload):
event: Literal["recovery_state"]
status: str
recovery_id: str
attempts: int
reason: NotRequired[str]
can_continue: NotRequired[bool]
class TurnEndWirePayload(_ChatWirePayload):
event: Literal["turn_end"]
latency_ms: NotRequired[int]
goal_state: NotRequired[dict[str, Any]]
usage: NotRequired[dict[str, int]]
round_usages: NotRequired[list[dict[str, int]]]
context_window_tokens: NotRequired[int]
WebUIWirePayload: TypeAlias = RecoveryStateWirePayload | TurnEndWirePayload
WebUIWirePersistence: TypeAlias = Literal["transient", "turn_complete"]
def encode_recovery_state(
chat_id: str,
event: RecoveryStateEvent,
) -> RecoveryStateWirePayload:
"""Project one transient recovery transition onto its stable wire shape."""
payload: RecoveryStateWirePayload = {
"event": "recovery_state",
"chat_id": chat_id,
"status": event.status,
"recovery_id": event.recovery_id,
"attempts": event.attempts,
}
if event.reason:
payload["reason"] = event.reason
if event.can_continue is not None:
payload["can_continue"] = event.can_continue
return payload
def encode_turn_end(
chat_id: str,
event: TurnEndEvent,
metadata: Mapping[str, object] | None = None,
) -> TurnEndWirePayload:
"""Project a completed turn without leaking internal metadata onto the wire."""
payload: TurnEndWirePayload = {
"event": "turn_end",
"chat_id": chat_id,
}
turn_id = (metadata or {}).get(WEBUI_TURN_METADATA_KEY)
if isinstance(turn_id, str) and turn_id:
payload["turn_id"] = turn_id
if event.latency_ms is not None:
payload["latency_ms"] = int(event.latency_ms)
if event.goal_state is not None:
payload["goal_state"] = event.goal_state
if event.usage is not None:
payload["usage"] = event.usage.to_turn_dict()
if event.round_usages:
payload["round_usages"] = [item.to_turn_dict() for item in event.round_usages]
if event.context_window_tokens is not None:
payload["context_window_tokens"] = int(event.context_window_tokens)
return payload
+91
View File
@@ -0,0 +1,91 @@
from __future__ import annotations
from nanobot.bus.outbound_events import RecoveryStateEvent, TurnEndEvent
from nanobot.providers.base import LLMUsage
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
from nanobot.webui.outbound_wire import encode_recovery_state, encode_turn_end
def test_encode_recovery_state_omits_absent_optional_fields() -> None:
payload = encode_recovery_state(
"chat-1",
RecoveryStateEvent(
status="running",
recovery_id="recovery-1",
reason="",
attempts=0,
),
)
assert payload == {
"event": "recovery_state",
"chat_id": "chat-1",
"status": "running",
"recovery_id": "recovery-1",
"attempts": 0,
}
def test_encode_recovery_state_preserves_false_can_continue() -> None:
payload = encode_recovery_state(
"chat-1",
RecoveryStateEvent(
status="awaiting_user",
recovery_id="recovery-1",
reason="tool_state_unknown",
attempts=1,
can_continue=False,
),
)
assert payload == {
"event": "recovery_state",
"chat_id": "chat-1",
"status": "awaiting_user",
"recovery_id": "recovery-1",
"attempts": 1,
"reason": "tool_state_unknown",
"can_continue": False,
}
def test_encode_turn_end_omits_absent_fields_and_private_metadata() -> None:
payload = encode_turn_end(
"chat-1",
TurnEndEvent(),
{WEBUI_TURN_METADATA_KEY: 42, "private": "must-not-leak"},
)
assert payload == {"event": "turn_end", "chat_id": "chat-1"}
def test_encode_turn_end_projects_complete_wire_contract() -> None:
usage = LLMUsage.reported(
input_tokens=80,
output_tokens=20,
cache_read_tokens=40,
).with_timing(generation_ms=500, ttft_ms=125)
goal_state = {"active": True, "ui_summary": "Explore codebase"}
payload = encode_turn_end(
"chat-1",
TurnEndEvent(
latency_ms=1500,
goal_state=goal_state,
usage=usage,
round_usages=(usage,),
context_window_tokens=128_000,
),
{WEBUI_TURN_METADATA_KEY: "turn-1", "private": "must-not-leak"},
)
assert payload == {
"event": "turn_end",
"chat_id": "chat-1",
"turn_id": "turn-1",
"latency_ms": 1500,
"goal_state": goal_state,
"usage": usage.to_turn_dict(),
"round_usages": [usage.to_turn_dict()],
"context_window_tokens": 128_000,
}