refactor: remove redundant comments and docstrings (#6527)
* refactor: remove redundant comments and docstrings * fix(signal): annotate async context manager as a generator
This commit is contained in:
1 parent
cb3ba45317
commit
a4d2430140
922 files changed
+406
-7738
No files matched your search
@@ -1 +0,0 @@
|
||||
"""WebSocket channel package."""
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Connection-scoped upload capabilities, issued only after the WS handshake."""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Shared MIME and batch limits for WebSocket attachment ingress."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""WebSocket management contract."""
|
||||
|
||||
from nanobot.channels.contracts import ChannelSetupSpec
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
from nanobot.channels.websocket.validation import validate
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""WebSocket server channel: nanobot acts as a WebSocket server and serves connected clients."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -275,7 +273,6 @@ class WebSocketConfig(Base):
|
||||
|
||||
|
||||
def _parse_inbound_payload(raw: str) -> str | None:
|
||||
"""Parse a client frame into text; return None for empty or unrecognized content."""
|
||||
text = raw.strip()
|
||||
if not text:
|
||||
return None
|
||||
@@ -300,12 +297,6 @@ def _is_valid_chat_id(value: Any) -> TypeGuard[str]: # pyright: ignore[reportUn
|
||||
|
||||
|
||||
def _parse_envelope(raw: str) -> dict[str, Any] | None:
|
||||
"""Return a typed envelope dict if the frame is a new-style JSON envelope, else None.
|
||||
|
||||
A frame qualifies when it parses as a JSON object with a string ``type`` field.
|
||||
Legacy frames (plain text, or ``{"content": ...}`` without ``type``) return None;
|
||||
callers should fall back to :func:`_parse_inbound_payload` for those.
|
||||
"""
|
||||
text = raw.strip()
|
||||
if not text.startswith("{"):
|
||||
return None
|
||||
@@ -358,7 +349,6 @@ class WebSocketChannel(BaseChannel):
|
||||
config = WebSocketConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
self.config: WebSocketConfig = config
|
||||
# chat_id -> connections subscribed to it (fan-out target).
|
||||
self._subs: dict[str, set[ServerConnection]] = {}
|
||||
# connection -> chat_ids it is subscribed to (O(1) cleanup on disconnect).
|
||||
self._conn_chats: dict[ServerConnection, set[str]] = {}
|
||||
@@ -387,7 +377,6 @@ class WebSocketChannel(BaseChannel):
|
||||
self._webui_request_operations = self._commands.request_operations
|
||||
self._webui_request_locks = self._commands.request_locks
|
||||
|
||||
# -- Subscription bookkeeping -------------------------------------------
|
||||
|
||||
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]:
|
||||
"""Return a stable snapshot of one chat's transport subscribers."""
|
||||
@@ -456,7 +445,6 @@ class WebSocketChannel(BaseChannel):
|
||||
)
|
||||
|
||||
def _attach(self, connection: ServerConnection, chat_id: str) -> None:
|
||||
"""Idempotently subscribe *connection* to *chat_id*."""
|
||||
if not self._register_connection_outbound(connection):
|
||||
return
|
||||
self._subs.setdefault(chat_id, set()).add(connection)
|
||||
@@ -484,7 +472,6 @@ class WebSocketChannel(BaseChannel):
|
||||
self._subs.pop(chat_id, 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)
|
||||
self._uploads.revoke(connection)
|
||||
state = self._connection_outbound.get(connection)
|
||||
@@ -507,7 +494,6 @@ class WebSocketChannel(BaseChannel):
|
||||
event: str,
|
||||
**fields: Any,
|
||||
) -> None:
|
||||
"""Send a control event (attached, error, ...) to a single connection."""
|
||||
payload: dict[str, Any] = {"event": event}
|
||||
payload.update(fields)
|
||||
raw = json.dumps(payload, ensure_ascii=False)
|
||||
@@ -531,7 +517,6 @@ class WebSocketChannel(BaseChannel):
|
||||
ctx.load_cert_chain(certfile=cert, keyfile=key)
|
||||
return ctx
|
||||
|
||||
# -- HTTP dispatch ------------------------------------------------------
|
||||
|
||||
async def _dispatch_http(self, connection: ServerConnection, request: WsRequest) -> Any:
|
||||
"""Compatibility proxy for the externally composed gateway endpoint."""
|
||||
@@ -554,7 +539,6 @@ class WebSocketChannel(BaseChannel):
|
||||
headers,
|
||||
)
|
||||
|
||||
# -- Server lifecycle and connection ingress ---------------------------
|
||||
|
||||
@staticmethod
|
||||
def _socket_is_accepting(sock: socket.socket) -> bool:
|
||||
@@ -602,7 +586,6 @@ class WebSocketChannel(BaseChannel):
|
||||
)
|
||||
|
||||
async def _wait_for_listener_loss(self, server: Server) -> None:
|
||||
"""Wait for shutdown or raise when the serving socket disappears."""
|
||||
assert self._stop_event is not None
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
@@ -881,7 +864,6 @@ class WebSocketChannel(BaseChannel):
|
||||
finally:
|
||||
await self._cleanup_connection(connection)
|
||||
|
||||
# -- Inbound WebSocket envelopes ---------------------------------------
|
||||
|
||||
async def _dispatch_envelope(
|
||||
self,
|
||||
@@ -889,7 +871,6 @@ class WebSocketChannel(BaseChannel):
|
||||
client_id: str,
|
||||
envelope: dict[str, Any],
|
||||
) -> None:
|
||||
"""Delegate one typed envelope to the WebUI application router."""
|
||||
await self._dispatch_active_envelope(connection, client_id, envelope)
|
||||
|
||||
async def _dispatch_active_envelope(
|
||||
@@ -902,7 +883,6 @@ class WebSocketChannel(BaseChannel):
|
||||
return
|
||||
await self._commands.dispatch(connection, client_id, envelope)
|
||||
|
||||
# -- Outbound WebSocket events -----------------------------------------
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self.gateway.http.remote_instances.close()
|
||||
@@ -1088,7 +1068,6 @@ class WebSocketChannel(BaseChannel):
|
||||
*,
|
||||
label: str = "",
|
||||
) -> None:
|
||||
"""Queue one frame without letting this connection block other clients."""
|
||||
state = self._connection_outbound.get(connection)
|
||||
if state is None or state.closing:
|
||||
return
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the WebSocket channel package."""
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Shared isolation for WebSocket tests that persist runtime state."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Production listener regressions for HTTP upload + small WS references."""
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
@@ -203,7 +202,6 @@ async def test_real_listener_large_binary_and_reference_delivery(gateway, mime,
|
||||
path = Path(inbound.media[0])
|
||||
assert path.read_bytes() == raw
|
||||
assert path.parent == channel.gateway.uploads.store.media_dir
|
||||
# Lost ACK retry must not resolve a consumed reference or dispatch twice.
|
||||
await ws.send(json.dumps(frame))
|
||||
await event(ws, "message_accepted")
|
||||
with pytest.raises(TimeoutError):
|
||||
@@ -275,7 +273,6 @@ async def test_http_policy_rejection_does_not_leave_files(gateway, mime, body):
|
||||
|
||||
async def test_one_shot_handshake_token_is_not_an_upload_credential(gateway):
|
||||
channel, _, http_url, _ = gateway
|
||||
# Use the same one-shot token registry as the bootstrap endpoint.
|
||||
issued = channel.gateway.tokens.issue_token(60, audience="webui")
|
||||
ws_url = http_url.replace("http://", "ws://") + "/ws?token=" + issued
|
||||
async with connect(ws_url) as ws, aiohttp.ClientSession() as http:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Binary staging regressions; these do not exercise the gateway HTTP listener."""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from pathlib import Path
|
||||
@@ -28,10 +26,10 @@ async def test_binary_larger_than_websocket_limit_preserves_layout(tmp_path):
|
||||
paths = store.resolve([ref], owner="owner")
|
||||
assert re.fullmatch(r"[0-9a-f]{12}\.png", Path(paths[0]).name)
|
||||
assert Path(paths[0]).read_bytes() == raw
|
||||
assert store.resolve([ref], owner="owner") == paths # a failed send is retryable
|
||||
assert store.resolve([ref], owner="owner") == paths
|
||||
assert store.commit([ref], owner="owner") == paths
|
||||
store.clear()
|
||||
assert Path(paths[0]).read_bytes() == raw # cleanup must not delete session media
|
||||
assert Path(paths[0]).read_bytes() == raw
|
||||
with pytest.raises(AttachmentUploadError):
|
||||
store.resolve([ref], owner="owner")
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Real socket regressions for body-capable HTTP beside bounded WebSockets."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import aiohttp
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Real listener regressions for peer disconnects while an HTTP route awaits."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
@@ -54,7 +52,6 @@ async def _listener(tmp_path, monkeypatch, caplog, unix, process_request):
|
||||
return await dispatch_http(connection, request)
|
||||
|
||||
monkeypatch.setattr(channel, "_dispatch_http", dispatch)
|
||||
# Capture independently of logging redirection while retaining the real filter.
|
||||
logger = logging.Logger("websockets.eof-regression", level=logging.ERROR)
|
||||
logger.addHandler(caplog.handler)
|
||||
logger.addFilter(WebSocketHandshakeNoiseFilter())
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Borrowed local attachments share ingress policy without taking file ownership."""
|
||||
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Settings restarts are controls, not persisted chat turns."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -53,7 +51,6 @@ async def test_settings_restart_does_not_create_or_change_chat_history(history,
|
||||
before_files = {p: p.read_bytes() for p in tmp_path.rglob("*.jsonl")}
|
||||
before_transcript = history.read(key)
|
||||
|
||||
# Use each new connection's default ID, then an existing chat when present.
|
||||
chat_ids = ["ready-default-1", "ready-default-2"]
|
||||
if existing != "none":
|
||||
chat_ids.append("existing")
|
||||
@@ -65,7 +62,6 @@ async def test_settings_restart_does_not_create_or_change_chat_history(history,
|
||||
await channel._dispatch_envelope(connection, "browser", envelope)
|
||||
message = bus.publish_inbound.await_args.args[0]
|
||||
assert message.metadata[WEBUI_RESTART_CONTROL_METADATA_KEY] is True
|
||||
# Exercise the real command response, but never execute a process restart.
|
||||
def discard_restart_task(coro):
|
||||
coro.close()
|
||||
with monkeypatch.context() as patch:
|
||||
@@ -74,7 +70,6 @@ async def test_settings_restart_does_not_create_or_change_chat_history(history,
|
||||
msg=message, session=None, key=message.session_key, raw=message.content, loop=MagicMock(),
|
||||
))
|
||||
await channel.send(response)
|
||||
# A lost ACK retry must not enqueue a second restart.
|
||||
calls = bus.publish_inbound.await_count
|
||||
await channel._dispatch_envelope(connection, "browser", envelope)
|
||||
assert bus.publish_inbound.await_count == calls
|
||||
@@ -86,7 +81,6 @@ async def test_settings_restart_does_not_create_or_change_chat_history(history,
|
||||
assert all(frame["text"] == "Restarting..." and frame["turn_id"].startswith("webui-system:") for frame in replies)
|
||||
assert {p: p.read_bytes() for p in tmp_path.rglob("*.jsonl")} == before_files
|
||||
assert history.read(key) == before_transcript
|
||||
# A fresh manager uses the public sidebar discovery path, not a cached count.
|
||||
fresh = SessionManager(sessions.workspace)
|
||||
assert list_webui_sessions(fresh) == before_rows
|
||||
if existing in {"canonical", "both"}:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Unit and lightweight integration tests for the WebSocket channel."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
@@ -89,8 +87,6 @@ from nanobot.webui.settings_api import settings_payload, update_provider_setting
|
||||
|
||||
from .ws_test_client import http_get as _http_get
|
||||
|
||||
# -- Shared helpers (aligned with test_websocket_integration.py) ---------------
|
||||
|
||||
_PORT = 0
|
||||
|
||||
|
||||
@@ -887,12 +883,12 @@ def test_parse_inbound_invalid_json_falls_back_to_raw_string() -> None:
|
||||
@pytest.mark.parametrize(
|
||||
("raw", "expected"),
|
||||
[
|
||||
('{"content": ""}', None), # empty string content
|
||||
('{"content": 123}', None), # non-string content
|
||||
('{"content": " "}', None), # whitespace-only content
|
||||
('["hello"]', '["hello"]'), # JSON array: not a dict, treated as plain text
|
||||
('{"unknown_key": "val"}', None), # unrecognized key
|
||||
('{"content": null}', None), # null content
|
||||
('{"content": ""}', None),
|
||||
('{"content": 123}', None),
|
||||
('{"content": " "}', None),
|
||||
('["hello"]', '["hello"]'),
|
||||
('{"unknown_key": "val"}', None),
|
||||
('{"content": null}', None),
|
||||
],
|
||||
)
|
||||
def test_parse_inbound_payload_edge_cases(raw: str, expected: str | None) -> None:
|
||||
@@ -944,7 +940,6 @@ def test_issue_route_secret_matches_bearer_and_header() -> None:
|
||||
def test_issue_route_secret_matches_empty_secret() -> None:
|
||||
from websockets.datastructures import Headers
|
||||
|
||||
# Empty secret always returns True regardless of headers
|
||||
assert _issue_route_secret_matches(Headers([]), "") is True
|
||||
assert _issue_route_secret_matches(Headers([("Authorization", "Bearer anything")]), "") is True
|
||||
|
||||
@@ -1721,7 +1716,6 @@ async def test_webui_automation_intent_is_hidden_and_not_inherited_by_cron(histo
|
||||
assert "create an automation" in block.content
|
||||
assert "not to execute the task immediately" in block.content
|
||||
|
||||
# Model input includes the context; public history strips the exact saved suffix.
|
||||
content, marker = append_runtime_context(msg.content, [block])
|
||||
assert block.content in content
|
||||
assert public_history_message({
|
||||
@@ -2742,7 +2736,6 @@ async def test_send_progress_omits_binary_tool_results_from_wire_and_transcript(
|
||||
assert replayed["text"] == ""
|
||||
assert replayed["tool_events"] == payload["tool_events"]
|
||||
|
||||
# WebUI projection must not alter the result that the runner sends back to the model.
|
||||
assert tool_events[0]["result"][0]["image_url"]["url"] == data_url
|
||||
|
||||
|
||||
@@ -3081,7 +3074,6 @@ async def test_send_reasoning_end_emits_close_frame() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_reasoning_one_shot_expands_to_delta_plus_end() -> None:
|
||||
"""``send_reasoning`` produces one delta and one end."""
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
||||
mock_ws = AsyncMock()
|
||||
@@ -3731,8 +3723,6 @@ async def test_durable_incomplete_marker_stays_pending_without_safe_session_reco
|
||||
event=GoalStatusEvent(status="idle"),
|
||||
))
|
||||
|
||||
# Simulate a gateway restart: no process-local owner survives, so the
|
||||
# persisted marker must be sufficient to reject canonical completion.
|
||||
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
||||
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
||||
wth._WEBSOCKET_TURN_IDS.clear()
|
||||
@@ -3836,7 +3826,6 @@ async def test_http_replay_recovers_marked_answer_from_session_after_gateway_res
|
||||
assert persisted_lines[-1]["event"] == "turn_end"
|
||||
assert persisted_lines[-1]["transcript_incomplete"] is True
|
||||
|
||||
# Drop all process-local state and construct a fresh HTTP/session layer.
|
||||
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
||||
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
||||
wth._WEBSOCKET_TURN_IDS.clear()
|
||||
@@ -4336,7 +4325,6 @@ async def test_send_non_connection_closed_exception_is_isolated() -> None:
|
||||
async def test_send_delta_missing_connection_is_noop() -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus))
|
||||
# No exception, no error — just a no-op
|
||||
await channel.send_delta("nonexistent", "chunk", stream_id="s1")
|
||||
assert channel._subs == {}
|
||||
|
||||
@@ -4345,7 +4333,6 @@ async def test_send_delta_missing_connection_is_noop() -> None:
|
||||
async def test_stop_is_idempotent() -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
||||
# stop() before start() should not raise
|
||||
await channel.stop()
|
||||
await channel.stop()
|
||||
assert channel._subs == {}
|
||||
@@ -4544,7 +4531,7 @@ async def test_settings_api_returns_safe_subset_and_updates_whitelist(
|
||||
providers = {provider["name"]: provider for provider in body["providers"]}
|
||||
assert providers["openai"]["configured"] is True
|
||||
assert providers["openai"]["api_key_hint"] == "secr••••-key"
|
||||
assert providers["azure_openai"]["api_key_required"] is False # AAD auth supported; no static key required
|
||||
assert providers["azure_openai"]["api_key_required"] is False
|
||||
assert providers["openrouter"]["configured"] is False
|
||||
assert providers["openrouter"]["api_key_required"] is True
|
||||
assert providers["orcarouter"]["label"] == "OrcaRouter"
|
||||
@@ -5191,7 +5178,6 @@ async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMoc
|
||||
ready = json.loads(ready_raw)
|
||||
chat_id = ready["chat_id"]
|
||||
|
||||
# Server pushes deltas directly
|
||||
await channel.send_delta(
|
||||
chat_id, "Hello ", stream_id="s1"
|
||||
)
|
||||
@@ -5238,7 +5224,6 @@ async def test_token_issue_rejects_when_at_capacity(bus: MagicMock, start_listen
|
||||
port, server_task = await start_listener(channel)
|
||||
|
||||
try:
|
||||
# Fill issued tokens to capacity
|
||||
channel.gateway.tokens.issued_tokens = {
|
||||
f"nbwt_fill_{i}": time.monotonic() + 300
|
||||
for i in range(channel.gateway.tokens.max_tokens)
|
||||
@@ -5523,11 +5508,9 @@ async def test_non_utf8_binary_frame_ignored(bus: MagicMock, start_listener) ->
|
||||
|
||||
try:
|
||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bin-test") as client:
|
||||
await client.recv() # consume ready
|
||||
# Send non-UTF-8 bytes
|
||||
await client.recv()
|
||||
await client.send(b"\xff\xfe\xfd")
|
||||
await asyncio.sleep(0.05)
|
||||
# publish_inbound should NOT have been called
|
||||
bus.publish_inbound.assert_not_awaited()
|
||||
finally:
|
||||
await channel.stop()
|
||||
@@ -5547,7 +5530,6 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock, sta
|
||||
port, server_task = await start_listener(channel)
|
||||
|
||||
try:
|
||||
# Get an issued token
|
||||
resp = await _http_get(
|
||||
f"http://127.0.0.1:{port}/auth/token",
|
||||
headers={"Authorization": "Bearer route-secret"},
|
||||
@@ -5555,7 +5537,6 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock, sta
|
||||
assert resp.status_code == 200
|
||||
issued_token = resp.json()["token"]
|
||||
|
||||
# Connect using issued token (not the static one)
|
||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?token={issued_token}&client_id=caller") as client:
|
||||
ready = json.loads(await client.recv())
|
||||
assert ready["event"] == "ready"
|
||||
@@ -5583,20 +5564,17 @@ async def test_allow_from_empty_list_denies_all(bus: MagicMock, start_listener)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_websocket_requires_token_without_issue_path(bus: MagicMock, start_listener) -> None:
|
||||
"""When websocket_requires_token is True but no token or issue path configured, all connections are rejected."""
|
||||
port = 0
|
||||
channel = _ch(bus, port=port, websocketRequiresToken=True)
|
||||
|
||||
port, server_task = await start_listener(channel)
|
||||
|
||||
try:
|
||||
# No token at all → 401
|
||||
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=u"):
|
||||
pass
|
||||
assert exc_info.value.response.status_code == 401
|
||||
|
||||
# Wrong token → 401
|
||||
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=u&token=wrong"):
|
||||
pass
|
||||
@@ -5607,7 +5585,6 @@ async def test_websocket_requires_token_without_issue_path(bus: MagicMock, start
|
||||
|
||||
|
||||
# -- Multi-chat multiplexing -------------------------------------------------
|
||||
#
|
||||
# The multiplex protocol lets one WS connection route N logical chats over
|
||||
# typed envelopes (`new_chat` / `attach` / `message`). Legacy frames must keep
|
||||
# working on the connection's default chat_id.
|
||||
@@ -5624,20 +5601,17 @@ async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> N
|
||||
ready = json.loads(await client.recv())
|
||||
default_chat = ready["chat_id"]
|
||||
|
||||
# Plain text frame routes to default chat_id
|
||||
await client.send("hello from legacy")
|
||||
await asyncio.sleep(0.1)
|
||||
inbound = bus.publish_inbound.call_args[0][0]
|
||||
assert inbound.chat_id == default_chat
|
||||
assert inbound.content == "hello from legacy"
|
||||
|
||||
# {"content": ...} frame routes to default chat_id
|
||||
await client.send(json.dumps({"content": "structured legacy"}))
|
||||
await asyncio.sleep(0.1)
|
||||
assert bus.publish_inbound.call_args[0][0].chat_id == default_chat
|
||||
assert bus.publish_inbound.call_args[0][0].content == "structured legacy"
|
||||
|
||||
# Outbound still reaches the legacy client, with chat_id annotated
|
||||
await channel.send(
|
||||
OutboundMessage(channel="websocket", chat_id=default_chat, content="reply")
|
||||
)
|
||||
@@ -5667,7 +5641,6 @@ async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> N
|
||||
new_chat = attached["chat_id"]
|
||||
assert new_chat and new_chat != default_chat
|
||||
|
||||
# Send on the new chat via typed envelope
|
||||
await client.send(
|
||||
json.dumps({"type": "message", "chat_id": new_chat, "content": "hi on new"})
|
||||
)
|
||||
@@ -5676,7 +5649,6 @@ async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> N
|
||||
assert inbound.chat_id == new_chat
|
||||
assert inbound.content == "hi on new"
|
||||
|
||||
# Server pushes a message back; chat_id must match
|
||||
await channel.send(
|
||||
OutboundMessage(channel="websocket", chat_id=new_chat, content="ok")
|
||||
)
|
||||
@@ -5793,7 +5765,7 @@ async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> N
|
||||
|
||||
try:
|
||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=two") as client:
|
||||
await client.recv() # ready
|
||||
await client.recv()
|
||||
|
||||
await client.send(json.dumps({"type": "new_chat"}))
|
||||
chat_a = (await _recv_ws_event(client, "attached"))["chat_id"]
|
||||
@@ -5801,7 +5773,6 @@ async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> N
|
||||
chat_b = (await _recv_ws_event(client, "attached"))["chat_id"]
|
||||
assert chat_a != chat_b
|
||||
|
||||
# Push A → client sees A only (FIFO over the single WS).
|
||||
await channel.send(
|
||||
OutboundMessage(channel="websocket", chat_id=chat_a, content="for-A")
|
||||
)
|
||||
@@ -5809,7 +5780,6 @@ async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> N
|
||||
assert msg_a["chat_id"] == chat_a
|
||||
assert msg_a["text"] == "for-A"
|
||||
|
||||
# Push B → client sees B only.
|
||||
await channel.send(
|
||||
OutboundMessage(channel="websocket", chat_id=chat_b, content="for-B")
|
||||
)
|
||||
@@ -5829,24 +5799,20 @@ async def test_multiplex_invalid_frames_return_error(bus: MagicMock, start_liste
|
||||
|
||||
try:
|
||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bad") as client:
|
||||
await client.recv() # ready
|
||||
await client.recv()
|
||||
|
||||
# attach with bad chat_id
|
||||
await client.send(json.dumps({"type": "attach", "chat_id": "has space"}))
|
||||
err1 = json.loads(await client.recv())
|
||||
assert err1["event"] == "error"
|
||||
|
||||
# message with missing content
|
||||
await client.send(json.dumps({"type": "message", "chat_id": "abc", "content": ""}))
|
||||
err2 = json.loads(await client.recv())
|
||||
assert err2["event"] == "error"
|
||||
|
||||
# unknown type
|
||||
await client.send(json.dumps({"type": "nope"}))
|
||||
err3 = json.loads(await client.recv())
|
||||
assert err3["event"] == "error"
|
||||
|
||||
# Connection survives: legacy frame still works.
|
||||
await client.send("still-alive")
|
||||
await asyncio.sleep(0.1)
|
||||
bus.publish_inbound.assert_awaited()
|
||||
@@ -5870,7 +5836,6 @@ async def test_multiplex_cleanup_on_disconnect(bus: MagicMock, start_listener) -
|
||||
extra_chat = json.loads(await client.recv())["chat_id"]
|
||||
assert default_chat in channel._subs
|
||||
assert extra_chat in channel._subs
|
||||
# Client gone. Server-side tracking must be empty.
|
||||
await asyncio.sleep(0.2)
|
||||
assert default_chat not in channel._subs
|
||||
assert extra_chat not in channel._subs
|
||||
@@ -5888,12 +5853,10 @@ def test_parse_envelope_detects_typed_frames() -> None:
|
||||
|
||||
|
||||
def test_parse_envelope_rejects_legacy_and_garbage() -> None:
|
||||
# No `type` field → legacy, caller falls back to _parse_inbound_payload.
|
||||
assert _parse_envelope('{"content":"hi"}') is None
|
||||
assert _parse_envelope("plain text") is None
|
||||
assert _parse_envelope("{broken") is None
|
||||
assert _parse_envelope("[1,2,3]") is None
|
||||
# Non-string `type` is not a valid envelope.
|
||||
assert _parse_envelope('{"type":123}') is None
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""WS envelope regressions; binary ingress is tested through the HTTP listener."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -56,20 +54,17 @@ def isolate_websocket_turn_state() -> None:
|
||||
|
||||
|
||||
def test_max_message_bytes_keeps_existing_transport_guard() -> None:
|
||||
"""Moving attachments to HTTP does not disable the configurable WS guard."""
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
|
||||
default = WebSocketConfig().max_message_bytes
|
||||
assert default == 36 * 1024 * 1024
|
||||
assert WebSocketConfig(max_message_bytes=1048576).max_message_bytes == 1048576
|
||||
# The existing upper bound remains 40 MB.
|
||||
with pytest.raises(Exception):
|
||||
WebSocketConfig(max_message_bytes=41_943_040 + 1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_without_media_backward_compatible(monkeypatch) -> None:
|
||||
"""Existing clients that don't send ``media`` keep working unchanged."""
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {"type": "message", "chat_id": "abc123", "content": "hello"}
|
||||
@@ -81,7 +76,6 @@ async def test_message_without_media_backward_compatible(monkeypatch) -> None:
|
||||
call = channel._handle_message.call_args
|
||||
assert call.kwargs["chat_id"] == "abc123"
|
||||
assert call.kwargs["content"] == "hello"
|
||||
# When no media, we pass ``media=None`` so downstream treats it as absent.
|
||||
assert call.kwargs["media"] is None
|
||||
|
||||
|
||||
@@ -217,7 +211,6 @@ async def test_message_rejected_when_media_item_shape_wrong(tmp_path) -> None:
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "huh",
|
||||
# Not a dict — plain string at the top level.
|
||||
"media": ["data:image/png;base64,XXXX"],
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""End-to-end tests for the embedded webui's HTTP routes on the WebSocket channel."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import random
|
||||
@@ -277,11 +275,9 @@ async def test_sessions_list_requires_bearer_token(
|
||||
channel = _ch(bus, session_manager=sm, port=29902)
|
||||
server_task = asyncio.create_task(channel.start())
|
||||
try:
|
||||
# Unauthenticated → 401.
|
||||
deny = await _http_get("http://127.0.0.1:29902/api/sessions")
|
||||
assert deny.status_code == 401
|
||||
|
||||
# Directly mint an API token for route-level auth checks.
|
||||
token = channel.gateway.tokens.issue_api_token(300)
|
||||
auth = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
@@ -289,7 +285,6 @@ async def test_sessions_list_requires_bearer_token(
|
||||
assert listing.status_code == 200
|
||||
keys = [s["key"] for s in listing.json()["sessions"]]
|
||||
assert "websocket:abc" in keys
|
||||
# Server stays an opaque source: filesystem paths must not leak to the wire.
|
||||
assert all("path" not in s for s in listing.json()["sessions"])
|
||||
|
||||
finally:
|
||||
@@ -1502,7 +1497,6 @@ async def test_nanobot_feature_install_only_tracks_pending_restart_without_start
|
||||
assert features[0]["enabled"] is False
|
||||
assert [feature["restart_pending"] for feature in features] == [installed_now, False]
|
||||
|
||||
# Refreshing the catalog keeps the pending installation tied to its channel.
|
||||
refreshed = await _http_get(
|
||||
f"http://127.0.0.1:{channel.config.port}/api/settings/nanobot-features",
|
||||
headers={"Authorization": f"Bearer {channel.gateway.tokens.issue_api_token(300)}"},
|
||||
@@ -1512,7 +1506,6 @@ async def test_nanobot_feature_install_only_tracks_pending_restart_without_start
|
||||
installed_now, False,
|
||||
]
|
||||
|
||||
# A new gateway owns a fresh runtime; installed support is ready to configure.
|
||||
restarted = _ch(bus, session_manager=SessionManager(tmp_path), port=_free_port())
|
||||
after_restart = await _http_get(
|
||||
f"http://127.0.0.1:{restarted.config.port}/api/settings/nanobot-features",
|
||||
@@ -2361,8 +2354,6 @@ async def test_mcp_presets_routes_require_token_and_return_payload(
|
||||
async def test_sessions_list_only_returns_websocket_sessions_by_default(
|
||||
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# Seed a realistic multi-channel disk state: CLI, Slack, Lark and
|
||||
# websocket sessions all live in the same ``sessions/`` directory.
|
||||
sm = _seed_many(
|
||||
tmp_path,
|
||||
[
|
||||
@@ -2394,8 +2385,6 @@ async def test_sessions_list_only_returns_websocket_sessions_by_default(
|
||||
assert listing.status_code == 200
|
||||
sessions = listing.json()["sessions"]
|
||||
keys = {s["key"] for s in sessions}
|
||||
# Only websocket-channel sessions are part of the webui surface; CLI /
|
||||
# Slack / Lark rows would be non-resumable from the browser.
|
||||
assert keys == {"websocket:alpha", "websocket:beta"}
|
||||
rows = {row["key"]: row for row in sessions}
|
||||
handles = {
|
||||
@@ -3636,8 +3625,6 @@ async def test_session_delete_rejects_invalid_key(
|
||||
channel = _ch(bus, session_manager=sm, port=29904)
|
||||
server_task = asyncio.create_task(channel.start())
|
||||
try:
|
||||
# Invalid characters in the key -> regex match fails -> 404
|
||||
# (route doesn't match, falls through to channel 404).
|
||||
resp = await _webui_mutate(
|
||||
channel,
|
||||
"session.delete",
|
||||
@@ -3661,15 +3648,12 @@ async def test_static_serves_index_when_dist_present(
|
||||
channel = _ch(bus, session_manager=sm, static_dist_path=dist, port=29905)
|
||||
server_task = asyncio.create_task(channel.start())
|
||||
try:
|
||||
# Bare ``GET /`` is a browser opening the app: it must return the SPA
|
||||
# index.html, not the WS-upgrade handler's 401/426.
|
||||
root = await _http_get("http://127.0.0.1:29905/")
|
||||
assert root.status_code == 200
|
||||
assert "nbweb" in root.text
|
||||
asset = await _http_get("http://127.0.0.1:29905/favicon.svg")
|
||||
assert asset.status_code == 200
|
||||
assert "<svg" in asset.text
|
||||
# Unknown SPA route falls back to index.html.
|
||||
spa = await _http_get("http://127.0.0.1:29905/sessions/abc")
|
||||
assert spa.status_code == 200
|
||||
assert "nbweb" in spa.text
|
||||
@@ -3714,7 +3698,6 @@ async def test_unknown_route_returns_404(bus: MagicMock) -> None:
|
||||
async def test_api_token_pool_purges_expired(bus: MagicMock, tmp_path: Path) -> None:
|
||||
sm = _seed_session(tmp_path)
|
||||
channel = _ch(bus, session_manager=sm, port=29908)
|
||||
# Don't start a server — directly inject and validate.
|
||||
import time as _time
|
||||
channel.gateway.tokens.api_tokens["expired"] = _time.monotonic() - 1
|
||||
channel.gateway.tokens.api_tokens["live"] = _time.monotonic() + 60
|
||||
@@ -4074,7 +4057,6 @@ def test_wildcard_ipv6_with_secret_is_valid(bus: MagicMock) -> None:
|
||||
|
||||
|
||||
def test_bootstrap_accepts_static_token_as_secret(bus: MagicMock) -> None:
|
||||
"""When only token (not token_issue_secret) is set, bootstrap accepts it."""
|
||||
channel = _ch(bus, host="0.0.0.0", token="static-tok")
|
||||
resp = channel.gateway.http._handle_bootstrap(
|
||||
_REMOTE, _FakeReq({"Authorization": "Bearer static-tok"})
|
||||
@@ -4253,7 +4235,6 @@ def test_bootstrap_accepts_x_nanobot_auth_header(bus: MagicMock) -> None:
|
||||
|
||||
|
||||
def test_bootstrap_secret_also_enforced_on_localhost(bus: MagicMock) -> None:
|
||||
"""When secret is set, even localhost must provide it (reverse-proxy safety)."""
|
||||
channel = _ch(bus, host="0.0.0.0", tokenIssueSecret="s3cret")
|
||||
resp = channel.gateway.http._handle_bootstrap(_LOCAL, _NO_HEADERS)
|
||||
assert resp.status_code == 401
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
"""Integration tests for the WebSocket channel using WsTestClient.
|
||||
|
||||
Complements the unit/lightweight tests in test_websocket_channel.py by covering
|
||||
multi-client scenarios, edge cases, and realistic usage patterns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -55,9 +49,6 @@ def bus() -> MagicMock:
|
||||
return b
|
||||
|
||||
|
||||
# -- Connection basics ----------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ready_event_fields(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29901)
|
||||
@@ -99,9 +90,6 @@ async def test_each_connection_unique_chat_id(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Inbound messages (client -> server) ----------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_plain_text(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29904)
|
||||
@@ -185,9 +173,6 @@ async def test_messages_preserve_order(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Outbound messages (server -> client) ---------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_send_message(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29909)
|
||||
@@ -207,20 +192,17 @@ async def test_server_send_message(bus: MagicMock) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_send_tags_tool_hint_with_kind(bus: MagicMock) -> None:
|
||||
"""Tool-hint progress events surface as ``kind: "tool_hint"``."""
|
||||
ch = _ch(bus, 29919)
|
||||
t = asyncio.create_task(ch.start())
|
||||
try:
|
||||
async with WsTestClient("ws://127.0.0.1:29919/", client_id="h") as c:
|
||||
ready = await c.recv_ready()
|
||||
# Plain reply: no "kind" field.
|
||||
await ch.send(OutboundMessage(
|
||||
channel="websocket", chat_id=ready.chat_id, content="hi",
|
||||
))
|
||||
plain = await c.recv_message()
|
||||
assert plain.raw.get("kind") is None
|
||||
|
||||
# Tool-hint breadcrumb: kind == "tool_hint".
|
||||
tool_start = {
|
||||
"phase": "start", "call_id": "call-weather", "name": "weather",
|
||||
"arguments": {"action": "get"},
|
||||
@@ -248,7 +230,6 @@ async def test_server_send_tags_tool_hint_with_kind(bus: MagicMock) -> None:
|
||||
assert result.text == ""
|
||||
assert result.raw["tool_events"] == [tool_end]
|
||||
|
||||
# Generic progress (non-tool-hint) gets the softer "progress" label.
|
||||
await ch.send(OutboundMessage(
|
||||
channel="websocket", chat_id=ready.chat_id,
|
||||
content="thinking…",
|
||||
@@ -281,9 +262,6 @@ async def test_server_send_with_media_and_reply(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Streaming ------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_deltas_and_end(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29911, streaming=True)
|
||||
@@ -329,9 +307,6 @@ async def test_interleaved_streams(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Multi-client ---------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_independent_sessions(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29913)
|
||||
@@ -410,7 +385,6 @@ async def test_disconnected_client_cleanup(bus: MagicMock) -> None:
|
||||
try:
|
||||
async with WsTestClient("ws://127.0.0.1:29914/", client_id="tmp") as c:
|
||||
chat_id = (await c.recv_ready()).chat_id
|
||||
# disconnected
|
||||
await asyncio.sleep(0.1)
|
||||
await ch.send(OutboundMessage(
|
||||
channel="websocket", chat_id=chat_id, content="orphan",
|
||||
@@ -421,9 +395,6 @@ async def test_disconnected_client_cleanup(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Authentication -------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_static_token_accepted(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29915, token="secret")
|
||||
@@ -457,24 +428,19 @@ async def test_token_issue_full_flow(bus: MagicMock) -> None:
|
||||
websocketRequiresToken=True)
|
||||
t = asyncio.create_task(ch.start())
|
||||
try:
|
||||
# no secret -> 401
|
||||
_, status = await issue_token(port=29917, issue_path="/auth/token")
|
||||
assert status == 401
|
||||
|
||||
# with secret -> token
|
||||
token = await issue_token_ok(port=29917, issue_path="/auth/token", secret="s")
|
||||
|
||||
# no token -> 401
|
||||
with pytest.raises(websockets.exceptions.InvalidStatus) as exc:
|
||||
async with WsTestClient("ws://127.0.0.1:29917/ws", client_id="x"):
|
||||
pass
|
||||
assert exc.value.response.status_code == 401
|
||||
|
||||
# valid token -> ok
|
||||
async with WsTestClient("ws://127.0.0.1:29917/ws", client_id="ok", token=token) as c:
|
||||
assert (await c.recv_ready()).client_id == "ok"
|
||||
|
||||
# reuse -> 401
|
||||
with pytest.raises(websockets.exceptions.InvalidStatus) as exc:
|
||||
async with WsTestClient("ws://127.0.0.1:29917/ws", client_id="r", token=token):
|
||||
pass
|
||||
@@ -484,9 +450,6 @@ async def test_token_issue_full_flow(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Path routing ---------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_path(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29918, path="/my-chat")
|
||||
@@ -525,9 +488,6 @@ async def test_trailing_slash_normalized(bus: MagicMock) -> None:
|
||||
await t
|
||||
|
||||
|
||||
# -- Edge cases -----------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_large_message(bus: MagicMock) -> None:
|
||||
ch = _ch(bus, 29921)
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
"""Tests for the signed ``/api/media/<sig>/<payload>`` route and WebUI replay.
|
||||
|
||||
The route is the return path for local media rendered by the WebUI. These tests
|
||||
cover URL signing and serving end-to-end plus the adversarial edges (bad
|
||||
signatures, ``..`` traversal, non-existent files, non-image types).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -28,8 +21,6 @@ from nanobot.webui.media_api import (
|
||||
from .ws_test_client import InProcessHttpChannel
|
||||
from .ws_test_client import http_get as _http_get
|
||||
|
||||
# PNG magic bytes + a couple of sentinel bytes so we can verify byte-for-byte
|
||||
# round-trip of the served payload. Stays under mimetype + size limits.
|
||||
_PNG_BYTES = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
@@ -93,11 +84,6 @@ def _sign_media_path(channel: WebSocketChannel, path: Path) -> str | None:
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# media_api.sign_media_path: the URL minter
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sign_media_path_rejects_paths_outside_media_root(
|
||||
bus: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -115,15 +101,12 @@ def test_sign_media_path_rejects_paths_outside_media_root(
|
||||
channel = _ch(bus, port=0)
|
||||
with patch("nanobot.webui.media_gateway.get_media_dir", return_value=media):
|
||||
assert _sign_media_path(channel, outside) is None
|
||||
# Traversal via the media root is also rejected — the resolve() step
|
||||
# normalises ``..`` out before the relative_to check.
|
||||
assert _sign_media_path(channel, media / ".." / "secrets" / "cred.txt") is None
|
||||
|
||||
|
||||
def test_sign_media_path_round_trips_via_hmac(
|
||||
bus: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""The signature embeds exactly ``HMAC-SHA256(secret, payload)[:16]``."""
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
(media / "a.png").write_bytes(_PNG_BYTES)
|
||||
@@ -137,7 +120,6 @@ def test_sign_media_path_round_trips_via_hmac(
|
||||
channel.gateway.media.secret, payload.encode("ascii"), hashlib.sha256
|
||||
).digest()[:16]
|
||||
assert b64url_decode(sig) == expected
|
||||
# The payload decodes back to the *relative* path — no absolute-path leaks.
|
||||
assert b64url_decode(payload).decode() == "a.png"
|
||||
|
||||
|
||||
@@ -227,16 +209,10 @@ def test_local_markdown_image_rejects_workspace_escape(
|
||||
assert list((media / "websocket").iterdir()) == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# /api/media/<sig>/<payload>: the serving handler
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_media_route_serves_signed_file(
|
||||
bus: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Valid signature + existing file => 200 with correct bytes + MIME."""
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
target = media / "round-trip.png"
|
||||
@@ -268,7 +244,6 @@ async def test_media_route_serves_signed_file(
|
||||
async def test_media_route_serves_video_byte_ranges(
|
||||
bus: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""MP4 playback needs HTTP Range support for mid-stream reads and seeking."""
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
target = media / "clip.mp4"
|
||||
@@ -370,7 +345,6 @@ async def test_media_route_rejects_bad_signature(
|
||||
good = _sign_media_path(channel, media / "f.png")
|
||||
assert good is not None
|
||||
_, payload = good[len("/api/media/"):].split("/", 1)
|
||||
# Forge a sig with a *different* secret.
|
||||
forged_mac = hmac.new(
|
||||
b"\x00" * 32, payload.encode("ascii"), hashlib.sha256
|
||||
).digest()[:16]
|
||||
@@ -401,7 +375,6 @@ async def test_media_route_rejects_path_traversal_payload(
|
||||
secret_file.write_text("classified")
|
||||
|
||||
channel = _ch(bus, port=29922)
|
||||
# Hand-craft a traversal payload the legit signer would refuse to mint.
|
||||
payload = b64url_encode(b"../secret.txt")
|
||||
mac = hmac.new(
|
||||
channel.gateway.media.secret, payload.encode("ascii"), hashlib.sha256
|
||||
@@ -434,7 +407,7 @@ async def test_media_route_404s_missing_file(
|
||||
with patch("nanobot.webui.media_gateway.get_media_dir", return_value=media):
|
||||
url_path = _sign_media_path(channel, target)
|
||||
assert url_path is not None
|
||||
target.unlink() # the file vanishes between signing and fetching
|
||||
target.unlink()
|
||||
server_task = asyncio.create_task(channel.start())
|
||||
try:
|
||||
resp = await _http_get(f"http://127.0.0.1:29923{url_path}")
|
||||
@@ -481,7 +454,6 @@ async def test_media_route_degrades_non_image_to_octet_stream(
|
||||
async def test_media_route_serves_svg_with_strict_csp(
|
||||
bus: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""Generated SVG can preview as an image without becoming executable HTML."""
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
target = media / "chart.svg"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Connection-local outbound delivery guarantees for the WebSocket channel."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Boundary tests for pure WebSocket protocol helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Test websocket subscribe hydration only replays known active turns."""
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
@@ -52,7 +50,6 @@ def _delivery(history, tmp_path) -> tuple[WebUIOutboundDelivery, _RecordingTrans
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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."""
|
||||
outbound, transport = _delivery(history, tmp_path)
|
||||
|
||||
with patch("nanobot.webui.session_projection.websocket_turn_wall_started_at", return_value=None):
|
||||
@@ -63,7 +60,6 @@ async def test_subscribe_hydration_is_quiet_when_no_turn_active(history, tmp_pat
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subscribe_hydration_pushes_running_when_turn_active(history, tmp_path):
|
||||
"""Reconnecting client should receive running status when turn is active."""
|
||||
outbound, transport = _delivery(history, tmp_path)
|
||||
|
||||
with (
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""WebUI admission binds the generation of the session that executes the turn."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -172,7 +172,6 @@ class WsTestClient:
|
||||
assert self._ws is not None, "Client is not connected"
|
||||
return self._ws
|
||||
|
||||
# -- Receiving --------------------------------------------------------
|
||||
|
||||
async def recv_raw(self, timeout: float = 10.0) -> dict[str, Any]:
|
||||
"""Receive and parse one raw JSON message with timeout."""
|
||||
@@ -216,7 +215,6 @@ class WsTestClient:
|
||||
"""Receive exactly *n* messages."""
|
||||
return [await self.recv(timeout) for _ in range(n)]
|
||||
|
||||
# -- Sending ----------------------------------------------------------
|
||||
|
||||
async def send_text(self, text: str) -> None:
|
||||
"""Send a plain text frame."""
|
||||
@@ -226,16 +224,12 @@ class WsTestClient:
|
||||
"""Send a JSON frame."""
|
||||
await self.ws.send(json.dumps(data, ensure_ascii=False))
|
||||
|
||||
# -- Connection introspection -----------------------------------------
|
||||
|
||||
@property
|
||||
def closed(self) -> bool:
|
||||
return self._ws is None or self._ws.closed
|
||||
|
||||
|
||||
# -- Token issuance helpers -----------------------------------------------
|
||||
|
||||
|
||||
async def http_get(
|
||||
url: str,
|
||||
headers: dict[str, str] | list[tuple[str, str]] | None = None,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""WebSocket setup validation owned by the channel package."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
|
||||
Reference in new issue
Block a user