Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(web): WebChannel WS 承载改造为 uvicorn+FastAPI 同端口双协议

yechenzhen78803275a314
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 61ae62b618..165ed6ba5f 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -24,7 +24,7 @@ import sys
import time
import uuid as uuid_module
from dataclasses import dataclass, field
-from typing import Any, Awaitable, Callable
+from typing import Any, Awaitable, Callable, NamedTuple
from urllib.parse import urlparse
from websockets.exceptions import ConnectionClosed, ConnectionClosedError
@@ -1571,11 +1571,21 @@ def _build_route_config_map(bindings: list[GatewayRouteBinding]) -> dict[str, Ro
}
+class _WebBindSettings(NamedTuple):
+ """Web 监听绑定参数包(G.FNM.03:相关参数具名封装)。"""
+
+ web_host: str
+ web_port: int
+ web_path: str
+ web_dual_protocol: bool
+
+
async def _run(
agent_server_url: str,
web_host: str,
web_port: int,
web_path: str,
+ web_dual_protocol: bool = True,
) -> None:
from jiuwenswarm.telemetry.runtime import ProcessTelemetryLifecycle
@@ -1587,9 +1597,7 @@ async def _run(
try:
restart_requested = await _run_with_telemetry(
agent_server_url,
- web_host,
- web_port,
- web_path,
+ _WebBindSettings(web_host, web_port, web_path, web_dual_protocol),
telemetry_lifecycle,
)
finally:
@@ -1601,11 +1609,10 @@ async def _run(
async def _run_with_telemetry(
agent_server_url: str,
- web_host: str,
- web_port: int,
- web_path: str,
+ web_bind: _WebBindSettings,
telemetry_lifecycle,
) -> bool:
+ web_host, web_port, web_path, web_dual_protocol = web_bind
from jiuwenswarm.common.model_client_extensions import load_extra_model_clients
load_extra_model_clients()
@@ -2121,6 +2128,7 @@ async def _run_with_telemetry(
host=web_host,
ws_port=web_port,
path=web_path,
+ dual_protocol=web_dual_protocol,
)
web_channel = WebChannel(web_config, _DummyBus())
@@ -3239,6 +3247,8 @@ def main() -> None:
web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1")
web_port = args.port or int(os.getenv("WEB_PORT", "19000"))
web_path = args.web_path or os.getenv("WEB_PATH", "/ws")
+ _dual_raw = os.getenv("WEB_DUAL_PROTOCOL", "1").strip().lower()
+ web_dual_protocol = _dual_raw not in {"0", "false", "no", "off"}
install_async_dump_handler("gateway")
asyncio.run(
@@ -3247,6 +3257,7 @@ def main() -> None:
web_host=web_host,
web_port=web_port,
web_path=web_path,
+ web_dual_protocol=web_dual_protocol,
)
)
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_channel_app.py b/jiuwenswarm/gateway/channel_manager/web/web_channel_app.py
new file mode 100644
index 0000000000..28e016d977
--- /dev/null
+++ b/jiuwenswarm/gateway/channel_manager/web/web_channel_app.py
@@ -0,0 +1,138 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""FastAPI app for WebChannel: WebSocket now, optional HTTP routes later (same port)."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+from fastapi import FastAPI, WebSocket
+from fastapi.responses import PlainTextResponse
+
+from jiuwenswarm.common.security.ws_origin import (
+ get_header_value,
+ is_allowed_browser_origin,
+ is_origin_check_enabled,
+)
+from jiuwenswarm.gateway.channel_manager.web.ws_connection_adapter import (
+ StarletteWsAdapter,
+)
+
+if TYPE_CHECKING:
+ from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel
+
+logger = logging.getLogger(__name__)
+
+_FORBIDDEN_ORIGIN_BODY = "Forbidden: Origin not allowed\n"
+_GIT_WS_PATH = "/ws/git"
+
+
+def build_web_channel_app(channel: WebChannel) -> FastAPI:
+ """Build the dual-protocol capable app bound to one WebChannel instance.
+
+ Phase 1: WebSocket endpoints for ``channel.config.path`` (default ``/ws``)
+ and hard-coded ``/ws/git``. Later: register HTTP routes on the same ``app``
+ without changing existing WS JSON-RPC methods.
+ """
+ app = FastAPI(
+ title="JiuwenSwarm WebChannel",
+ docs_url=None,
+ redoc_url=None,
+ openapi_url=None,
+ )
+ app.state.web_channel = channel
+
+ # Extension point for future same-port HTTP (e.g. container file API).
+ # Keep unused in Phase 1 so WS behavior stays the sole surface.
+ register_http_routes(app, channel)
+
+ # Register the raw config.path: _connection_handler compares request_path
+ # against the un-normalized value, so normalizing here (e.g. stripping a
+ # trailing slash from WEB_PATH="/ws/") would desync route registration
+ # from the handler's path check.
+ main_path = channel.config.path
+
+ async def websocket_endpoint(websocket: WebSocket) -> None:
+ await _serve_channel_websocket(channel, websocket)
+
+ # Honor WEB_PATH / --web-path (same as legacy handle_connection path check).
+ app.add_api_websocket_route(main_path, websocket_endpoint)
+ if main_path != _GIT_WS_PATH:
+ app.add_api_websocket_route(_GIT_WS_PATH, websocket_endpoint)
+ else:
+ logger.warning(
+ "WebChannel config.path=%s conflicts with git WS path; "
+ "only registering once (git handler wins in handle_connection)",
+ main_path,
+ )
+
+ return app
+
+
+def register_http_routes(app: FastAPI, channel: WebChannel) -> None:
+ """Register optional HTTP routes on the WebChannel port.
+
+ Intentionally empty in Phase 1. Future uploads/downloads should be added here
+ (or via included routers) so ``/ws`` remains unchanged.
+ """
+ _ = (app, channel)
+
+
+async def _serve_channel_websocket(channel: WebChannel, websocket: WebSocket) -> None:
+ if await _reject_disallowed_origin(websocket):
+ return
+
+ adapter = StarletteWsAdapter(websocket)
+ await adapter.accept()
+ try:
+ await channel.handle_connection(adapter, path=adapter.path)
+ except Exception:
+ logger.exception(
+ "WebChannel dual-protocol WS handler crashed path=%s remote=%s",
+ adapter.path,
+ adapter.remote_address,
+ )
+ if not adapter.closed:
+ await adapter.close(code=1011, reason="internal error")
+
+
+async def _reject_disallowed_origin(websocket: WebSocket) -> bool:
+ """Return True when the handshake was rejected (HTTP 403)."""
+ enable_origin_check = is_origin_check_enabled()
+ origin = get_header_value(websocket.headers, "Origin")
+ if not enable_origin_check:
+ logger.info(
+ "WebChannel 握手检查 path=%s origin=%s enable_origin_check=%s allowed=%s",
+ websocket.url.path,
+ origin,
+ enable_origin_check,
+ True,
+ )
+ return False
+
+ allowed = is_allowed_browser_origin(origin)
+ logger.info(
+ "WebChannel 握手检查 path=%s origin=%s enable_origin_check=%s allowed=%s",
+ websocket.url.path,
+ origin,
+ enable_origin_check,
+ allowed,
+ )
+ if allowed:
+ return False
+
+ logger.warning(
+ "WebChannel 握手拒绝 path=%s origin=%s reason=origin_not_allowed",
+ websocket.url.path,
+ origin,
+ )
+ await websocket.send_denial_response(
+ PlainTextResponse(_FORBIDDEN_ORIGIN_BODY, status_code=403),
+ )
+ return True
+
+
+def mount_future_http_router(app: FastAPI, router: Any) -> None:
+ """Helper for later phases: ``app.include_router(router, prefix=...)``."""
+ app.include_router(router)
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
index be3ad071be..70befe78f4 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
@@ -275,6 +275,10 @@ class WebChannel(BaseChannel):
async def stop_http(self) -> None:
await self.http.stop()
+ async def handle_connection(self, ws: Any, path: str | None = None) -> None:
+ """Public entry for serving one accepted WebSocket (dual-protocol / adapters)."""
+ await self.ws.handle_connection(ws, path=path)
+
async def start(self) -> None:
"""Start WebSocket and Gateway Web HTTP; block until WS server closes."""
if self._running:
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py
index 52d386cc76..0490b0405f 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py
@@ -10,6 +10,8 @@ import json
import logging
import os
import secrets
+import socket
+import sys
import threading
import time
import uuid
@@ -127,6 +129,9 @@ class WebChannelConfig:
http_port: int
path: str
allow_from: list[str]
+ # True: uvicorn+FastAPI on the WS port (WS now; HTTP routes can be added later).
+ # False: legacy websockets.serve only (rollback).
+ dual_protocol: bool
def __init__(
self,
@@ -138,6 +143,7 @@ class WebChannelConfig:
path: str = "/ws",
allow_from: list[str] | None = None,
port: int | None = None,
+ dual_protocol: bool = True,
) -> None:
if port is not None:
ws_port = port
@@ -149,6 +155,7 @@ class WebChannelConfig:
self.http_port = int(http_port) if http_port is not None else self.ws_port + 2
self.path = path
self.allow_from = list(allow_from or [])
+ self.dual_protocol = dual_protocol
self.__post_init__()
def __post_init__(self) -> None:
@@ -180,6 +187,8 @@ class WebWsTransport(BaseWsChannel):
self._owner = owner
self.config: WebChannelConfig = config
self._server: Any = None
+ self._uvicorn_server: Any = None
+ self._uvicorn_task: asyncio.Task[None] | None = None
# ws -> set[session_id]: 追踪每个连接上活跃的 session
self._ws_sessions: dict[int, set[str]] = {}
# session_id -> is_processing
@@ -627,6 +636,60 @@ class WebWsTransport(BaseWsChannel):
logger.warning("WebWsTransport 未启用(enabled=False)")
return
+ if self.config.dual_protocol:
+ await self._start_dual_protocol()
+ return
+ await self._start_websockets_legacy()
+
+ async def _start_dual_protocol(self) -> None:
+ """Same port: FastAPI/uvicorn (WS today; HTTP routes can be mounted later)."""
+ import uvicorn
+
+ from jiuwenswarm.common.ws_limits import WEB_WS_MAX_MESSAGE_BYTES
+ from jiuwenswarm.gateway.channel_manager.web.web_channel_app import (
+ build_web_channel_app,
+ )
+
+ app = build_web_channel_app(self._owner)
+ uv_cfg = uvicorn.Config(
+ app,
+ host=self.config.host,
+ port=self.config.ws_port,
+ log_level="info",
+ access_log=False,
+ ws_max_size=WEB_WS_MAX_MESSAGE_BYTES,
+ ws_ping_interval=20.0,
+ ws_ping_timeout=60.0,
+ )
+ # Bind here, not inside the serve task: uvicorn swallows bind errors
+ # with sys.exit(1) inside serve(), which would defer port conflicts
+ # (SystemExit) past the "已启动" log and HTTP startup. A pre-bound
+ # socket also fails fast with a plain OSError instead.
+ family = socket.AF_INET6 if ":" in (self.config.host or "") else socket.AF_INET
+ sock = socket.socket(family, socket.SOCK_STREAM)
+ if sys.platform != "win32":
+ # Match uvicorn/asyncio defaults on POSIX (fast TIME_WAIT rebinding);
+ # SO_REUSEADDR on Windows enables port theft, so skip it there.
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ sock.bind((self.config.host, self.config.ws_port))
+ except OSError:
+ sock.close()
+ raise
+ self._uvicorn_server = uvicorn.Server(uv_cfg)
+ # serve() blocks; run it as a task so start() can bring up the HTTP
+ # listener afterwards (dev-stable's start/wait_closed split).
+ self._uvicorn_task = asyncio.create_task(self._uvicorn_server.serve(sockets=[sock]))
+ self._running = True
+ logger.info(
+ "WebChannel WS 已启动(dual_protocol): ws://%s:%s%s (HTTP-ready same port)",
+ self.config.host,
+ self.config.ws_port,
+ self.config.path,
+ )
+
+ async def _start_websockets_legacy(self) -> None:
+ """Rollback path: pure websockets.serve (no HTTP on this port)."""
try:
from websockets.legacy.server import serve as ws_serve
except Exception: # pragma: no cover
@@ -647,10 +710,13 @@ class WebWsTransport(BaseWsChannel):
)
self._running = True
logger.info(
- f"WebChannel WS 已启动: ws://{self.config.host}:{self.config.ws_port}{self.config.path}"
+ f"WebChannel WS 已启动(legacy): ws://{self.config.host}:{self.config.ws_port}{self.config.path}"
)
async def wait_closed(self) -> None:
+ if self._uvicorn_task is not None:
+ await self._uvicorn_task
+ return
if self._server is not None:
await self._server.wait_closed()
@@ -663,6 +729,17 @@ class WebWsTransport(BaseWsChannel):
await asyncio.gather(*close_tasks, return_exceptions=True)
self._clients_by_key.clear()
+ if self._uvicorn_server is not None:
+ self._uvicorn_server.should_exit = True
+ if self._uvicorn_task is not None:
+ try:
+ await self._uvicorn_task
+ except asyncio.CancelledError: # pragma: no cover
+ pass
+ except Exception:
+ logger.warning("WebChannel uvicorn task 异常退出", exc_info=True)
+ self._uvicorn_server = None
+ self._uvicorn_task = None
if self._server is not None:
self._server.close()
await self._server.wait_closed()
@@ -1070,6 +1147,10 @@ class WebWsTransport(BaseWsChannel):
# ── 内部实现 ──────────────────────────────────────────
+ async def handle_connection(self, ws: Any, path: str | None = None) -> None:
+ """Public entry for serving one accepted WebSocket (dual-protocol / adapters)."""
+ await self._connection_handler(ws, path=path)
+
async def _connection_handler(self, ws: Any, path: str | None = None) -> None:
raw_path = path if path is not None else getattr(ws, "path", "")
parsed = urlparse(raw_path)
diff --git a/jiuwenswarm/gateway/channel_manager/web/ws_connection_adapter.py b/jiuwenswarm/gateway/channel_manager/web/ws_connection_adapter.py
new file mode 100644
index 0000000000..d3656d3058
--- /dev/null
+++ b/jiuwenswarm/gateway/channel_manager/web/ws_connection_adapter.py
@@ -0,0 +1,119 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Adapt Starlette WebSocket to the websockets-like surface WebChannel expects."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
+from websockets.exceptions import (
+ ConnectionClosed,
+ ConnectionClosedError,
+ ConnectionClosedOK,
+)
+from websockets.frames import Close
+
+
+class StarletteWsAdapter:
+ """Thin adapter so existing WebChannel handlers keep using ``send`` / ``async for`` / ``closed``.
+
+ Future HTTP routes on the same uvicorn app do not go through this adapter.
+ """
+
+ def __init__(self, websocket: WebSocket) -> None:
+ self._ws = websocket
+ self._closed = False
+ self._close_code = 1006
+ self._close_reason = ""
+ # Match websockets: path includes query string when present.
+ path = websocket.url.path or ""
+ query = websocket.url.query or ""
+ self.path = f"{path}?{query}" if query else path
+ client = websocket.client
+ self.remote_address: tuple[str, int] | None = (
+ (client.host, client.port) if client is not None else None
+ )
+ self.local_address: tuple[str, int] | None = None
+ scope_server = websocket.scope.get("server")
+ if isinstance(scope_server, (list, tuple)) and len(scope_server) >= 2:
+ self.local_address = (str(scope_server[0]), int(scope_server[1]))
+ # Headers containers used by WebChannel._extract_ws_header_user_id / Origin helpers.
+ self.request_headers = websocket.headers
+ self.request = type("Request", (), {"headers": websocket.headers, "path": self.path})()
+
+ @property
+ def closed(self) -> bool:
+ if self._closed:
+ return True
+ return self._ws.client_state == WebSocketState.DISCONNECTED
+
+ @property
+ def state(self) -> Any:
+ return self._ws.client_state
+
+ def _closed_exc(self) -> ConnectionClosed:
+ frame = Close(self._close_code, self._close_reason or "")
+ if self._close_code == 1000:
+ return ConnectionClosedOK(frame, None)
+ return ConnectionClosedError(frame, None)
+
+ def _mark_closed(self, code: int | None = None, reason: str | None = None) -> None:
+ self._closed = True
+ if code is not None:
+ self._close_code = int(code)
+ if reason is not None:
+ self._close_reason = str(reason)
+
+ async def accept(self, **kwargs: Any) -> None:
+ await self._ws.accept(**kwargs)
+
+ async def send(self, data: str | bytes) -> None:
+ if self.closed:
+ raise self._closed_exc()
+ try:
+ if isinstance(data, bytes):
+ await self._ws.send_bytes(data)
+ else:
+ await self._ws.send_text(data)
+ except WebSocketDisconnect as exc:
+ self._mark_closed(exc.code, exc.reason)
+ raise self._closed_exc() from exc
+
+ async def recv(self) -> str | bytes:
+ if self.closed:
+ raise self._closed_exc()
+ try:
+ message = await self._ws.receive()
+ except WebSocketDisconnect as exc:
+ self._mark_closed(exc.code, exc.reason)
+ raise self._closed_exc() from exc
+
+ msg_type = message.get("type")
+ if msg_type == "websocket.disconnect":
+ self._mark_closed(message.get("code", 1006), message.get("reason", ""))
+ raise self._closed_exc()
+ if "text" in message and message["text"] is not None:
+ return message["text"]
+ if "bytes" in message and message["bytes"] is not None:
+ return message["bytes"]
+ self._mark_closed(1006, "empty websocket frame")
+ raise self._closed_exc()
+
+ async def close(self, code: int = 1000, reason: str = "") -> None:
+ if self.closed:
+ return
+ self._mark_closed(code, reason)
+ try:
+ await self._ws.close(code=code, reason=reason or "")
+ except Exception: # noqa: BLE001 — best-effort close
+ return
+
+ def __aiter__(self) -> StarletteWsAdapter:
+ return self
+
+ async def __anext__(self) -> str | bytes:
+ try:
+ return await self.recv()
+ except ConnectionClosed:
+ raise StopAsyncIteration from None
diff --git a/tests/unit_tests/channel/test_web_channel_dual_protocol.py b/tests/unit_tests/channel/test_web_channel_dual_protocol.py
new file mode 100644
index 0000000000..7efe2bb9a5
--- /dev/null
+++ b/tests/unit_tests/channel/test_web_channel_dual_protocol.py
@@ -0,0 +1,236 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for WebChannel dual-protocol (same-port WS; HTTP-ready) Phase 1.
+
+Avoid fastapi/starlette TestClient: some CI images ship a Starlette that requires
+``httpx2`` and fail at import time. Exercise FastAPI route registration and the
+public ``handle_connection`` path with a lightweight fake websocket instead.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import socket
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter
+from jiuwenswarm.gateway.channel_manager.web.web_channel_app import (
+ _reject_disallowed_origin,
+ build_web_channel_app,
+)
+from jiuwenswarm.gateway.channel_manager.web.web_connect import (
+ WebChannel,
+ WebChannelConfig,
+)
+from jiuwenswarm.gateway.channel_manager.web.ws_connection_adapter import (
+ StarletteWsAdapter,
+)
+
+
+def _make_channel(**kwargs: Any) -> WebChannel:
+ cfg = WebChannelConfig(enabled=True, dual_protocol=True, **kwargs)
+ return WebChannel(cfg, RobotMessageRouter())
+
+
+def _route_paths(app: Any) -> set[str | None]:
+ return {getattr(r, "path", None) for r in app.router.routes}
+
+
+class _QueueWebSocket:
+ """Minimal websockets-like surface for ``WebChannel.handle_connection``."""
+
+ def __init__(self, path: str, inbound: list[str]) -> None:
+ self.path = path
+ self.remote_address = ("127.0.0.1", 12345)
+ self.closed = False
+ self.close_code: int | None = None
+ self.close_reason: str | None = None
+ self.sent: list[dict[str, Any]] = []
+ self._inbound = list(inbound)
+ self._idx = 0
+
+ async def send(self, data: str | bytes) -> None:
+ if isinstance(data, bytes):
+ data = data.decode("utf-8")
+ self.sent.append(json.loads(data))
+
+ async def close(self, code: int = 1000, reason: str = "") -> None:
+ self.closed = True
+ self.close_code = code
+ self.close_reason = reason
+
+ def __aiter__(self) -> _QueueWebSocket:
+ return self
+
+ async def __anext__(self) -> str:
+ if self._idx >= len(self._inbound):
+ raise StopAsyncIteration
+ item = self._inbound[self._idx]
+ self._idx += 1
+ return item
+
+
+def test_build_app_exposes_ws_routes_only() -> None:
+ channel = _make_channel()
+ app = build_web_channel_app(channel)
+ paths = _route_paths(app)
+ assert "/ws" in paths
+ assert "/ws/git" in paths
+ assert "/container-file-api/upload" not in paths
+ assert "/file-api/upload" not in paths
+
+
+def test_build_app_registers_custom_config_path() -> None:
+ channel = _make_channel(path="/custom")
+ app = build_web_channel_app(channel)
+ paths = _route_paths(app)
+ assert "/custom" in paths
+ assert "/ws/git" in paths
+ assert "/ws" not in paths
+
+
+def test_build_app_registers_raw_config_path() -> None:
+ """Route registration must match _connection_handler's raw config.path check."""
+ channel = _make_channel(path="/ws/")
+ app = build_web_channel_app(channel)
+ assert "/ws/" in _route_paths(app)
+ assert "/ws/git" in _route_paths(app)
+
+
+def _register_ping(channel: WebChannel) -> None:
+ channel.on_message(lambda _msg: False)
+
+ async def _ping(ws, req_id, params, session_id):
+ await channel.send_response(
+ ws, req_id, ok=True, payload={"pong": True, "session_id": session_id},
+ )
+
+ channel.register_method("test.ping", _ping)
+
+
+async def _ping_roundtrip(channel: WebChannel, path: str) -> None:
+ _register_ping(channel)
+ req = json.dumps(
+ {
+ "type": "req",
+ "id": "r1",
+ "method": "test.ping",
+ "params": {},
+ }
+ )
+ ws = _QueueWebSocket(f"{path}?user_id=alice&session_id=sess-1", [req])
+ await channel.handle_connection(ws, path=ws.path)
+ # Writer may flush asynchronously after handler returns; give it a tick.
+ await asyncio.sleep(0)
+ for _ in range(20):
+ if any(f.get("type") == "res" and f.get("id") == "r1" for f in ws.sent):
+ break
+ await asyncio.sleep(0.01)
+ matches = [f for f in ws.sent if f.get("type") == "res" and f.get("id") == "r1"]
+ assert matches, f"no ping response in {ws.sent!r}"
+ assert matches[0]["ok"] is True
+ assert matches[0]["payload"]["pong"] is True
+
+
+async def test_dual_protocol_ws_jsonrpc_roundtrip() -> None:
+ await _ping_roundtrip(_make_channel(), "/ws")
+
+
+async def test_dual_protocol_custom_path_jsonrpc_roundtrip() -> None:
+ await _ping_roundtrip(_make_channel(path="/custom"), "/custom")
+
+
+async def test_dual_protocol_ws_git_path_closes_without_registry() -> None:
+ """/ws/git accepts then closes with 1011 if git registry is absent (same as legacy)."""
+ channel = _make_channel()
+ ws = _QueueWebSocket("/ws/git?user_id=alice", [])
+ await channel.handle_connection(ws, path=ws.path)
+ assert ws.closed is True
+ assert ws.close_code == 1011
+
+
+async def test_origin_rejected_when_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("JIUWENSWARM_ENABLE_ORIGIN_CHECK", "1")
+ monkeypatch.setenv("JIUWENSWARM_WS_ALLOWED_ORIGIN_HOSTS", "allowed.example")
+
+ websocket = MagicMock()
+ websocket.headers = {"origin": "https://evil.example"}
+ websocket.url.path = "/ws"
+ websocket.send_denial_response = AsyncMock()
+
+ rejected = await _reject_disallowed_origin(websocket)
+ assert rejected is True
+ websocket.send_denial_response.assert_awaited_once()
+
+
+def test_starlette_adapter_path_includes_query() -> None:
+ websocket = MagicMock()
+ websocket.url.path = "/ws"
+ websocket.url.query = "token=abc&user_id=u1"
+ websocket.client = MagicMock(host="127.0.0.1", port=9)
+ websocket.scope = {"server": ("0.0.0.0", 19000)}
+ websocket.headers = {"x-user-id": "u1"}
+ websocket.client_state = MagicMock()
+
+ adapter = StarletteWsAdapter(websocket)
+ assert adapter.path == "/ws?token=abc&user_id=u1"
+ assert adapter.remote_address == ("127.0.0.1", 9)
+ assert adapter.request_headers.get("x-user-id") == "u1"
+
+
+def test_webchannel_config_dual_protocol_default_true() -> None:
+ assert WebChannelConfig().dual_protocol is True
+
+
+def test_webchannel_config_legacy_flag() -> None:
+ assert WebChannelConfig(dual_protocol=False).dual_protocol is False
+
+
+async def _raise_runtime_error() -> None:
+ raise RuntimeError("uvicorn boom")
+
+
+async def test_stop_ws_server_completes_cleanup_when_uvicorn_task_fails() -> None:
+ """Non-CancelledError from the uvicorn task must not abort stop cleanup."""
+ transport = _make_channel().ws
+ transport._uvicorn_server = MagicMock()
+ transport._uvicorn_task = asyncio.create_task(_raise_runtime_error())
+ await asyncio.sleep(0) # let the task fail and surface the exception
+ with pytest.raises(RuntimeError):
+ transport._uvicorn_task.result()
+
+ await transport.stop_ws_server()
+
+ assert transport._uvicorn_server is None
+ assert transport._uvicorn_task is None
+ assert transport._running is False
+
+
+async def test_dual_protocol_trailing_slash_path_roundtrip() -> None:
+ """WEB_PATH="/ws/" deployments keep working: route and handler agree on "/ws/"."""
+ await _ping_roundtrip(_make_channel(path="/ws/"), "/ws/")
+
+
+async def test_dual_protocol_start_fails_fast_when_port_occupied(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Port conflict must raise OSError from start_ws_server, not SystemExit later."""
+ with socket.create_server(("127.0.0.1", 0)) as blocker:
+ channel = _make_channel(host="127.0.0.1", ws_port=blocker.getsockname()[1])
+ with caplog.at_level(logging.INFO), pytest.raises(OSError):
+ await channel.ws.start_ws_server()
+ assert channel.ws._uvicorn_task is None
+ assert channel.ws._running is False
+ assert not any("已启动" in rec.message for rec in caplog.records)