Skip to content

Your lightweight open-source personal agent.

fix(websocket): abort disconnected HTTP handshakes before sending (#6348)

chengyongru927eba89ea65
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 40e2edb77..4cf47f856 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -102,6 +102,14 @@ jobs:
- name: Install dependencies
run: uv sync --all-extras --dev
+ # Feishu selects websockets<16. Check the default transport before the
+ # all-channel suite exercises the older compatible resolution.
+ - name: Test default WebSocket transport
+ run: >-
+ uv run --no-sync python -m pytest -q
+ nanobot/channels/websocket/tests/test_handshake_disconnect.py
+ nanobot/channels/websocket/tests/test_binary_http.py
+
- name: Install channel dependencies
run: uv run --no-sync python -m scripts.install_channel_dependencies --all-channels
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index d712205ab..161a6f449 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -20,6 +20,8 @@ from pydantic import Field, PrivateAttr, field_validator, model_validator
from websockets.asyncio.server import Server, ServerConnection, serve, unix_serve
from websockets.exceptions import ConnectionClosed
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,
@@ -705,6 +707,20 @@ class WebSocketChannel(BaseChannel):
) -> Any:
return await self._dispatch_http(connection, request)
+ def process_response(
+ connection: ServerConnection, _request: WsRequest, response: WsResponse,
+ ) -> WsResponse:
+ # Stay synchronous: websockets sends immediately after this hook returns.
+ if connection.state is not CONNECTING:
+ exc = connection.protocol.handshake_exc
+ if exc is not None:
+ connection.logger.error(
+ "opening handshake failed", exc_info=(type(exc), exc, exc.__traceback__),
+ )
+ # The request callback finished; cancel only this connection's handshake.
+ raise asyncio.CancelledError("Peer disconnected before handshake response")
+ return response
+
async def handler(connection: ServerConnection) -> None:
await self._connection_loop(connection)
@@ -745,6 +761,7 @@ class WebSocketChannel(BaseChannel):
handler,
socket_path,
process_request=process_request,
+ process_response=process_response,
create_connection=bridge.connection_factory,
open_timeout=_WEBUI_HTTP_OPEN_TIMEOUT_S,
max_size=self.config.max_message_bytes,
@@ -760,6 +777,7 @@ class WebSocketChannel(BaseChannel):
self.config.host,
self.config.port,
process_request=process_request,
+ process_response=process_response,
create_connection=bridge.connection_factory,
open_timeout=_WEBUI_HTTP_OPEN_TIMEOUT_S,
max_size=self.config.max_message_bytes,
diff --git a/nanobot/channels/websocket/tests/test_handshake_disconnect.py b/nanobot/channels/websocket/tests/test_handshake_disconnect.py
new file mode 100644
index 000000000..b1d5ba4fa
--- /dev/null
+++ b/nanobot/channels/websocket/tests/test_handshake_disconnect.py
@@ -0,0 +1,168 @@
+"""Real listener regressions for peer disconnects while an HTTP route awaits."""
+
+import asyncio
+import json
+import logging
+import sys
+from contextlib import asynccontextmanager
+
+import pytest
+from websockets.asyncio.client import connect, unix_connect
+
+from nanobot.bus.queue import MessageBus
+from nanobot.channels.websocket import runtime
+from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
+from nanobot.webui.gateway_services import build_gateway_services
+from nanobot.webui.websocket_logging import WebSocketHandshakeNoiseFilter
+
+
+@asynccontextmanager
+async def _listener(tmp_path, monkeypatch, caplog, unix, process_request):
+ if unix and sys.platform == "win32":
+ pytest.skip("asyncio Unix sockets are unavailable on Windows")
+ config = WebSocketConfig(
+ enabled=True, allow_from=["*"], host="127.0.0.1", port=0, path="/ws",
+ websocket_requires_token=False,
+ unix_socket_path=str(tmp_path / "ws.sock") if unix else "",
+ )
+ bus = MessageBus()
+ gateway = build_gateway_services(
+ config=config, bus=bus, session_manager=None, static_dist_path=None,
+ workspace_path=tmp_path, default_restrict_to_workspace=False,
+ runtime_model_name=None, runtime_surface="browser",
+ runtime_capabilities_overrides=None,
+ )
+ channel = WebSocketChannel(config.model_dump(), bus, gateway=gateway)
+ dispatch_http = channel._dispatch_http
+
+ async def dispatch(connection, request):
+ if request.path in {"/delayed", "/probe"}:
+ return await process_request(connection, 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())
+ monkeypatch.setattr(runtime, "websockets_server_logger", lambda: logger)
+ task = asyncio.create_task(channel.start())
+ try:
+ async with asyncio.timeout(5):
+ while channel._server is None or not channel._server.is_serving():
+ if task.done():
+ await task
+ raise AssertionError("listener stopped before becoming ready")
+ await asyncio.sleep(0)
+ address = config.unix_socket_path if unix else (
+ "127.0.0.1", channel._server.sockets[0].getsockname()[1],
+ )
+ yield channel, address
+ finally:
+ await channel.stop()
+ await asyncio.wait_for(task, 5)
+
+
+@asynccontextmanager
+async def _stream(address):
+ reader, writer = await (
+ asyncio.open_unix_connection(address) if isinstance(address, str)
+ else asyncio.open_connection(*address)
+ )
+ try:
+ yield reader, writer
+ finally:
+ writer.close()
+ await writer.wait_closed()
+
+
+async def _request(writer, path):
+ writer.write(f"GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".encode())
+ await writer.drain()
+
+
[email protected]("unix", [False, True], ids=["tcp", "unix"])
[email protected]("half_close", [False, True], ids=["close", "half-close"])
+async def test_disconnect_during_http_response_keeps_listener_usable(
+ tmp_path, monkeypatch, caplog, unix, half_close,
+):
+ arrived = asyncio.get_running_loop().create_future()
+ release = asyncio.Event()
+ completed = asyncio.Event()
+
+ async def process_request(connection, request):
+ if request.path == "/delayed":
+ arrived.set_result(connection)
+ await release.wait()
+ completed.set()
+ return connection.respond(200, "healthy\n")
+
+ async with _listener(tmp_path, monkeypatch, caplog, unix, process_request) as (channel, address):
+ try:
+ async with _stream(address) as (_reader, writer):
+ await _request(writer, "/delayed")
+ connection = await asyncio.wait_for(arrived, 2)
+ if half_close:
+ writer.write_eof()
+ await writer.drain()
+ else:
+ writer.close()
+ await writer.wait_closed()
+ await asyncio.wait_for(connection.wait_closed(), 2)
+ release.set()
+
+ async with _stream(address) as (reader, writer):
+ await _request(writer, "/probe")
+ response = await asyncio.wait_for(reader.read(), 2)
+ assert response.startswith(b"HTTP/1.1 200 OK\r\n")
+ assert response.endswith(b"healthy\n")
+ uri = "ws://localhost/ws?client_id=still-alive"
+ client = unix_connect(address, uri=uri) if unix else connect(
+ f"ws://{address[0]}:{address[1]}/ws?client_id=still-alive", proxy=None,
+ )
+ async with client as ws:
+ ready = json.loads(await asyncio.wait_for(ws.recv(), 2))
+ assert ready["event"] == "ready"
+ await ws.send("still-alive")
+ inbound = await asyncio.wait_for(channel.bus.consume_inbound(), 2)
+ assert inbound.content == "still-alive"
+ assert completed.is_set()
+ finally:
+ release.set()
+
+ assert not [r for r in caplog.records if r.name == "websockets.eof-regression"], caplog.text
+
+
[email protected]("unix", [False, True], ids=["tcp", "unix"])
[email protected]("peer_left", [False, True], ids=["connected", "disconnected"])
+async def test_http_callback_failure_remains_visible(
+ tmp_path, monkeypatch, caplog, unix, peer_left,
+):
+ arrived = asyncio.get_running_loop().create_future()
+ release = asyncio.Event()
+ failure = RuntimeError("HTTP callback failed after awaiting")
+
+ async def process_request(connection, request):
+ arrived.set_result(connection)
+ await release.wait()
+ raise failure
+
+ async with _listener(tmp_path, monkeypatch, caplog, unix, process_request) as (_channel, address):
+ try:
+ async with _stream(address) as (reader, writer):
+ await _request(writer, "/delayed")
+ connection = await asyncio.wait_for(arrived, 2)
+ if peer_left:
+ writer.close()
+ await writer.wait_closed()
+ await asyncio.wait_for(connection.wait_closed(), 2)
+ release.set()
+ if not peer_left:
+ response = await asyncio.wait_for(reader.read(), 2)
+ assert response.startswith(b"HTTP/1.1 500 Internal Server Error\r\n")
+ finally:
+ release.set()
+
+ records = [r for r in caplog.records if r.name == "websockets.eof-regression"]
+ assert any(r.exc_info and r.exc_info[1] is failure for r in records), caplog.text
+ assert not any(r.getMessage() == "unexpected internal error" for r in records), caplog.text
diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
index f428f9324..17be8c60b 100644
--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py
+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
@@ -38,6 +38,7 @@ _PORT = 29900
@pytest.fixture(autouse=True)
def _isolate_runtime_data(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
+ monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
class _MatrixChannel(BaseChannel):
diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.py
index 29788e6c4..8681d348d 100644
--- a/tests/webui/test_settings_api.py
+++ b/tests/webui/test_settings_api.py
@@ -52,6 +52,12 @@ DYNAMIC_PROVIDER_NAME = "my-company-api"
DYNAMIC_PROVIDER_API_BASE = "https://example.test/v1"
[email protected](autouse=True)
+def isolate_settings_config(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Settings tests must never fall through to a user's default config."""
+ monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
+
+
@pytest.fixture
def oauth_flows() -> WebUIOAuthFlowRegistry:
return WebUIOAuthFlowRegistry()