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
@@ -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",
|
||||
}]
|
||||
Reference in new issue
Block a user