refactor(webui): extract outbound wire encoding (NAN-102)
This commit is contained in:
1 parent
e2df7df9f4
commit
e93b92c2d0
5 files changed
+228
-90
No files matched your search
@@ -49,13 +49,13 @@ from nanobot.webui.metadata import (
|
|||||||
WEBUI_TURN_METADATA_KEY,
|
WEBUI_TURN_METADATA_KEY,
|
||||||
)
|
)
|
||||||
from nanobot.webui.outbound_projection import WebUIOutboundProjector
|
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.session_identity import is_valid_webui_chat_id
|
||||||
from nanobot.webui.transcript import WEBUI_TRANSCRIPT_INCOMPLETE_KEY
|
from nanobot.webui.transcript import WEBUI_TRANSCRIPT_INCOMPLETE_KEY
|
||||||
from nanobot.webui.websocket_logging import websockets_server_logger
|
from nanobot.webui.websocket_logging import websockets_server_logger
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from nanobot.bus.outbound_events import ProgressEvent, RecoveryStateEvent
|
from nanobot.bus.outbound_events import ProgressEvent
|
||||||
from nanobot.providers.base import LLMUsage
|
|
||||||
|
|
||||||
# Plain HTTP WebUI routes also run through websockets.process_request.
|
# Plain HTTP WebUI routes also run through websockets.process_request.
|
||||||
_WEBUI_HTTP_OPEN_TIMEOUT_S = 360.0
|
_WEBUI_HTTP_OPEN_TIMEOUT_S = 360.0
|
||||||
@@ -1376,82 +1376,46 @@ class WebSocketChannel(BaseChannel):
|
|||||||
for connection in conns:
|
for connection in conns:
|
||||||
await self._safe_send_to(connection, raw, label=" stream ")
|
await self._safe_send_to(connection, raw, label=" stream ")
|
||||||
|
|
||||||
async def send_turn_end(
|
async def send_payload(
|
||||||
self,
|
self,
|
||||||
chat_id: str,
|
chat_id: str,
|
||||||
latency_ms: int | None = None,
|
payload: WebUIWirePayload,
|
||||||
*,
|
*,
|
||||||
goal_state: dict[str, Any] | None = None,
|
persistence: WebUIWirePersistence,
|
||||||
usage: LLMUsage | None = None,
|
|
||||||
round_usages: tuple[LLMUsage, ...] = (),
|
|
||||||
context_window_tokens: int | None = None,
|
|
||||||
metadata: dict[str, Any] | None = None,
|
metadata: dict[str, Any] | None = None,
|
||||||
turn_owner: str | None = None,
|
turn_owner: str | None = 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, ()))
|
conns = list(self._subs.get(chat_id, ()))
|
||||||
body: dict[str, Any] = {"event": "turn_end", "chat_id": chat_id}
|
body: dict[str, Any] = dict(payload)
|
||||||
turn_id = (metadata or {}).get(WEBUI_TURN_METADATA_KEY)
|
if persistence == "turn_complete":
|
||||||
if isinstance(turn_id, str) and turn_id:
|
canonical_webui_turn = (metadata or {}).get("webui") is True
|
||||||
body["turn_id"] = turn_id
|
prior_persistence_failure = (
|
||||||
if latency_ms is not None:
|
canonical_webui_turn
|
||||||
body["latency_ms"] = int(latency_ms)
|
and websocket_turn_transcript_persistence_failed(chat_id, turn_owner)
|
||||||
if goal_state is not None:
|
)
|
||||||
body["goal_state"] = goal_state
|
persisted = self._persist_turn_transcript_event(
|
||||||
if usage is not None:
|
chat_id,
|
||||||
body["usage"] = usage.to_turn_dict()
|
body,
|
||||||
if round_usages:
|
metadata=metadata,
|
||||||
body["round_usages"] = [item.to_turn_dict() for item in round_usages]
|
phase="complete",
|
||||||
if context_window_tokens is not None:
|
transcript_overrides=(
|
||||||
body["context_window_tokens"] = int(context_window_tokens)
|
{WEBUI_TRANSCRIPT_INCOMPLETE_KEY: True}
|
||||||
canonical_webui_turn = (metadata or {}).get("webui") is True
|
if prior_persistence_failure
|
||||||
prior_persistence_failure = (
|
else None
|
||||||
canonical_webui_turn
|
),
|
||||||
and websocket_turn_transcript_persistence_failed(chat_id, turn_owner)
|
)
|
||||||
)
|
if persisted:
|
||||||
persisted = self._persist_turn_transcript_event(
|
# A successful completion either has a complete transcript or now
|
||||||
chat_id,
|
# carries a durable incomplete marker. The HTTP replay path can
|
||||||
body,
|
# recover the latter from session history after a gateway restart.
|
||||||
metadata=metadata,
|
clear_websocket_turn_if_current(chat_id, turn_owner)
|
||||||
phase="complete",
|
self._clear_stream_buffers(chat_id)
|
||||||
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)
|
raw = json.dumps(body, ensure_ascii=False)
|
||||||
if not conns:
|
if not conns:
|
||||||
return
|
return
|
||||||
for connection in conns:
|
for connection in conns:
|
||||||
await self._safe_send_to(connection, raw, label=" turn_end ")
|
await self._safe_send_to(connection, raw, label=f" {body['event']} ")
|
||||||
|
|
||||||
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 ")
|
|
||||||
|
|
||||||
async def send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
|
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)."""
|
"""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()
|
mock_ws = AsyncMock()
|
||||||
channel._attach(mock_ws, "chat-1")
|
channel._attach(mock_ws, "chat-1")
|
||||||
|
channel._persist_turn_transcript_event = MagicMock(return_value=True)
|
||||||
|
|
||||||
await channel.send(OutboundMessage(
|
await channel.send(OutboundMessage(
|
||||||
channel="websocket",
|
channel="websocket",
|
||||||
@@ -2836,6 +2837,7 @@ async def test_recovery_state_is_a_structured_event_not_assistant_text() -> None
|
|||||||
"reason": "tool_state_unknown",
|
"reason": "tool_state_unknown",
|
||||||
"attempts": 1,
|
"attempts": 1,
|
||||||
}]
|
}]
|
||||||
|
channel._persist_turn_transcript_event.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -25,14 +25,18 @@ from nanobot.webui.metadata import (
|
|||||||
WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
|
WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
|
||||||
WEBUI_TURN_METADATA_KEY,
|
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_identity import webui_session_key
|
||||||
from nanobot.webui.session_projection import WebUISessionProjection
|
from nanobot.webui.session_projection import WebUISessionProjection
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from websockets.asyncio.server import ServerConnection
|
from websockets.asyncio.server import ServerConnection
|
||||||
|
|
||||||
from nanobot.providers.base import LLMUsage
|
|
||||||
|
|
||||||
|
|
||||||
class WebUIOutboundTransport(Protocol):
|
class WebUIOutboundTransport(Protocol):
|
||||||
"""Wire operations required by the outbound application projector."""
|
"""Wire operations required by the outbound application projector."""
|
||||||
@@ -65,7 +69,15 @@ class WebUIOutboundTransport(Protocol):
|
|||||||
provenance: dict[str, Any],
|
provenance: dict[str, Any],
|
||||||
) -> None: ...
|
) -> 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: ...
|
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,
|
turn_id: str | None = 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_session_updated(self, chat_id: str, *, scope: str | None = None) -> None: ...
|
||||||
|
|
||||||
async def send_file_edit_events(
|
async def send_file_edit_events(
|
||||||
@@ -182,7 +181,11 @@ class WebUIOutboundProjector:
|
|||||||
return
|
return
|
||||||
if isinstance(event, RecoveryStateEvent):
|
if isinstance(event, RecoveryStateEvent):
|
||||||
if conns:
|
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
|
return
|
||||||
if isinstance(event, GoalStateSyncEvent):
|
if isinstance(event, GoalStateSyncEvent):
|
||||||
if conns:
|
if conns:
|
||||||
@@ -221,13 +224,10 @@ class WebUIOutboundProjector:
|
|||||||
else "thread"
|
else "thread"
|
||||||
)
|
)
|
||||||
turn_owner = (msg.metadata or {}).get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
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,
|
msg.chat_id,
|
||||||
latency_ms=event.latency_ms,
|
encode_turn_end(msg.chat_id, event, msg.metadata),
|
||||||
goal_state=event.goal_state,
|
persistence="turn_complete",
|
||||||
usage=event.usage,
|
|
||||||
round_usages=event.round_usages,
|
|
||||||
context_window_tokens=event.context_window_tokens,
|
|
||||||
metadata=msg.metadata,
|
metadata=msg.metadata,
|
||||||
turn_owner=turn_owner if isinstance(turn_owner, str) else None,
|
turn_owner=turn_owner if isinstance(turn_owner, str) else None,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
Reference in new issue
Block a user