refactor(webui): centralize outbound delivery (NAN-365)
This commit is contained in:
1 parent
4a14faa47e
commit
2a3d29ce73
13 files changed
+846
-897
No files matched your search
+1
-1
@@ -6,7 +6,7 @@ Consult this document when changing ownership boundaries, extension points, abst
|
||||
|
||||
New capabilities should be added via `channels/`, `tools/`, skills, or MCP servers. The files `agent/loop.py` and `agent/runner.py` form the critical core path; changes there should be minimal and justified. If a feature can live in a channel adapter, a tool, or an external MCP server, it should not be inlined into the agent loop.
|
||||
|
||||
Runtime state fan-out follows the same boundary. `MessageBus.publish` awaits local subscribers for turn/run/model/goal state changes; `MessageBus.publish_event` queues routed channel delivery without waiting for network sends. Both carry `AgentEvent` values. Runner hooks publish typed output through the turn's scoped `EventSink`; direct-call callbacks are adapted at the execution boundary. WebUI/WebSocket wire details, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter.
|
||||
Runtime state fan-out follows the same boundary. `MessageBus.publish` awaits local subscribers for turn/run/model/goal state changes; `MessageBus.publish_event` queues routed channel delivery without waiting for network sends. Both carry `AgentEvent` values. Runner hooks publish typed output through the turn's scoped `EventSink`; direct-call callbacks are adapted at the execution boundary. WebUI/WebSocket wire details, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter. `nanobot.webui.outbound_delivery.WebUIOutboundDelivery` owns WebUI outbound projection, stream buffers, transcript policy and delivery-turn completion; the WebSocket transport only snapshots recipients and queues its public frames, retaining connection ordering, backpressure and drain accounting.
|
||||
|
||||
Tools and channels own their configuration, metadata, and activation behavior. Tool configuration models live beside their implementations in `agent/tools/*_config.py`; channel descriptors and configuration stay in their channel packages. The root schema in `config/schema.py` assembles these contracts without importing their runtime implementations. Tool classes expose their configuration through `config_key` and `config_cls()`.
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import uuid
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Self, TypeGuard, cast
|
||||
from typing import Any, Self, TypeGuard, cast
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from weakref import WeakSet
|
||||
|
||||
@@ -23,22 +23,12 @@ from websockets.http11 import Request as WsRequest
|
||||
from websockets.http11 import Response as WsResponse
|
||||
from websockets.protocol import CONNECTING
|
||||
|
||||
from nanobot.bus.events import (
|
||||
INBOUND_META_USER_SHELL,
|
||||
OUTBOUND_META_AGENT_UI,
|
||||
OutboundMessage,
|
||||
)
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
mark_websocket_turn_transcript_persistence_failed,
|
||||
websocket_turn_transcript_persistence_failed,
|
||||
)
|
||||
from nanobot.webui.gateway_services import GatewayServices
|
||||
from nanobot.webui.http_utils import (
|
||||
normalize_config_path as _normalize_config_path,
|
||||
@@ -50,24 +40,10 @@ from nanobot.webui.http_utils import (
|
||||
query_first as _query_first,
|
||||
)
|
||||
from nanobot.webui.inbound_commands import WebUICommandRouter
|
||||
from nanobot.webui.metadata import (
|
||||
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
||||
WEBUI_RESTART_CONTROL_METADATA_KEY,
|
||||
WEBUI_TURN_METADATA_KEY,
|
||||
)
|
||||
from nanobot.webui.outbound_projection import WebUIOutboundProjector
|
||||
from nanobot.webui.outbound_wire import (
|
||||
WebUIWirePayload,
|
||||
WebUIWirePersistence,
|
||||
project_tool_events,
|
||||
)
|
||||
from nanobot.webui.outbound_delivery import ChatAudience, WebUIAudience, WebUIOutboundDelivery
|
||||
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
|
||||
|
||||
# Plain HTTP WebUI routes also run through websockets.process_request.
|
||||
_WEBUI_HTTP_OPEN_TIMEOUT_S = 360.0
|
||||
_LISTENER_CHECK_INTERVAL_S = 0.5
|
||||
@@ -398,19 +374,18 @@ class WebSocketChannel(BaseChannel):
|
||||
self._retired_connections: WeakSet[ServerConnection] = WeakSet()
|
||||
|
||||
self.gateway = gateway
|
||||
self._media = gateway.media
|
||||
self._uploads = gateway.uploads
|
||||
self._transcripts = gateway.transcripts
|
||||
self._temporary_chats = gateway.temporary_chats
|
||||
self._session_projection = gateway.session_projection
|
||||
self._commands = WebUICommandRouter(self, gateway)
|
||||
self._outbound = WebUIOutboundDelivery(
|
||||
self,
|
||||
media=gateway.media,
|
||||
transcripts=gateway.transcripts,
|
||||
temporary_chats=gateway.temporary_chats,
|
||||
session_projection=gateway.session_projection,
|
||||
)
|
||||
self._commands = WebUICommandRouter(self, gateway, outbound=self._outbound)
|
||||
self._webui_request_tasks = self._commands.request_tasks
|
||||
self._webui_request_operations = self._commands.request_operations
|
||||
self._webui_request_locks = self._commands.request_locks
|
||||
self._outbound = WebUIOutboundProjector(self, self._session_projection)
|
||||
|
||||
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
|
||||
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
|
||||
|
||||
# -- Subscription bookkeeping -------------------------------------------
|
||||
|
||||
@@ -418,6 +393,14 @@ class WebSocketChannel(BaseChannel):
|
||||
"""Return a stable snapshot of one chat's transport subscribers."""
|
||||
return tuple(self._subs.get(chat_id, ()))
|
||||
|
||||
def webui_recipients(self, audience: WebUIAudience) -> tuple[ServerConnection, ...]:
|
||||
"""Snapshot the selected audience without interpreting its public frames."""
|
||||
if isinstance(audience, ChatAudience):
|
||||
return self.webui_subscribers(audience.chat_id)
|
||||
if audience == "authenticated_webui":
|
||||
return tuple(self._webui_connections)
|
||||
return tuple(self._conn_chats)
|
||||
|
||||
def webui_connection_chats(self, connection: ServerConnection) -> tuple[str, ...]:
|
||||
return tuple(self._conn_chats.get(connection, ()))
|
||||
|
||||
@@ -430,12 +413,6 @@ class WebSocketChannel(BaseChannel):
|
||||
def webui_clear_connection_default(self, connection: ServerConnection) -> None:
|
||||
self._conn_default.pop(connection, None)
|
||||
|
||||
def webui_clear_stream_buffers(self, chat_id: str) -> None:
|
||||
self._clear_stream_buffers(chat_id)
|
||||
|
||||
async def webui_hydrate(self, chat_id: str) -> None:
|
||||
await self._hydrate_after_subscribe(chat_id)
|
||||
|
||||
async def webui_send_event(
|
||||
self,
|
||||
connection: ServerConnection,
|
||||
@@ -506,14 +483,6 @@ class WebSocketChannel(BaseChannel):
|
||||
if not subscribers:
|
||||
self._subs.pop(chat_id, None)
|
||||
|
||||
def _clear_stream_buffers(self, chat_id: str) -> None:
|
||||
for key in tuple(self._stream_text_buffers):
|
||||
if key[0] == chat_id:
|
||||
self._stream_text_buffers.pop(key, None)
|
||||
for key in tuple(self._reasoning_text_buffers):
|
||||
if key[0] == chat_id:
|
||||
self._reasoning_text_buffers.pop(key, None)
|
||||
|
||||
async def _cleanup_connection(self, connection: ServerConnection) -> None:
|
||||
"""Remove *connection* from every subscription set; safe to call multiple times."""
|
||||
self._retired_connections.add(connection)
|
||||
@@ -532,10 +501,6 @@ class WebSocketChannel(BaseChannel):
|
||||
if self._connection_outbound.get(connection) is state:
|
||||
self._connection_outbound.pop(connection, None)
|
||||
|
||||
async def _hydrate_after_subscribe(self, chat_id: str) -> None:
|
||||
"""Replay persisted or actively running per-chat state after subscribe."""
|
||||
await self._outbound.hydrate(chat_id)
|
||||
|
||||
async def _send_event(
|
||||
self,
|
||||
connection: ServerConnection,
|
||||
@@ -688,7 +653,7 @@ class WebSocketChannel(BaseChannel):
|
||||
)
|
||||
|
||||
async def start(self) -> None:
|
||||
await self._transcripts.initialize()
|
||||
await self._outbound.initialize()
|
||||
self.gateway.http.remote_instances.resume()
|
||||
from nanobot.utils.logging_bridge import redirect_lib_logging
|
||||
|
||||
@@ -836,7 +801,7 @@ class WebSocketChannel(BaseChannel):
|
||||
if self._server is server:
|
||||
self._server = None
|
||||
|
||||
disconnect_pairing = self.bus.subscribe(self._queue_pairing_changed, PairingChanged)
|
||||
disconnect_pairing = self._outbound.bind_pairing(self.bus, channel=self.name)
|
||||
task = asyncio.create_task(runner())
|
||||
self._server_task = task
|
||||
try:
|
||||
@@ -884,7 +849,7 @@ class WebSocketChannel(BaseChannel):
|
||||
# Register only after ready is successfully sent to avoid out-of-order sends
|
||||
self._conn_default[connection] = default_chat_id
|
||||
self._attach(connection, default_chat_id)
|
||||
await self._hydrate_after_subscribe(default_chat_id)
|
||||
await self._outbound.hydrate(default_chat_id)
|
||||
|
||||
async for raw in connection:
|
||||
if isinstance(raw, bytes):
|
||||
@@ -1162,151 +1127,9 @@ class WebSocketChannel(BaseChannel):
|
||||
# Give an idle writer a chance to start without waiting for physical I/O.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def _persist_turn_transcript_event(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str,
|
||||
include_source: bool = False,
|
||||
transcript_overrides: dict[str, Any] | None = None,
|
||||
) -> bool:
|
||||
"""Persist one canonical turn event and retain unsafe owners on failure."""
|
||||
if (
|
||||
(metadata or {}).get(WEBUI_RESTART_CONTROL_METADATA_KEY) is True
|
||||
or not self._temporary_chats.should_persist_transcript(chat_id)
|
||||
):
|
||||
self._transcripts.prepare_event(
|
||||
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
|
||||
)
|
||||
return True
|
||||
persisted = await self._transcripts.prepare_and_append(
|
||||
chat_id,
|
||||
event,
|
||||
metadata=metadata,
|
||||
phase=phase,
|
||||
include_source=include_source,
|
||||
transcript_overrides=transcript_overrides,
|
||||
)
|
||||
return self._retain_turn_on_transcript_failure(
|
||||
chat_id,
|
||||
persisted=persisted,
|
||||
metadata=metadata,
|
||||
phase=phase,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _retain_turn_on_transcript_failure(
|
||||
chat_id: str,
|
||||
*,
|
||||
persisted: bool,
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str,
|
||||
) -> bool:
|
||||
if not persisted and phase in {"answer", "complete"} and (metadata or {}).get("webui") is True:
|
||||
owner = (metadata or {}).get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
||||
mark_websocket_turn_transcript_persistence_failed(
|
||||
chat_id,
|
||||
owner if isinstance(owner, str) else None,
|
||||
)
|
||||
return persisted
|
||||
|
||||
async def _persist_turn_stream_event(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
completed_text: str | None,
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str,
|
||||
include_source: bool = False,
|
||||
) -> bool:
|
||||
"""Persist the canonical end of a live stream, never its wire chunks."""
|
||||
if not self._temporary_chats.should_persist_transcript(chat_id):
|
||||
self._transcripts.prepare_event(
|
||||
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
|
||||
)
|
||||
return True
|
||||
persisted = await self._transcripts.prepare_and_append_stream_event(
|
||||
chat_id,
|
||||
event,
|
||||
completed_text=completed_text,
|
||||
metadata=metadata,
|
||||
phase=phase,
|
||||
include_source=include_source,
|
||||
)
|
||||
return self._retain_turn_on_transcript_failure(
|
||||
chat_id,
|
||||
persisted=persisted,
|
||||
metadata=metadata,
|
||||
phase=phase,
|
||||
)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
await self._outbound.send(msg)
|
||||
|
||||
async def send_projected_message(
|
||||
self,
|
||||
msg: OutboundMessage,
|
||||
progress_event: ProgressEvent | None,
|
||||
) -> None:
|
||||
"""Serialize one ordinary outbound message selected by the projector."""
|
||||
conns = list(self._subs.get(msg.chat_id, ()))
|
||||
text = msg.content
|
||||
user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True
|
||||
wire_text = text if user_shell else self._media.rewrite_local_markdown_images(text)
|
||||
payload: dict[str, Any] = {
|
||||
"event": "message",
|
||||
"chat_id": msg.chat_id,
|
||||
"text": wire_text,
|
||||
}
|
||||
if user_shell:
|
||||
payload["render_as"] = "text"
|
||||
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
|
||||
if isinstance(turn_id, str) and turn_id:
|
||||
payload["turn_id"] = turn_id
|
||||
if msg.media:
|
||||
payload["media"] = msg.media
|
||||
urls: list[dict[str, str]] = []
|
||||
for entry in msg.media:
|
||||
signed = self._media.sign_or_stage_media_path(Path(entry))
|
||||
if signed is not None:
|
||||
urls.append(signed)
|
||||
if urls:
|
||||
payload["media_urls"] = urls
|
||||
if msg.reply_to:
|
||||
payload["reply_to"] = msg.reply_to
|
||||
lat = msg.metadata.get("latency_ms")
|
||||
if isinstance(lat, (int, float)):
|
||||
payload["latency_ms"] = int(lat)
|
||||
if progress_event and progress_event.tool_events:
|
||||
payload["tool_events"] = project_tool_events(progress_event.tool_events)
|
||||
agent_ui = msg.metadata.get(OUTBOUND_META_AGENT_UI)
|
||||
if agent_ui is not None:
|
||||
payload["agent_ui"] = agent_ui
|
||||
# Mark intermediate agent breadcrumbs (tool-call hints, generic
|
||||
# progress strings) so WS clients can render them as subordinate
|
||||
# trace rows rather than conversational replies.
|
||||
if progress_event and progress_event.tool_hint:
|
||||
payload["kind"] = "tool_hint"
|
||||
elif progress_event:
|
||||
payload["kind"] = "progress"
|
||||
phase = "activity" if payload.get("kind") in ("tool_hint", "progress") else "answer"
|
||||
await self._persist_turn_transcript_event(
|
||||
msg.chat_id,
|
||||
payload,
|
||||
metadata=msg.metadata,
|
||||
phase=phase,
|
||||
include_source=True,
|
||||
transcript_overrides={"text": text},
|
||||
)
|
||||
raw = json.dumps(payload, ensure_ascii=False)
|
||||
if not conns:
|
||||
return
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" ")
|
||||
|
||||
async def send_reasoning_delta(
|
||||
self,
|
||||
chat_id: str,
|
||||
@@ -1315,36 +1138,7 @@ class WebSocketChannel(BaseChannel):
|
||||
*,
|
||||
stream_id: str | None = None,
|
||||
) -> None:
|
||||
"""Push one chunk of model reasoning. Mirrors ``send_delta`` shape so
|
||||
clients receive a stream that opens, updates in place, and closes —
|
||||
rendered above the active assistant bubble with a shimmer header
|
||||
until the matching ``reasoning_end`` arrives.
|
||||
"""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
if not delta:
|
||||
return
|
||||
meta = metadata or {}
|
||||
body: dict[str, Any] = {
|
||||
"event": "reasoning_delta",
|
||||
"chat_id": chat_id,
|
||||
"text": delta,
|
||||
}
|
||||
if stream_id is not None:
|
||||
body["stream_id"] = stream_id
|
||||
stream_key = (chat_id, str(stream_id or ""))
|
||||
self._reasoning_text_buffers.setdefault(stream_key, []).append(delta)
|
||||
await self._persist_turn_stream_event(
|
||||
chat_id,
|
||||
body,
|
||||
completed_text=None,
|
||||
metadata=meta,
|
||||
phase="reasoning",
|
||||
)
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
if not conns:
|
||||
return
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" reasoning ")
|
||||
await self._outbound.send_reasoning_delta(chat_id, delta, metadata, stream_id=stream_id)
|
||||
|
||||
async def send_reasoning_end(
|
||||
self,
|
||||
@@ -1353,29 +1147,7 @@ class WebSocketChannel(BaseChannel):
|
||||
*,
|
||||
stream_id: str | None = None,
|
||||
) -> None:
|
||||
"""Close the current reasoning stream segment for in-place renderers."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
meta = metadata or {}
|
||||
body: dict[str, Any] = {
|
||||
"event": "reasoning_end",
|
||||
"chat_id": chat_id,
|
||||
}
|
||||
if stream_id is not None:
|
||||
body["stream_id"] = stream_id
|
||||
stream_key = (chat_id, str(stream_id or ""))
|
||||
reasoning_text = "".join(self._reasoning_text_buffers.pop(stream_key, []))
|
||||
await self._persist_turn_stream_event(
|
||||
chat_id,
|
||||
body,
|
||||
completed_text=reasoning_text or None,
|
||||
metadata=meta,
|
||||
phase="reasoning",
|
||||
)
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
if not conns:
|
||||
return
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" reasoning_end ")
|
||||
await self._outbound.send_reasoning_end(chat_id, metadata, stream_id=stream_id)
|
||||
|
||||
async def send_file_edit_events(
|
||||
self,
|
||||
@@ -1383,23 +1155,7 @@ class WebSocketChannel(BaseChannel):
|
||||
edits: list[dict[str, Any]],
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
payload: dict[str, Any] = {
|
||||
"event": "file_edit",
|
||||
"chat_id": chat_id,
|
||||
"edits": edits,
|
||||
}
|
||||
await self._persist_turn_transcript_event(
|
||||
chat_id,
|
||||
payload,
|
||||
metadata=metadata,
|
||||
phase="activity",
|
||||
)
|
||||
raw = json.dumps(payload, ensure_ascii=False)
|
||||
if not conns:
|
||||
return
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" file_edit ")
|
||||
await self._outbound.send_file_edit_events(chat_id, edits, metadata)
|
||||
|
||||
async def send_delta(
|
||||
self,
|
||||
@@ -1412,230 +1168,7 @@ class WebSocketChannel(BaseChannel):
|
||||
resuming: bool = False,
|
||||
merge_next: bool = False,
|
||||
) -> None:
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
meta = metadata or {}
|
||||
stream_key = (chat_id, str(stream_id or ""))
|
||||
completed_text: str | None = None
|
||||
if stream_end:
|
||||
body: dict[str, Any] = {"event": "stream_end", "chat_id": chat_id}
|
||||
buffered = (
|
||||
self._stream_text_buffers.setdefault(stream_key, [])
|
||||
if merge_next
|
||||
else self._stream_text_buffers.pop(stream_key, [])
|
||||
)
|
||||
if delta:
|
||||
buffered.append(delta)
|
||||
full_text = "".join(buffered)
|
||||
rewritten = self._media.rewrite_local_markdown_images(full_text)
|
||||
completed_text = rewritten
|
||||
if delta or rewritten != full_text:
|
||||
body["text"] = rewritten
|
||||
else:
|
||||
body = {
|
||||
"event": "delta",
|
||||
"chat_id": chat_id,
|
||||
"text": delta,
|
||||
}
|
||||
self._stream_text_buffers.setdefault(stream_key, []).append(delta)
|
||||
if stream_id is not None:
|
||||
body["stream_id"] = stream_id
|
||||
if stream_end and resuming:
|
||||
body["resuming"] = True
|
||||
if stream_end and merge_next:
|
||||
body["merge_next"] = True
|
||||
await self._persist_turn_stream_event(
|
||||
chat_id,
|
||||
body,
|
||||
completed_text=completed_text,
|
||||
metadata=meta,
|
||||
phase="answer",
|
||||
include_source=True,
|
||||
await self._outbound.send_delta(
|
||||
chat_id, delta, metadata, stream_id=stream_id,
|
||||
stream_end=stream_end, resuming=resuming, merge_next=merge_next,
|
||||
)
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
if not conns:
|
||||
return
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" stream ")
|
||||
|
||||
async def send_payload(
|
||||
self,
|
||||
chat_id: str,
|
||||
payload: WebUIWirePayload,
|
||||
*,
|
||||
persistence: WebUIWirePersistence,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
turn_owner: str | None = None,
|
||||
) -> None:
|
||||
"""Persist as requested, frame, and fan out one encoded WebUI payload."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
body: dict[str, Any] = dict(payload)
|
||||
if persistence == "turn_activity":
|
||||
await self._persist_turn_transcript_event(
|
||||
chat_id,
|
||||
body,
|
||||
metadata=metadata,
|
||||
phase="activity",
|
||||
)
|
||||
elif 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 = await 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=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)."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
if not conns:
|
||||
return
|
||||
body = {"event": "goal_state", "chat_id": chat_id, "goal_state": blob}
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" goal_state ")
|
||||
|
||||
async def send_goal_status(
|
||||
self,
|
||||
chat_id: str,
|
||||
status: str,
|
||||
*,
|
||||
started_at: float | None = None,
|
||||
turn_id: str | None = None,
|
||||
) -> None:
|
||||
"""Notify subscribed clients that a turn started or finished (wall-clock hint)."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
if not conns:
|
||||
return
|
||||
body: dict[str, Any] = {
|
||||
"event": "goal_status",
|
||||
"chat_id": chat_id,
|
||||
"status": status,
|
||||
}
|
||||
if status == "running" and started_at is not None:
|
||||
body["started_at"] = started_at
|
||||
if turn_id:
|
||||
body["turn_id"] = turn_id
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" goal_status ")
|
||||
|
||||
async def send_session_updated(self, chat_id: str, *, scope: str | None = None) -> None:
|
||||
"""Notify WebUI clients that a session row should refresh."""
|
||||
conns = list(self._conn_chats)
|
||||
if not conns:
|
||||
return
|
||||
body: dict[str, Any] = {"event": "session_updated", "chat_id": chat_id}
|
||||
if scope:
|
||||
body["scope"] = scope
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" session_updated ")
|
||||
|
||||
async def send_user_input(
|
||||
self,
|
||||
chat_id: str,
|
||||
*,
|
||||
content: str,
|
||||
created_at_ms: int,
|
||||
provenance: dict[str, Any],
|
||||
) -> None:
|
||||
"""Project user input produced outside a WebSocket connection."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
if not conns:
|
||||
return
|
||||
body: dict[str, Any] = {
|
||||
"event": "user_message",
|
||||
"chat_id": chat_id,
|
||||
"text": content,
|
||||
"created_at_ms": created_at_ms,
|
||||
"starts_turn": False,
|
||||
}
|
||||
if provenance:
|
||||
body["provenance"] = provenance
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" user_message ")
|
||||
|
||||
async def _queue_pairing_changed(self, event: PairingChanged) -> None:
|
||||
await self.bus.publish_event(event, channel=self.name, chat_id="*")
|
||||
|
||||
async def send_pairing_changed(self) -> None:
|
||||
"""Project invalidation only to bootstrap-authenticated WebUI clients."""
|
||||
for connection in tuple(self._webui_connections):
|
||||
await self._send_event(connection, "pairing_changed")
|
||||
|
||||
async def send_runtime_model_updated(
|
||||
self,
|
||||
*,
|
||||
model_name: Any,
|
||||
model_preset: Any = None,
|
||||
) -> None:
|
||||
"""Broadcast runtime model changes to every open websocket connection."""
|
||||
conns = list(self._conn_chats)
|
||||
if not conns or not isinstance(model_name, str) or not model_name.strip():
|
||||
return
|
||||
body: dict[str, Any] = {
|
||||
"event": "runtime_model_updated",
|
||||
"model_name": model_name.strip(),
|
||||
}
|
||||
if isinstance(model_preset, str) and model_preset.strip():
|
||||
body["model_preset"] = model_preset.strip()
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" runtime_model_updated ")
|
||||
|
||||
async def send_turn_model_updated(
|
||||
self,
|
||||
chat_id: str,
|
||||
*,
|
||||
model_name: Any,
|
||||
model_preset: Any = None,
|
||||
context_window_tokens: Any = None,
|
||||
fallback: bool = False,
|
||||
reauth_provider: str | None = None,
|
||||
) -> None:
|
||||
"""Notify one chat's subscribers which model is handling its current request."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
if (
|
||||
not conns
|
||||
or not isinstance(model_name, str)
|
||||
or not model_name.strip()
|
||||
):
|
||||
return
|
||||
body: dict[str, Any] = {
|
||||
"event": "turn_model_updated",
|
||||
"chat_id": chat_id,
|
||||
"model_name": model_name.strip(),
|
||||
}
|
||||
if isinstance(model_preset, str) and model_preset.strip():
|
||||
body["model_preset"] = model_preset.strip()
|
||||
if isinstance(context_window_tokens, int) and context_window_tokens > 0:
|
||||
body["context_window_tokens"] = context_window_tokens
|
||||
if fallback:
|
||||
body["fallback"] = True
|
||||
if reauth_provider:
|
||||
body["reauth_provider"] = reauth_provider
|
||||
raw = json.dumps(body, ensure_ascii=False)
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" turn_model_updated ")
|
||||
@@ -793,7 +793,12 @@ async def test_send_session_updated_broadcasts_to_other_webui_connections(bus) -
|
||||
assert sorted(channel._subs) == ["chat-a", "chat-b"]
|
||||
assert sum(len(conns) for conns in channel._subs.values()) == 2
|
||||
|
||||
await channel.send_session_updated("chat-a", scope="thread")
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-a",
|
||||
content="",
|
||||
event=SessionUpdatedEvent(scope="thread"),
|
||||
))
|
||||
|
||||
active_events = [json.loads(raw)["event"] for raw in active_conn.sent]
|
||||
other_events = [json.loads(raw)["event"] for raw in other_conn.sent]
|
||||
@@ -2274,7 +2279,7 @@ async def test_in_flight_message_without_scope_uses_latest_access_mode(
|
||||
hydrate_started.set()
|
||||
await release_hydrate.wait()
|
||||
|
||||
channel._hydrate_after_subscribe = blocked_hydrate
|
||||
monkeypatch.setattr(channel._outbound, "hydrate", blocked_hydrate)
|
||||
message_conn = AsyncMock()
|
||||
message_conn.remote_address = ("203.0.113.8", 50123)
|
||||
settings_conn = AsyncMock()
|
||||
@@ -2883,7 +2888,7 @@ async def test_send_delta_marks_resuming_stream_end() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_delta_keeps_buffer_across_merged_stream_boundary(history, ) -> None:
|
||||
async def test_send_delta_preserves_merged_text_then_starts_fresh_segment(history) -> None:
|
||||
|
||||
|
||||
bus = MagicMock()
|
||||
@@ -2914,7 +2919,6 @@ async def test_send_delta_keeps_buffer_across_merged_stream_boundary(history, )
|
||||
"first ",
|
||||
"second",
|
||||
]
|
||||
assert ("chat-1", "sid") not in channel._stream_text_buffers
|
||||
lines = history.read("websocket:chat-1")
|
||||
assert [line["event"] for line in lines] == ["stream_end", "stream_end"]
|
||||
assert [line["text"] for line in lines] == ["first ", "first second"]
|
||||
@@ -2922,6 +2926,15 @@ async def test_send_delta_keeps_buffer_across_merged_stream_boundary(history, )
|
||||
assert body is not None
|
||||
assert _thread_conversation_events(body)[-1]["content"] == "first second"
|
||||
|
||||
await history.stream(
|
||||
channel, "send_delta", "chat-1", "new segment", stream_id="sid", stream_end=True,
|
||||
)
|
||||
|
||||
assert _sent_ws_payloads(mock_ws)[-1]["text"] == "new segment"
|
||||
assert [line["text"] for line in history.read("websocket:chat-1")] == [
|
||||
"first ", "first second", "new segment",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_delta_stream_end_includes_inline_final_text() -> None:
|
||||
@@ -3224,25 +3237,42 @@ async def test_reasoning_transcript_persists_one_canonical_record(history, monke
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_end_discards_unclosed_stream_buffers() -> None:
|
||||
async def test_turn_end_keeps_unclosed_text_out_of_the_next_stream_segment(history) -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
gateway=_basic_handler(bus, session_manager=history.sessions),
|
||||
)
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-unclosed")
|
||||
|
||||
await channel.send_delta("chat-unclosed", "partial", stream_id="s1")
|
||||
await channel.send_reasoning_delta("chat-unclosed", "thinking", stream_id="r1")
|
||||
await channel.send(OutboundMessage(
|
||||
await history.stream(channel, "send_delta", "chat-unclosed", "partial", stream_id="s1")
|
||||
await history.stream(channel, "send_reasoning_delta", "chat-unclosed", "thinking", stream_id="r1")
|
||||
await channel.send(await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-unclosed",
|
||||
content="",
|
||||
event=TurnEndEvent(),
|
||||
))
|
||||
await history.stream(channel, "send_delta", "chat-unclosed", "fresh", stream_id="s1")
|
||||
await history.stream(
|
||||
channel, "send_delta", "chat-unclosed", " answer", stream_id="s1", stream_end=True,
|
||||
)
|
||||
await history.stream(channel, "send_reasoning_delta", "chat-unclosed", "new thought", stream_id="r1")
|
||||
await history.stream(channel, "send_reasoning_end", "chat-unclosed", stream_id="r1")
|
||||
|
||||
assert channel._stream_text_buffers == {}
|
||||
assert channel._reasoning_text_buffers == {}
|
||||
payloads = _sent_ws_payloads(mock_ws)
|
||||
assert next(payload for payload in payloads if payload["event"] == "stream_end")["text"] == "fresh answer"
|
||||
assert payloads[-2]["event"] == "reasoning_delta"
|
||||
assert payloads[-2]["text"] == "new thought"
|
||||
assert payloads[-1] == {
|
||||
"event": "reasoning_end", "chat_id": "chat-unclosed", "stream_id": "r1",
|
||||
}
|
||||
lines = history.read("websocket:chat-unclosed")
|
||||
assert [(line["event"], line.get("text")) for line in lines] == [
|
||||
("turn_end", None), ("stream_end", "fresh answer"), ("reasoning_end", "new thought"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -3267,19 +3297,19 @@ async def test_send_turn_end_emits_turn_end_event() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_retry_status_is_transient_and_turn_scoped(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
history, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.outbound_wire.time.time", lambda: 120.0)
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
gateway=_basic_handler(bus, session_manager=history.sessions),
|
||||
)
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-1")
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
await channel.send(await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
@@ -3303,21 +3333,21 @@ async def test_retry_status_is_transient_and_turn_scoped(
|
||||
"error_kind": "connection",
|
||||
"retry_after_s": 3.5,
|
||||
}]
|
||||
assert history.read("websocket:chat-1") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_retry_wait_is_not_sent_or_persisted() -> None:
|
||||
async def test_legacy_retry_wait_is_not_sent_or_persisted(history) -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
gateway=_basic_handler(bus, session_manager=history.sessions),
|
||||
)
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-1")
|
||||
channel._persist_turn_transcript_event = MagicMock(return_value=True)
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
await channel.send(await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="Model request failed, retry in 2s (attempt 1).",
|
||||
@@ -3327,7 +3357,7 @@ async def test_legacy_retry_wait_is_not_sent_or_persisted() -> None:
|
||||
))
|
||||
|
||||
assert _sent_ws_payloads(mock_ws) == []
|
||||
channel._persist_turn_transcript_event.assert_not_called()
|
||||
assert history.read("websocket:chat-1") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -3439,18 +3469,17 @@ async def test_context_compaction_is_structured_persisted_and_summary_free(histo
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovery_state_is_a_structured_event_not_assistant_text() -> None:
|
||||
async def test_recovery_state_is_a_structured_event_not_assistant_text(history) -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
gateway=_basic_handler(bus, session_manager=history.sessions),
|
||||
)
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-1")
|
||||
channel._persist_turn_transcript_event = MagicMock(return_value=True)
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
await channel.send(await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
@@ -3470,7 +3499,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()
|
||||
assert history.read("websocket:chat-1") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.channels.websocket import runtime
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
@@ -64,7 +65,7 @@ class _RecordingConnection:
|
||||
await self.release_close.wait()
|
||||
|
||||
|
||||
def _channel() -> WebSocketChannel:
|
||||
def _channel(session_manager: SessionManager | None = None) -> WebSocketChannel:
|
||||
bus = MessageBus()
|
||||
config = WebSocketConfig(
|
||||
enabled=True,
|
||||
@@ -74,7 +75,7 @@ def _channel() -> WebSocketChannel:
|
||||
gateway = build_gateway_services(
|
||||
config=config,
|
||||
bus=bus,
|
||||
session_manager=None,
|
||||
session_manager=session_manager,
|
||||
static_dist_path=None,
|
||||
workspace_path=Path.cwd(),
|
||||
default_restrict_to_workspace=False,
|
||||
@@ -82,10 +83,7 @@ def _channel() -> WebSocketChannel:
|
||||
runtime_surface="tui",
|
||||
runtime_capabilities_overrides=None,
|
||||
)
|
||||
channel = WebSocketChannel(config, bus, gateway=gateway)
|
||||
# Keep disk latency out of every connection delivery synchronization check.
|
||||
channel._persist_turn_transcript_event = AsyncMock(return_value=True)
|
||||
return channel
|
||||
return WebSocketChannel(config, bus, gateway=gateway)
|
||||
|
||||
|
||||
def _message(chat_id: str, text: str) -> OutboundMessage:
|
||||
@@ -218,6 +216,49 @@ async def test_slow_tui_does_not_block_same_topic_fanout() -> None:
|
||||
await channel._cleanup_connection(cast(Any, healthy))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_recipients_are_snapshotted_before_history_append(history, monkeypatch) -> None:
|
||||
channel = _channel(history.sessions)
|
||||
first_connection = _RecordingConnection()
|
||||
late_connection = _RecordingConnection()
|
||||
channel._attach(cast(Any, first_connection), "chat-snapshot")
|
||||
first_message = await history.message(
|
||||
channel="websocket", chat_id="chat-snapshot", content="first",
|
||||
)
|
||||
append_started = asyncio.Event()
|
||||
release_append = asyncio.Event()
|
||||
append_history = history.sessions.state.append_history
|
||||
|
||||
async def blocked_append(*args, **kwargs):
|
||||
append_started.set()
|
||||
await release_append.wait()
|
||||
return await append_history(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(history.sessions.state, "append_history", blocked_append)
|
||||
sending = asyncio.create_task(channel.send(first_message))
|
||||
try:
|
||||
await asyncio.wait_for(append_started.wait(), timeout=1)
|
||||
channel._attach(cast(Any, late_connection), "chat-snapshot")
|
||||
release_append.set()
|
||||
await asyncio.wait_for(sending, timeout=1)
|
||||
assert await _next_text(first_connection) == "first"
|
||||
|
||||
await channel.send(await history.message(
|
||||
channel="websocket", chat_id="chat-snapshot", content="second",
|
||||
))
|
||||
assert await _next_text(first_connection) == "second"
|
||||
assert await _next_text(late_connection) == "second"
|
||||
assert late_connection.sent.empty()
|
||||
assert [record["text"] for record in history.read("websocket:chat-snapshot")] == [
|
||||
"first", "second",
|
||||
]
|
||||
finally:
|
||||
release_append.set()
|
||||
await asyncio.gather(sending, return_exceptions=True)
|
||||
await channel._cleanup_connection(cast(Any, first_connection))
|
||||
await channel._cleanup_connection(cast(Any, late_connection))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connection_writer_preserves_order_without_concurrent_sends() -> None:
|
||||
channel = _channel()
|
||||
@@ -483,15 +524,15 @@ async def test_normal_cleanup_can_overlap_connection_retirement(monkeypatch) ->
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("user_shell", [True, False])
|
||||
async def test_shell_output_is_literal_without_changing_other_command_replies(
|
||||
user_shell: bool, monkeypatch: pytest.MonkeyPatch,
|
||||
history, user_shell: bool, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
channel = _channel()
|
||||
channel = _channel(history.sessions)
|
||||
connection = _RecordingConnection()
|
||||
channel._attach(cast(Any, connection), "shell-output")
|
||||
output = "Path\n----\n __pycache__\n```mermaid\nflowchart LR\n```\n\n"
|
||||
rewritten = output.replace("local.png", "/api/media/signed")
|
||||
monkeypatch.setattr(channel._media, "rewrite_local_markdown_images", lambda text: rewritten)
|
||||
message = OutboundMessage(
|
||||
monkeypatch.setattr(channel.gateway.media, "rewrite_local_markdown_images", lambda text: rewritten)
|
||||
message = await history.message(
|
||||
channel="websocket", chat_id="shell-output", content=output,
|
||||
metadata={"render_as": "text", INBOUND_META_USER_SHELL: user_shell},
|
||||
)
|
||||
@@ -500,9 +541,10 @@ async def test_shell_output_is_literal_without_changing_other_command_replies(
|
||||
payload = json.loads(await asyncio.wait_for(connection.sent.get(), timeout=1))
|
||||
assert payload["text"] == (output if user_shell else rewritten)
|
||||
assert payload.get("render_as") == ("text" if user_shell else None)
|
||||
persisted = channel._persist_turn_transcript_event.await_args
|
||||
assert persisted.args[1] == payload
|
||||
assert persisted.kwargs["transcript_overrides"] == {"text": output}
|
||||
[persisted] = history.read("websocket:shell-output")
|
||||
assert persisted["event"] == "message"
|
||||
assert persisted["text"] == output
|
||||
assert persisted.get("render_as") == ("text" if user_shell else None)
|
||||
assert message.content == output
|
||||
finally:
|
||||
await channel._cleanup_connection(cast(Any, connection))
|
||||
@@ -1,63 +1,70 @@
|
||||
"""Test websocket subscribe hydration only replays known active turns."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import json
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel
|
||||
from nanobot.webui.outbound_projection import WebUIOutboundProjector
|
||||
from nanobot.webui.session_projection import WebUISessionProjection
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
from nanobot.webui.outbound_delivery import WebUIOutboundDelivery
|
||||
|
||||
|
||||
class _RecordingTransport:
|
||||
def __init__(self) -> None:
|
||||
self.connection = MagicMock(spec=ServerConnection)
|
||||
self.frames: list[dict[str, Any]] = []
|
||||
|
||||
def webui_recipients(self, audience: object) -> tuple[ServerConnection, ...]:
|
||||
return (self.connection,)
|
||||
|
||||
async def webui_send_raw(
|
||||
self, connection: ServerConnection, raw: str, *, label: str = "",
|
||||
) -> None:
|
||||
self.frames.append(json.loads(raw))
|
||||
|
||||
|
||||
def _delivery(history, tmp_path) -> tuple[WebUIOutboundDelivery, _RecordingTransport]:
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(allow_from=["*"], websocket_requires_token=False),
|
||||
bus=MessageBus(),
|
||||
session_manager=history.sessions,
|
||||
static_dist_path=None,
|
||||
workspace_path=tmp_path,
|
||||
default_restrict_to_workspace=False,
|
||||
runtime_model_name=None,
|
||||
runtime_surface="browser",
|
||||
runtime_capabilities_overrides=None,
|
||||
)
|
||||
transport = _RecordingTransport()
|
||||
outbound = WebUIOutboundDelivery(
|
||||
transport,
|
||||
media=gateway.media,
|
||||
transcripts=gateway.transcripts,
|
||||
temporary_chats=gateway.temporary_chats,
|
||||
session_projection=gateway.session_projection,
|
||||
)
|
||||
return outbound, transport
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hydrate_after_subscribe_is_quiet_when_no_turn_active():
|
||||
async def test_subscribe_hydration_is_quiet_when_no_turn_active(history, tmp_path):
|
||||
"""Subscribe hydration must not inject an idle event into normal message order."""
|
||||
channel = WebSocketChannel.__new__(WebSocketChannel)
|
||||
channel.gateway = MagicMock()
|
||||
channel.gateway.session_manager = MagicMock()
|
||||
channel.gateway.session_manager.state.read_metadata = AsyncMock(return_value={})
|
||||
channel._session_projection = WebUISessionProjection(channel.gateway.session_manager)
|
||||
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
|
||||
channel._turn_models = {}
|
||||
|
||||
sent_events = []
|
||||
|
||||
async def mock_send_goal_state(chat_id, blob):
|
||||
sent_events.append(("goal_state", chat_id, blob))
|
||||
|
||||
async def mock_send_goal_status(chat_id, status, **kwargs):
|
||||
sent_events.append(("goal_status", chat_id, status, kwargs))
|
||||
|
||||
channel.send_goal_state = mock_send_goal_state
|
||||
channel.send_goal_status = mock_send_goal_status
|
||||
outbound, transport = _delivery(history, tmp_path)
|
||||
|
||||
with patch("nanobot.webui.session_projection.websocket_turn_wall_started_at", return_value=None):
|
||||
await channel._hydrate_after_subscribe("test-chat")
|
||||
await outbound.hydrate("test-chat")
|
||||
|
||||
assert sent_events == []
|
||||
assert transport.frames == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hydrate_after_subscribe_pushes_running_when_turn_active():
|
||||
async def test_subscribe_hydration_pushes_running_when_turn_active(history, tmp_path):
|
||||
"""Reconnecting client should receive running status when turn is active."""
|
||||
channel = WebSocketChannel.__new__(WebSocketChannel)
|
||||
channel.gateway = MagicMock()
|
||||
channel.gateway.session_manager = MagicMock()
|
||||
channel.gateway.session_manager.state.read_metadata = AsyncMock(return_value={})
|
||||
channel._session_projection = WebUISessionProjection(channel.gateway.session_manager)
|
||||
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
|
||||
channel._turn_models = {}
|
||||
|
||||
sent_events = []
|
||||
|
||||
async def mock_send_goal_state(chat_id, blob):
|
||||
sent_events.append(("goal_state", chat_id, blob))
|
||||
|
||||
async def mock_send_goal_status(chat_id, status, **kwargs):
|
||||
sent_events.append(("goal_status", chat_id, status, kwargs))
|
||||
|
||||
channel.send_goal_state = mock_send_goal_state
|
||||
channel.send_goal_status = mock_send_goal_status
|
||||
outbound, transport = _delivery(history, tmp_path)
|
||||
|
||||
with (
|
||||
patch(
|
||||
@@ -69,9 +76,12 @@ async def test_hydrate_after_subscribe_pushes_running_when_turn_active():
|
||||
return_value="turn-active",
|
||||
),
|
||||
):
|
||||
await channel._hydrate_after_subscribe("test-chat")
|
||||
await outbound.hydrate("test-chat")
|
||||
|
||||
running_events = [e for e in sent_events if e[0] == "goal_status" and e[2] == "running"]
|
||||
assert len(running_events) == 1
|
||||
assert running_events[0][3]["started_at"] == 1234567890.0
|
||||
assert running_events[0][3]["turn_id"] == "turn-active"
|
||||
assert transport.frames == [{
|
||||
"event": "goal_status",
|
||||
"chat_id": "test-chat",
|
||||
"status": "running",
|
||||
"started_at": 1234567890.0,
|
||||
"turn_id": "turn-active",
|
||||
}]
|
||||
@@ -10,7 +10,7 @@ import time
|
||||
import uuid
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol, cast
|
||||
from typing import TYPE_CHECKING, Any, Protocol, cast
|
||||
|
||||
from loguru import logger
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
@@ -66,6 +66,9 @@ from nanobot.webui.sidebar_state import write_webui_sidebar_state
|
||||
from nanobot.webui.temporary_chats import TemporaryChatError
|
||||
from nanobot.webui.transcription_ws import webui_transcription_event
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.webui.outbound_delivery import WebUIOutboundDelivery
|
||||
|
||||
_WEBUI_REQUEST_CACHE_TTL_S = 5 * 60.0
|
||||
_WEBUI_REQUEST_CACHE_MAX = 256
|
||||
|
||||
@@ -100,10 +103,6 @@ class WebUICommandTransport(Protocol):
|
||||
|
||||
def webui_clear_connection_default(self, connection: ServerConnection) -> None: ...
|
||||
|
||||
def webui_clear_stream_buffers(self, chat_id: str) -> None: ...
|
||||
|
||||
async def webui_hydrate(self, chat_id: str) -> None: ...
|
||||
|
||||
async def webui_send_event(
|
||||
self,
|
||||
connection: ServerConnection,
|
||||
@@ -133,19 +132,15 @@ class WebUICommandTransport(Protocol):
|
||||
session_generation: str | None,
|
||||
) -> None: ...
|
||||
|
||||
async def send_session_updated(
|
||||
self,
|
||||
chat_id: str,
|
||||
*,
|
||||
scope: str | None = None,
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class WebUICommandRouter:
|
||||
"""Own WebUI command semantics while a transport host owns raw connections."""
|
||||
|
||||
def __init__(self, transport: WebUICommandTransport, gateway: GatewayServices) -> None:
|
||||
def __init__(
|
||||
self, transport: WebUICommandTransport, gateway: GatewayServices, *, outbound: WebUIOutboundDelivery,
|
||||
) -> None:
|
||||
self._transport = transport
|
||||
self._outbound = outbound
|
||||
self.gateway = gateway
|
||||
self._http_router = gateway.http
|
||||
self._media = gateway.media
|
||||
@@ -202,7 +197,7 @@ class WebUICommandRouter:
|
||||
scope="metadata",
|
||||
workspace_scope=scope.payload(),
|
||||
)
|
||||
await self._transport.webui_hydrate(fork_id)
|
||||
await self._outbound.hydrate(fork_id)
|
||||
|
||||
async def discard_owned_chat(
|
||||
self,
|
||||
@@ -212,7 +207,7 @@ class WebUICommandRouter:
|
||||
await self._temporary_chats.discard(connection, chat_id)
|
||||
self._transport.webui_detach(connection, chat_id)
|
||||
clear_websocket_turns(chat_id)
|
||||
self._transport.webui_clear_stream_buffers(chat_id)
|
||||
self._outbound.discard(chat_id)
|
||||
|
||||
async def cleanup_connection(self, connection: ServerConnection) -> None:
|
||||
"""Release command-owned state associated with one transport connection."""
|
||||
@@ -330,7 +325,7 @@ class WebUICommandRouter:
|
||||
scope="metadata",
|
||||
workspace_scope=scope.payload(),
|
||||
)
|
||||
await self._transport.webui_hydrate(new_id)
|
||||
await self._outbound.hydrate(new_id)
|
||||
return
|
||||
if command_type == "new_temporary_chat":
|
||||
try:
|
||||
@@ -397,7 +392,7 @@ class WebUICommandRouter:
|
||||
chat_id=chat_id,
|
||||
**(await self._session_projection.attach_fields(webui_session_key(chat_id))),
|
||||
)
|
||||
await self._transport.webui_hydrate(chat_id)
|
||||
await self._outbound.hydrate(chat_id)
|
||||
return
|
||||
if command_type == "set_sidebar_state":
|
||||
if connection not in self._webui_connections:
|
||||
@@ -460,7 +455,7 @@ class WebUICommandRouter:
|
||||
connection, lambda: self._workspaces.stage_scope(chat_id, scope), chat_id=chat_id,
|
||||
) is None:
|
||||
return
|
||||
await self._transport.send_session_updated(chat_id, scope="metadata")
|
||||
await self._outbound.session_updated(chat_id, scope="metadata")
|
||||
await self._transport.webui_send_event(
|
||||
connection,
|
||||
"session_updated",
|
||||
@@ -630,7 +625,7 @@ class WebUICommandRouter:
|
||||
return
|
||||
self._transport.webui_attach(connection, chat_id)
|
||||
if temporary_policy is None or temporary_policy.hydrate_transcript:
|
||||
await self._transport.webui_hydrate(chat_id)
|
||||
await self._outbound.hydrate(chat_id)
|
||||
|
||||
scope = temporary_policy.workspace_scope if temporary_policy is not None else (
|
||||
await self.workspace_scope_or_error(
|
||||
@@ -871,7 +866,7 @@ class WebUICommandRouter:
|
||||
attachment["name"] = name
|
||||
if is_webui and not restart_control:
|
||||
if session_created:
|
||||
await self._transport.send_session_updated(chat_id, scope="metadata")
|
||||
await self._outbound.session_updated(chat_id, scope="metadata")
|
||||
await self.broadcast_user_message(
|
||||
connection,
|
||||
chat_id,
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
"""Own WebUI outbound projection, stream state and durable delivery completion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.bus.events import INBOUND_META_USER_SHELL, OUTBOUND_META_AGENT_UI, OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
GoalStateSyncEvent,
|
||||
GoalStatusEvent,
|
||||
ProgressEvent,
|
||||
RetryStatusEvent,
|
||||
RetryWaitEvent,
|
||||
RuntimeModelUpdatedEvent,
|
||||
SessionUpdatedEvent,
|
||||
TurnEndEvent,
|
||||
TurnModelUpdatedEvent,
|
||||
UserInputEvent,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import SubagentTaskChanged
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
mark_websocket_turn_transcript_persistence_failed,
|
||||
websocket_turn_transcript_persistence_failed,
|
||||
)
|
||||
from nanobot.webui.media_gateway import WebUIMediaGateway
|
||||
from nanobot.webui.metadata import (
|
||||
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
||||
WEBUI_RESTART_CONTROL_METADATA_KEY,
|
||||
WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
|
||||
WEBUI_TURN_METADATA_KEY,
|
||||
)
|
||||
from nanobot.webui.outbound_wire import (
|
||||
FileEditWirePayload,
|
||||
GoalStateWirePayload,
|
||||
GoalStatusWirePayload,
|
||||
MessageWirePayload,
|
||||
RuntimeModelWirePayload,
|
||||
SessionUpdatedWirePayload,
|
||||
StreamWirePayload,
|
||||
TurnModelWirePayload,
|
||||
UserInputWirePayload,
|
||||
WebUIWirePayload,
|
||||
WebUIWirePersistence,
|
||||
encode_turn_end,
|
||||
project_notification,
|
||||
project_tool_events,
|
||||
)
|
||||
from nanobot.webui.session_identity import webui_session_key
|
||||
from nanobot.webui.session_projection import WebUISessionProjection
|
||||
from nanobot.webui.temporary_chats import WebUITemporaryChats
|
||||
from nanobot.webui.transcript import WEBUI_TRANSCRIPT_INCOMPLETE_KEY, WebUITranscriptRecorder
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChatAudience:
|
||||
chat_id: str
|
||||
|
||||
|
||||
WebUIAudience: TypeAlias = ChatAudience | Literal["all_connections", "authenticated_webui"]
|
||||
|
||||
|
||||
class WebUIOutboundTransport(Protocol):
|
||||
"""Snapshot recipients and enqueue already projected public JSON frames."""
|
||||
|
||||
def webui_recipients(self, audience: WebUIAudience) -> tuple[ServerConnection, ...]: ...
|
||||
|
||||
async def webui_send_raw(
|
||||
self, connection: ServerConnection, raw: str, *, label: str = "",
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class WebUIOutboundDelivery:
|
||||
"""Keep presentation, history and delivery-turn policy out of socket writers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
transport: WebUIOutboundTransport,
|
||||
*,
|
||||
media: WebUIMediaGateway,
|
||||
transcripts: WebUITranscriptRecorder,
|
||||
temporary_chats: WebUITemporaryChats,
|
||||
session_projection: WebUISessionProjection,
|
||||
) -> None:
|
||||
self._transport = transport
|
||||
self._media = media
|
||||
self._transcripts = transcripts
|
||||
self._temporary_chats = temporary_chats
|
||||
self._session_projection = session_projection
|
||||
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
|
||||
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
|
||||
|
||||
async def initialize(self) -> None:
|
||||
await self._transcripts.initialize()
|
||||
|
||||
def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]:
|
||||
async def queue_changed(event: PairingChanged) -> None:
|
||||
await bus.publish_event(event, channel=channel, chat_id="*")
|
||||
|
||||
return bus.subscribe(queue_changed, PairingChanged)
|
||||
|
||||
def discard(self, chat_id: str) -> None:
|
||||
"""Forget unclosed streams when a turn ends or its chat is discarded."""
|
||||
for buffers in (self._stream_text_buffers, self._reasoning_text_buffers):
|
||||
for key in tuple(buffers):
|
||||
if key[0] == chat_id:
|
||||
buffers.pop(key, None)
|
||||
|
||||
async def hydrate(self, chat_id: str) -> None:
|
||||
for event in await self._session_projection.hydration_events(
|
||||
webui_session_key(chat_id), chat_id,
|
||||
):
|
||||
if event["event"] == "goal_state":
|
||||
await self._send_goal_state(chat_id, event["goal_state"])
|
||||
else:
|
||||
await self._send_goal_status(
|
||||
chat_id, "running", started_at=event["started_at"], turn_id=event.get("turn_id"),
|
||||
)
|
||||
|
||||
async def _fanout(
|
||||
self,
|
||||
recipients: tuple[ServerConnection, ...],
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
label: str,
|
||||
) -> None:
|
||||
raw = json.dumps(payload, ensure_ascii=False)
|
||||
for connection in recipients:
|
||||
await self._transport.webui_send_raw(connection, raw, label=label)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
event = msg.event
|
||||
if isinstance(event, PairingChanged):
|
||||
await self._fanout(
|
||||
self._transport.webui_recipients("authenticated_webui"),
|
||||
{"event": "pairing_changed"},
|
||||
label=" pairing_changed ",
|
||||
)
|
||||
return
|
||||
if isinstance(event, RetryWaitEvent):
|
||||
return
|
||||
if isinstance(event, RuntimeModelUpdatedEvent):
|
||||
await self._send_runtime_model_updated(event.model, event.model_preset)
|
||||
return
|
||||
|
||||
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
|
||||
if not recipients:
|
||||
quiet_events = (
|
||||
ProgressEvent, RetryStatusEvent, UserInputEvent, TurnEndEvent, SessionUpdatedEvent,
|
||||
GoalStatusEvent, GoalStateSyncEvent, SubagentTaskChanged, ContextCompactionEvent,
|
||||
)
|
||||
log = logger.debug if isinstance(event, quiet_events) else logger.warning
|
||||
log("no active subscribers for chat_id={}", msg.chat_id)
|
||||
|
||||
if isinstance(event, TurnModelUpdatedEvent):
|
||||
if recipients:
|
||||
await self._send_turn_model_updated(msg.chat_id, event)
|
||||
return
|
||||
if isinstance(event, UserInputEvent):
|
||||
if recipients:
|
||||
body: UserInputWirePayload = {
|
||||
"event": "user_message", "chat_id": msg.chat_id, "text": event.content,
|
||||
"created_at_ms": event.created_at_ms, "starts_turn": False,
|
||||
}
|
||||
if event.provenance:
|
||||
body["provenance"] = event.provenance
|
||||
await self._fanout(recipients, body, label=" user_message ")
|
||||
return
|
||||
notification = project_notification(msg.chat_id, event, msg.metadata)
|
||||
if notification is not None:
|
||||
if recipients or notification.deliver_offline:
|
||||
await self._send_payload(
|
||||
msg.chat_id, notification.payload, persistence=notification.persistence,
|
||||
metadata=msg.metadata if notification.attach_turn_metadata else None,
|
||||
)
|
||||
return
|
||||
if isinstance(event, GoalStateSyncEvent):
|
||||
if recipients:
|
||||
await self._send_goal_state(msg.chat_id, event.goal_state or {"active": False})
|
||||
return
|
||||
if isinstance(event, GoalStatusEvent):
|
||||
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
|
||||
turn_owner = msg.metadata.get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
||||
owner = turn_owner if isinstance(turn_owner, str) else None
|
||||
try:
|
||||
if recipients and event.status in ("running", "idle"):
|
||||
await self._send_goal_status(
|
||||
msg.chat_id, event.status, started_at=event.started_at,
|
||||
turn_id=turn_id if isinstance(turn_id, str) else None,
|
||||
)
|
||||
finally:
|
||||
if event.status == "idle":
|
||||
clear_websocket_turn_if_current(
|
||||
msg.chat_id, owner, preserve_persistence_failure=True,
|
||||
)
|
||||
return
|
||||
if isinstance(event, TurnEndEvent):
|
||||
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
|
||||
scope = (
|
||||
"metadata" if isinstance(turn_id, str)
|
||||
and turn_id.startswith(WEBUI_SYSTEM_COMMAND_TURN_PREFIX) else "thread"
|
||||
)
|
||||
turn_owner = msg.metadata.get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
||||
await self._send_payload(
|
||||
msg.chat_id, 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,
|
||||
)
|
||||
await self.session_updated(msg.chat_id, scope=scope)
|
||||
return
|
||||
if isinstance(event, SubagentTaskChanged):
|
||||
if recipients:
|
||||
task = self._session_projection.subagent_task(webui_session_key(msg.chat_id), event.task_id)
|
||||
if task is not None:
|
||||
await self._send_payload(
|
||||
msg.chat_id, {"event": "subagent_task", "chat_id": msg.chat_id, "task": task},
|
||||
persistence="transient",
|
||||
)
|
||||
return
|
||||
if isinstance(event, SessionUpdatedEvent):
|
||||
if recipients:
|
||||
await self.session_updated(msg.chat_id, scope=event.scope)
|
||||
return
|
||||
progress = event if isinstance(event, ProgressEvent) else None
|
||||
if progress and progress.file_edit_events:
|
||||
await self.send_file_edit_events(msg.chat_id, progress.file_edit_events, msg.metadata)
|
||||
return
|
||||
await self._send_message(msg, progress)
|
||||
|
||||
async def _persist_turn_transcript_event(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str,
|
||||
include_source: bool = False,
|
||||
transcript_overrides: dict[str, Any] | None = None,
|
||||
) -> bool:
|
||||
if (
|
||||
(metadata or {}).get(WEBUI_RESTART_CONTROL_METADATA_KEY) is True
|
||||
or not self._temporary_chats.should_persist_transcript(chat_id)
|
||||
):
|
||||
self._transcripts.prepare_event(
|
||||
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
|
||||
)
|
||||
return True
|
||||
persisted = await self._transcripts.prepare_and_append(
|
||||
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
|
||||
transcript_overrides=transcript_overrides,
|
||||
)
|
||||
return self._retain_turn_on_transcript_failure(
|
||||
chat_id, persisted=persisted, metadata=metadata, phase=phase,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _retain_turn_on_transcript_failure(
|
||||
chat_id: str,
|
||||
*,
|
||||
persisted: bool,
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str,
|
||||
) -> bool:
|
||||
if not persisted and phase in {"answer", "complete"} and (metadata or {}).get("webui") is True:
|
||||
owner = (metadata or {}).get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
||||
mark_websocket_turn_transcript_persistence_failed(
|
||||
chat_id, owner if isinstance(owner, str) else None,
|
||||
)
|
||||
return persisted
|
||||
|
||||
async def _persist_turn_stream_event(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
completed_text: str | None,
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str,
|
||||
include_source: bool = False,
|
||||
) -> bool:
|
||||
if not self._temporary_chats.should_persist_transcript(chat_id):
|
||||
self._transcripts.prepare_event(
|
||||
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
|
||||
)
|
||||
return True
|
||||
persisted = await self._transcripts.prepare_and_append_stream_event(
|
||||
chat_id, event, completed_text=completed_text, metadata=metadata,
|
||||
phase=phase, include_source=include_source,
|
||||
)
|
||||
return self._retain_turn_on_transcript_failure(
|
||||
chat_id, persisted=persisted, metadata=metadata, phase=phase,
|
||||
)
|
||||
|
||||
async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
|
||||
text = msg.content
|
||||
user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True
|
||||
payload: MessageWirePayload = {
|
||||
"event": "message", "chat_id": msg.chat_id,
|
||||
"text": text if user_shell else self._media.rewrite_local_markdown_images(text),
|
||||
}
|
||||
if user_shell:
|
||||
payload["render_as"] = "text"
|
||||
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
|
||||
if isinstance(turn_id, str) and turn_id:
|
||||
payload["turn_id"] = turn_id
|
||||
if msg.media:
|
||||
payload["media"] = msg.media
|
||||
urls: list[dict[str, str]] = []
|
||||
for entry in msg.media:
|
||||
signed = self._media.sign_or_stage_media_path(Path(entry))
|
||||
if signed is not None:
|
||||
urls.append(signed)
|
||||
if urls:
|
||||
payload["media_urls"] = urls
|
||||
if msg.reply_to:
|
||||
payload["reply_to"] = msg.reply_to
|
||||
latency = msg.metadata.get("latency_ms")
|
||||
if isinstance(latency, (int, float)):
|
||||
payload["latency_ms"] = int(latency)
|
||||
if progress and progress.tool_events:
|
||||
payload["tool_events"] = project_tool_events(progress.tool_events)
|
||||
agent_ui = msg.metadata.get(OUTBOUND_META_AGENT_UI)
|
||||
if agent_ui is not None:
|
||||
payload["agent_ui"] = agent_ui
|
||||
if progress:
|
||||
payload["kind"] = "tool_hint" if progress.tool_hint else "progress"
|
||||
body: dict[str, Any] = dict(payload)
|
||||
await self._persist_turn_transcript_event(
|
||||
msg.chat_id, body, metadata=msg.metadata,
|
||||
phase="activity" if progress else "answer", include_source=True,
|
||||
transcript_overrides={"text": text},
|
||||
)
|
||||
await self._fanout(recipients, body, label=" ")
|
||||
|
||||
async def send_reasoning_delta(
|
||||
self, chat_id: str, delta: str, metadata: dict[str, Any] | None = None,
|
||||
*, stream_id: str | None = None,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
if not delta:
|
||||
return
|
||||
payload: StreamWirePayload = {"event": "reasoning_delta", "chat_id": chat_id, "text": delta}
|
||||
if stream_id is not None:
|
||||
payload["stream_id"] = stream_id
|
||||
self._reasoning_text_buffers.setdefault((chat_id, str(stream_id or "")), []).append(delta)
|
||||
body: dict[str, Any] = dict(payload)
|
||||
await self._persist_turn_stream_event(
|
||||
chat_id, body, completed_text=None, metadata=metadata or {}, phase="reasoning",
|
||||
)
|
||||
await self._fanout(recipients, body, label=" reasoning ")
|
||||
|
||||
async def send_reasoning_end(
|
||||
self, chat_id: str, metadata: dict[str, Any] | None = None,
|
||||
*, stream_id: str | None = None,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
payload: StreamWirePayload = {"event": "reasoning_end", "chat_id": chat_id}
|
||||
if stream_id is not None:
|
||||
payload["stream_id"] = stream_id
|
||||
text = "".join(self._reasoning_text_buffers.pop((chat_id, str(stream_id or "")), []))
|
||||
body: dict[str, Any] = dict(payload)
|
||||
await self._persist_turn_stream_event(
|
||||
chat_id, body, completed_text=text or None, metadata=metadata or {}, phase="reasoning",
|
||||
)
|
||||
await self._fanout(recipients, body, label=" reasoning_end ")
|
||||
|
||||
async def send_file_edit_events(
|
||||
self, chat_id: str, edits: list[dict[str, Any]], metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
payload: FileEditWirePayload = {"event": "file_edit", "chat_id": chat_id, "edits": edits}
|
||||
body: dict[str, Any] = dict(payload)
|
||||
await self._persist_turn_transcript_event(chat_id, body, metadata=metadata, phase="activity")
|
||||
await self._fanout(recipients, body, label=" file_edit ")
|
||||
|
||||
async def send_delta(
|
||||
self,
|
||||
chat_id: str,
|
||||
delta: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
*,
|
||||
stream_id: str | None = None,
|
||||
stream_end: bool = False,
|
||||
resuming: bool = False,
|
||||
merge_next: bool = False,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
stream_key = (chat_id, str(stream_id or ""))
|
||||
completed_text: str | None = None
|
||||
payload: StreamWirePayload
|
||||
if stream_end:
|
||||
payload = {"event": "stream_end", "chat_id": chat_id}
|
||||
buffered = (
|
||||
self._stream_text_buffers.setdefault(stream_key, [])
|
||||
if merge_next else self._stream_text_buffers.pop(stream_key, [])
|
||||
)
|
||||
if delta:
|
||||
buffered.append(delta)
|
||||
full_text = "".join(buffered)
|
||||
rewritten = self._media.rewrite_local_markdown_images(full_text)
|
||||
completed_text = rewritten
|
||||
if delta or rewritten != full_text:
|
||||
payload["text"] = rewritten
|
||||
else:
|
||||
payload = {"event": "delta", "chat_id": chat_id, "text": delta}
|
||||
self._stream_text_buffers.setdefault(stream_key, []).append(delta)
|
||||
if stream_id is not None:
|
||||
payload["stream_id"] = stream_id
|
||||
if stream_end and resuming:
|
||||
payload["resuming"] = True
|
||||
if stream_end and merge_next:
|
||||
payload["merge_next"] = True
|
||||
body: dict[str, Any] = dict(payload)
|
||||
await self._persist_turn_stream_event(
|
||||
chat_id, body, completed_text=completed_text, metadata=metadata or {},
|
||||
phase="answer", include_source=True,
|
||||
)
|
||||
await self._fanout(recipients, body, label=" stream ")
|
||||
|
||||
async def _send_payload(
|
||||
self,
|
||||
chat_id: str,
|
||||
payload: WebUIWirePayload,
|
||||
*,
|
||||
persistence: WebUIWirePersistence,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
turn_owner: str | None = None,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
body: dict[str, Any] = dict(payload)
|
||||
if persistence == "turn_activity":
|
||||
await self._persist_turn_transcript_event(chat_id, body, metadata=metadata, phase="activity")
|
||||
elif persistence == "turn_complete":
|
||||
prior_failure = (
|
||||
(metadata or {}).get("webui") is True
|
||||
and websocket_turn_transcript_persistence_failed(chat_id, turn_owner)
|
||||
)
|
||||
persisted = await self._persist_turn_transcript_event(
|
||||
chat_id, body, metadata=metadata, phase="complete",
|
||||
transcript_overrides={WEBUI_TRANSCRIPT_INCOMPLETE_KEY: True} if prior_failure else None,
|
||||
)
|
||||
if persisted:
|
||||
# A durable incomplete marker allows HTTP recovery after restart.
|
||||
clear_websocket_turn_if_current(chat_id, turn_owner)
|
||||
self.discard(chat_id)
|
||||
await self._fanout(recipients, body, label=f" {body['event']} ")
|
||||
|
||||
async def _send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
if recipients:
|
||||
payload: GoalStateWirePayload = {"event": "goal_state", "chat_id": chat_id, "goal_state": blob}
|
||||
await self._fanout(recipients, payload, label=" goal_state ")
|
||||
|
||||
async def _send_goal_status(
|
||||
self, chat_id: str, status: str, *, started_at: float | None = None, turn_id: str | None = None,
|
||||
) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
if not recipients:
|
||||
return
|
||||
payload: GoalStatusWirePayload = {"event": "goal_status", "chat_id": chat_id, "status": status}
|
||||
if status == "running" and started_at is not None:
|
||||
payload["started_at"] = started_at
|
||||
if turn_id:
|
||||
payload["turn_id"] = turn_id
|
||||
await self._fanout(recipients, payload, label=" goal_status ")
|
||||
|
||||
async def session_updated(self, chat_id: str, *, scope: str | None = None) -> None:
|
||||
recipients = self._transport.webui_recipients("all_connections")
|
||||
if not recipients:
|
||||
return
|
||||
payload: SessionUpdatedWirePayload = {"event": "session_updated", "chat_id": chat_id}
|
||||
if scope:
|
||||
payload["scope"] = scope
|
||||
await self._fanout(recipients, payload, label=" session_updated ")
|
||||
|
||||
async def _send_runtime_model_updated(self, model_name: str | None, model_preset: str | None) -> None:
|
||||
recipients = self._transport.webui_recipients("all_connections")
|
||||
if not recipients or not isinstance(model_name, str) or not model_name.strip():
|
||||
return
|
||||
payload: RuntimeModelWirePayload = {"event": "runtime_model_updated", "model_name": model_name.strip()}
|
||||
if isinstance(model_preset, str) and model_preset.strip():
|
||||
payload["model_preset"] = model_preset.strip()
|
||||
await self._fanout(recipients, payload, label=" runtime_model_updated ")
|
||||
|
||||
async def _send_turn_model_updated(self, chat_id: str, event: TurnModelUpdatedEvent) -> None:
|
||||
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
|
||||
if not recipients or not event.model.strip():
|
||||
return
|
||||
payload: TurnModelWirePayload = {
|
||||
"event": "turn_model_updated", "chat_id": chat_id, "model_name": event.model.strip(),
|
||||
}
|
||||
if isinstance(event.model_preset, str) and event.model_preset.strip():
|
||||
payload["model_preset"] = event.model_preset.strip()
|
||||
if isinstance(event.context_window_tokens, int) and event.context_window_tokens > 0:
|
||||
payload["context_window_tokens"] = event.context_window_tokens
|
||||
if event.fallback:
|
||||
payload["fallback"] = True
|
||||
if event.reauth_provider:
|
||||
payload["reauth_provider"] = event.reauth_provider
|
||||
await self._fanout(recipients, payload, label=" turn_model_updated ")
|
||||
@@ -1,276 +0,0 @@
|
||||
"""Project agent runtime events onto the WebUI wire protocol."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Protocol
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
GoalStateSyncEvent,
|
||||
GoalStatusEvent,
|
||||
ProgressEvent,
|
||||
RetryStatusEvent,
|
||||
RetryWaitEvent,
|
||||
RuntimeModelUpdatedEvent,
|
||||
SessionUpdatedEvent,
|
||||
TurnEndEvent,
|
||||
TurnModelUpdatedEvent,
|
||||
UserInputEvent,
|
||||
)
|
||||
from nanobot.bus.runtime_events import SubagentTaskChanged
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.session.webui_turns import clear_websocket_turn_if_current
|
||||
from nanobot.webui.metadata import (
|
||||
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
||||
WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
|
||||
WEBUI_TURN_METADATA_KEY,
|
||||
)
|
||||
from nanobot.webui.outbound_wire import (
|
||||
WebUIWirePayload,
|
||||
WebUIWirePersistence,
|
||||
encode_turn_end,
|
||||
project_notification,
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
class WebUIOutboundTransport(Protocol):
|
||||
"""Wire operations required by the outbound application projector."""
|
||||
|
||||
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]: ...
|
||||
|
||||
async def send_pairing_changed(self) -> None: ...
|
||||
|
||||
async def send_runtime_model_updated(
|
||||
self,
|
||||
*,
|
||||
model_name: str | None,
|
||||
model_preset: str | None = None,
|
||||
) -> None: ...
|
||||
|
||||
async def send_turn_model_updated(
|
||||
self,
|
||||
chat_id: str,
|
||||
*,
|
||||
model_name: str,
|
||||
model_preset: str | None = None,
|
||||
context_window_tokens: int | None = None,
|
||||
fallback: bool = False,
|
||||
reauth_provider: str | None = None,
|
||||
) -> None: ...
|
||||
|
||||
async def send_user_input(
|
||||
self,
|
||||
chat_id: str,
|
||||
*,
|
||||
content: str,
|
||||
created_at_ms: int,
|
||||
provenance: dict[str, Any],
|
||||
) -> 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_status(
|
||||
self,
|
||||
chat_id: str,
|
||||
status: str,
|
||||
*,
|
||||
started_at: float | None = None,
|
||||
turn_id: str | None = None,
|
||||
) -> None: ...
|
||||
|
||||
async def send_session_updated(self, chat_id: str, *, scope: str | None = None) -> None: ...
|
||||
|
||||
async def send_file_edit_events(
|
||||
self,
|
||||
chat_id: str,
|
||||
edits: list[dict[str, Any]],
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None: ...
|
||||
|
||||
async def send_projected_message(
|
||||
self,
|
||||
msg: OutboundMessage,
|
||||
progress_event: ProgressEvent | None,
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class WebUIOutboundProjector:
|
||||
"""Interpret runtime events without coupling that state machine to the channel."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
transport: WebUIOutboundTransport,
|
||||
session_projection: WebUISessionProjection,
|
||||
) -> None:
|
||||
self._transport = transport
|
||||
self._session_projection = session_projection
|
||||
|
||||
async def hydrate(self, chat_id: str) -> None:
|
||||
"""Replay reconnect state through the existing stable wire operations."""
|
||||
for event in await self._session_projection.hydration_events(
|
||||
webui_session_key(chat_id),
|
||||
chat_id,
|
||||
):
|
||||
if event["event"] == "goal_state":
|
||||
await self._transport.send_goal_state(chat_id, event["goal_state"])
|
||||
continue
|
||||
await self._transport.send_goal_status(
|
||||
chat_id,
|
||||
"running",
|
||||
started_at=event["started_at"],
|
||||
turn_id=event.get("turn_id"),
|
||||
)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
event = msg.event
|
||||
if isinstance(event, PairingChanged):
|
||||
await self._transport.send_pairing_changed()
|
||||
return
|
||||
if isinstance(event, RetryWaitEvent):
|
||||
return
|
||||
progress_event = event if isinstance(event, ProgressEvent) else None
|
||||
if isinstance(event, RuntimeModelUpdatedEvent):
|
||||
await self._transport.send_runtime_model_updated(
|
||||
model_name=event.model,
|
||||
model_preset=event.model_preset,
|
||||
)
|
||||
return
|
||||
|
||||
conns = list(self._transport.webui_subscribers(msg.chat_id))
|
||||
if not conns:
|
||||
quiet_events = (
|
||||
ProgressEvent,
|
||||
RetryStatusEvent,
|
||||
UserInputEvent,
|
||||
TurnEndEvent,
|
||||
SessionUpdatedEvent,
|
||||
GoalStatusEvent,
|
||||
GoalStateSyncEvent,
|
||||
SubagentTaskChanged,
|
||||
ContextCompactionEvent,
|
||||
)
|
||||
log = (
|
||||
logger.debug
|
||||
if isinstance(event, quiet_events)
|
||||
else logger.warning
|
||||
)
|
||||
log("no active subscribers for chat_id={}", msg.chat_id)
|
||||
|
||||
if isinstance(event, TurnModelUpdatedEvent):
|
||||
if conns:
|
||||
await self._transport.send_turn_model_updated(
|
||||
msg.chat_id,
|
||||
model_name=event.model,
|
||||
model_preset=event.model_preset,
|
||||
context_window_tokens=event.context_window_tokens,
|
||||
fallback=event.fallback,
|
||||
reauth_provider=event.reauth_provider,
|
||||
)
|
||||
return
|
||||
if isinstance(event, UserInputEvent):
|
||||
if conns:
|
||||
await self._transport.send_user_input(
|
||||
msg.chat_id,
|
||||
content=event.content,
|
||||
created_at_ms=event.created_at_ms,
|
||||
provenance=event.provenance,
|
||||
)
|
||||
return
|
||||
notification = project_notification(msg.chat_id, event, msg.metadata)
|
||||
if notification is not None:
|
||||
if conns or notification.deliver_offline:
|
||||
kwargs: dict[str, Any] = (
|
||||
{"metadata": msg.metadata} if notification.attach_turn_metadata else {}
|
||||
)
|
||||
await self._transport.send_payload(
|
||||
msg.chat_id, notification.payload,
|
||||
persistence=notification.persistence,
|
||||
**kwargs,
|
||||
)
|
||||
return
|
||||
if isinstance(event, GoalStateSyncEvent):
|
||||
if conns:
|
||||
await self._transport.send_goal_state(
|
||||
msg.chat_id,
|
||||
event.goal_state or {"active": False},
|
||||
)
|
||||
return
|
||||
if isinstance(event, GoalStatusEvent):
|
||||
turn_id = (msg.metadata or {}).get(WEBUI_TURN_METADATA_KEY)
|
||||
current_turn_id = turn_id if isinstance(turn_id, str) else None
|
||||
turn_owner = (msg.metadata or {}).get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
||||
current_turn_owner = turn_owner if isinstance(turn_owner, str) else None
|
||||
try:
|
||||
if conns and event.status in ("running", "idle"):
|
||||
await self._transport.send_goal_status(
|
||||
msg.chat_id,
|
||||
event.status,
|
||||
started_at=event.started_at,
|
||||
turn_id=current_turn_id,
|
||||
)
|
||||
finally:
|
||||
if event.status == "idle":
|
||||
clear_websocket_turn_if_current(
|
||||
msg.chat_id,
|
||||
current_turn_owner,
|
||||
preserve_persistence_failure=True,
|
||||
)
|
||||
return
|
||||
if isinstance(event, TurnEndEvent):
|
||||
turn_id = (msg.metadata or {}).get(WEBUI_TURN_METADATA_KEY)
|
||||
session_update_scope = (
|
||||
"metadata"
|
||||
if isinstance(turn_id, str)
|
||||
and turn_id.startswith(WEBUI_SYSTEM_COMMAND_TURN_PREFIX)
|
||||
else "thread"
|
||||
)
|
||||
turn_owner = (msg.metadata or {}).get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
|
||||
await self._transport.send_payload(
|
||||
msg.chat_id,
|
||||
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,
|
||||
)
|
||||
await self._transport.send_session_updated(msg.chat_id, scope=session_update_scope)
|
||||
return
|
||||
if isinstance(event, SubagentTaskChanged):
|
||||
if conns:
|
||||
task = self._session_projection.subagent_task(webui_session_key(msg.chat_id), event.task_id)
|
||||
if task is not None:
|
||||
await self._transport.send_payload(
|
||||
msg.chat_id,
|
||||
{"event": "subagent_task", "chat_id": msg.chat_id, "task": task},
|
||||
persistence="transient",
|
||||
)
|
||||
return
|
||||
if isinstance(event, SessionUpdatedEvent):
|
||||
if conns:
|
||||
await self._transport.send_session_updated(msg.chat_id, scope=event.scope)
|
||||
return
|
||||
if progress_event and progress_event.file_edit_events:
|
||||
await self._transport.send_file_edit_events(
|
||||
msg.chat_id,
|
||||
progress_event.file_edit_events,
|
||||
msg.metadata,
|
||||
)
|
||||
return
|
||||
await self._transport.send_projected_message(msg, progress_event)
|
||||
@@ -111,9 +111,80 @@ class SubagentTaskWirePayload(_ChatWirePayload):
|
||||
task: dict[str, object]
|
||||
|
||||
|
||||
class MessageWirePayload(_ChatWirePayload):
|
||||
event: Literal["message"]
|
||||
text: str
|
||||
render_as: NotRequired[Literal["text"]]
|
||||
media: NotRequired[list[str]]
|
||||
media_urls: NotRequired[list[dict[str, str]]]
|
||||
reply_to: NotRequired[str]
|
||||
latency_ms: NotRequired[int]
|
||||
tool_events: NotRequired[list[dict[str, _JSONValue]]]
|
||||
agent_ui: NotRequired[object]
|
||||
kind: NotRequired[Literal["tool_hint", "progress"]]
|
||||
|
||||
|
||||
class StreamWirePayload(_ChatWirePayload):
|
||||
event: Literal["delta", "stream_end", "reasoning_delta", "reasoning_end"]
|
||||
text: NotRequired[str]
|
||||
stream_id: NotRequired[str]
|
||||
resuming: NotRequired[bool]
|
||||
merge_next: NotRequired[bool]
|
||||
|
||||
|
||||
class FileEditWirePayload(_ChatWirePayload):
|
||||
event: Literal["file_edit"]
|
||||
edits: list[dict[str, Any]]
|
||||
|
||||
|
||||
class GoalStateWirePayload(_ChatWirePayload):
|
||||
event: Literal["goal_state"]
|
||||
goal_state: dict[str, Any]
|
||||
|
||||
|
||||
class GoalStatusWirePayload(_ChatWirePayload):
|
||||
event: Literal["goal_status"]
|
||||
status: str
|
||||
started_at: NotRequired[float]
|
||||
|
||||
|
||||
class SessionUpdatedWirePayload(_ChatWirePayload):
|
||||
event: Literal["session_updated"]
|
||||
scope: NotRequired[str]
|
||||
|
||||
|
||||
class UserInputWirePayload(_ChatWirePayload):
|
||||
event: Literal["user_message"]
|
||||
text: str
|
||||
created_at_ms: int
|
||||
starts_turn: bool
|
||||
provenance: NotRequired[dict[str, Any]]
|
||||
|
||||
|
||||
class PairingChangedWirePayload(TypedDict):
|
||||
event: Literal["pairing_changed"]
|
||||
|
||||
|
||||
class RuntimeModelWirePayload(TypedDict):
|
||||
event: Literal["runtime_model_updated"]
|
||||
model_name: str
|
||||
model_preset: NotRequired[str]
|
||||
|
||||
|
||||
class TurnModelWirePayload(_ChatWirePayload):
|
||||
event: Literal["turn_model_updated"]
|
||||
model_name: str
|
||||
model_preset: NotRequired[str]
|
||||
context_window_tokens: NotRequired[int]
|
||||
fallback: NotRequired[bool]
|
||||
reauth_provider: NotRequired[str]
|
||||
|
||||
|
||||
WebUIWirePayload: TypeAlias = (
|
||||
RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
|
||||
| SubagentTaskWirePayload
|
||||
| SubagentTaskWirePayload | MessageWirePayload | StreamWirePayload | FileEditWirePayload
|
||||
| GoalStateWirePayload | GoalStatusWirePayload | SessionUpdatedWirePayload | UserInputWirePayload
|
||||
| PairingChangedWirePayload | RuntimeModelWirePayload | TurnModelWirePayload
|
||||
)
|
||||
WebUIWirePersistence: TypeAlias = Literal[
|
||||
"transient",
|
||||
|
||||
@@ -107,14 +107,18 @@ IMPORT_RULES = (
|
||||
"nanobot.command",
|
||||
"nanobot.runtime_context",
|
||||
"nanobot.security.workspace_access",
|
||||
"nanobot.pairing.events",
|
||||
"nanobot.session.goal_state",
|
||||
"nanobot.session.webui_turns",
|
||||
"nanobot.webui.metadata",
|
||||
"nanobot.webui.outbound_wire",
|
||||
"nanobot.webui.transcript",
|
||||
"nanobot.webui.cli_apps_api",
|
||||
"nanobot.webui.forking",
|
||||
"nanobot.webui.mcp_presets_api",
|
||||
"nanobot.webui.sidebar_state",
|
||||
"nanobot.webui.transcription_ws",
|
||||
),
|
||||
type_only_allowed=("nanobot.bus.outbound_events.ProgressEvent",),
|
||||
),
|
||||
ImportRule(
|
||||
"tool-config-base",
|
||||
|
||||
@@ -352,11 +352,12 @@ async def test_runner_records_each_provider_when_streaming_times_out_and_recover
|
||||
@pytest.mark.parametrize("temporary", [False, True])
|
||||
async def test_websocket_wire_and_disk_replay_preserve_sources(history, tmp_path, monkeypatch, temporary):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
channel = WebSocketChannel({"allowFrom": ["*"]}, MessageBus(), gateway=MagicMock())
|
||||
channel._media.rewrite_local_markdown_images.side_effect = lambda text: text
|
||||
channel._transcripts = WebUITranscriptRecorder(history.sessions)
|
||||
gateway = MagicMock()
|
||||
gateway.media.rewrite_local_markdown_images.side_effect = lambda text: text
|
||||
gateway.transcripts = WebUITranscriptRecorder(history.sessions)
|
||||
gateway.temporary_chats.should_persist_transcript = lambda _: not temporary
|
||||
channel = WebSocketChannel({"allowFrom": ["*"]}, MessageBus(), gateway=gateway)
|
||||
generation, _ = await history.sessions.state.open_with_metadata("websocket:source-chat", {})
|
||||
channel._temporary_chats.should_persist_transcript = lambda _: not temporary
|
||||
channel._safe_send_to = AsyncMock()
|
||||
channel._subs["source-chat"] = {MagicMock()}
|
||||
sources = [{"provider": "xai", "model": "grok", "preset": "snapshot name", "fallback": True}]
|
||||
|
||||
@@ -119,19 +119,24 @@ def test_storage_and_security_do_not_depend_on_adapters(module: str, rule: str)
|
||||
]
|
||||
|
||||
|
||||
def test_websocket_only_permits_progress_event_as_a_type_dependency() -> None:
|
||||
source = (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from nanobot.bus.outbound_events import ProgressEvent\n"
|
||||
" from nanobot.command import router\n"
|
||||
"else:\n"
|
||||
" from nanobot.bus.outbound_events import ProgressEvent\n"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"dependency",
|
||||
[
|
||||
"nanobot.bus.outbound_events.ProgressEvent",
|
||||
"nanobot.command.router",
|
||||
"nanobot.pairing.events.PairingChanged",
|
||||
"nanobot.session.webui_turns.clear_websocket_turn_if_current",
|
||||
"nanobot.webui.transcript.WebUITranscriptRecorder",
|
||||
"nanobot.webui.outbound_wire.project_notification",
|
||||
],
|
||||
)
|
||||
def test_websocket_transport_leaves_event_and_history_policy_to_delivery(dependency: str) -> None:
|
||||
module, name = dependency.rsplit(".", 1)
|
||||
source = f"from {module} import {name}\n"
|
||||
assert find_violations(source, "nanobot.channels.websocket.runtime") == [
|
||||
Violation("websocket-transport", "nanobot.command.router", 4),
|
||||
Violation("websocket-transport", "nanobot.bus.outbound_events.ProgressEvent", 6),
|
||||
Violation("websocket-transport", dependency, 1),
|
||||
]
|
||||
assert find_violations(source, "nanobot.webui.outbound_delivery") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -49,7 +49,7 @@ async def channel(tmp_path, monkeypatch):
|
||||
assert not channel._commands.request_tasks
|
||||
|
||||
|
||||
async def test_send_delegates_the_outbound_message_to_the_projector(channel, monkeypatch):
|
||||
async def test_send_delegates_the_outbound_message_to_delivery(channel, monkeypatch):
|
||||
send = AsyncMock()
|
||||
hydrate = AsyncMock()
|
||||
monkeypatch.setattr(channel._outbound, "send", send)
|
||||
@@ -71,12 +71,34 @@ async def test_subscribe_hydration_delegates_the_requested_chat(channel, monkeyp
|
||||
monkeypatch.setattr(channel._outbound, "hydrate", hydrate)
|
||||
monkeypatch.setattr(channel._outbound, "send", send)
|
||||
|
||||
await channel._hydrate_after_subscribe("chat-2")
|
||||
await channel._dispatch_envelope(
|
||||
AsyncMock(), "client-1", {"type": "attach", "chat_id": "chat-2"},
|
||||
)
|
||||
|
||||
hydrate.assert_awaited_once_with("chat-2")
|
||||
send.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "args", "kwargs"),
|
||||
[
|
||||
("send_delta", ("chat-1", "part", {"webui_turn_id": "turn-1"}), {
|
||||
"stream_id": "s1", "stream_end": True, "resuming": True, "merge_next": True,
|
||||
}),
|
||||
("send_reasoning_delta", ("chat-1", "plan", {"webui_turn_id": "turn-1"}), {"stream_id": "r1"}),
|
||||
("send_reasoning_end", ("chat-1", {"webui_turn_id": "turn-1"}), {"stream_id": "r1"}),
|
||||
("send_file_edit_events", ("chat-1", [{"path": "a.py"}], {"webui_turn_id": "turn-1"}), {}),
|
||||
],
|
||||
)
|
||||
async def test_streaming_capabilities_use_the_same_delivery_owner(channel, monkeypatch, method, args, kwargs):
|
||||
deliver = AsyncMock()
|
||||
monkeypatch.setattr(channel._outbound, method, deliver)
|
||||
|
||||
await getattr(channel, method)(*args, **kwargs)
|
||||
|
||||
deliver.assert_awaited_once_with(*args, **kwargs)
|
||||
|
||||
|
||||
async def test_envelope_delegates_connection_client_and_payload_to_application(channel, monkeypatch):
|
||||
dispatch = AsyncMock()
|
||||
monkeypatch.setattr(channel._commands, "dispatch", dispatch)
|
||||
|
||||
Reference in new issue
Block a user