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(gateway):Gateway服务端支持HTTP协议
caozhenhua000052fdf808a91f
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.pyindex 591af24d5f..2d0617aa38 100644--- a/jiuwenswarm/channels/web/app_web.py+++ b/jiuwenswarm/channels/web/app_web.py@@ -2,13 +2,16 @@"""Serve built frontend static files with optional reverse proxy.+Production role: SPA + health; business file/share/sessions HTTP lives on+Gateway Web HTTP — this process proxies those paths when Ingress still hits Web.+``/api`` (non-sessions) and ``/ws`` proxy to Gateway WebChannel remain.+Supports ``--dotenv <path>`` for multi-instance isolation."""from __future__ import annotationsimport argparse-import cgiimport errnoimport http.clientimport json@@ -19,12 +22,10 @@ import selectimport socketimport sslimport sys-import timefrom functools import partialfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path-from typing import Any-from urllib.parse import quote, unquote, urlparse+from urllib.parse import unquote, urlparse# --- Early --dotenv parsing (before jiuwenswarm imports) ---from jiuwenswarm.dotenv_early import parse_dotenv_early@@ -32,30 +33,16 @@ parse_dotenv_early("jiuwenswarm-web")# --- Now safe to import jiuwenswarm modules ---from jiuwenswarm.agents.harness.common.tools.ssl_config import get_insecure_ssl_context, get_ssl_verify-from jiuwenswarm.agents.harness.team.bootstrap import configure_agent_teams_homefrom jiuwenswarm.common.debug_dump import install_async_dump_handlerfrom jiuwenswarm.common.ws_diagnostics import describe_ws_exception, format_ws_diagnostics-from jiuwenswarm.common.utils import get_agent_root_dir, get_logs_dir, \- get_agent_sessions_dir, get_multi_tenant_user_workspace_dir, get_root_dir, get_user_workspace_dir, \- is_package_installation, wait_for_tcp_port, SensitiveDataFilter-from jiuwenswarm.channels.web.history_store import (- ChatHistoryStore,- HistoryFrameRunner,- get_session_detail_sync,- list_sessions_sync,+from jiuwenswarm.common.utils import (+ get_logs_dir,+ get_root_dir,+ get_user_workspace_dir,+ wait_for_tcp_port,+ SensitiveDataFilter,)-from jiuwenswarm.server.runtime.session.session_history import history_exists, load_history_records--configure_agent_teams_home()--_history_runner: HistoryFrameRunner | None = None---def _get_agent_teams_root() -> Path:- """Return the agent teams root after dotenv initialization."""- from openjiuwen.agent_teams.paths import get_agent_teams_home-- return get_agent_teams_home().resolve()+from jiuwenswarm.gateway.channel_manager.web.web_http_server import resolve_web_http_portdef _get_package_dir() -> Path:@@ -81,106 +68,6 @@ def _default_dist_dir() -> Path:return dist_dir-def _normalize_lang_suffix(name: str) -> str:- """将 xxxx_zh.MD / xxxx_en.MD 规范为 xxxx.MD(去除 _zh/_en 后缀)。"""- stem, suffix = name.rpartition(".")[0], name.rpartition(".")[2]- suffix_lower = suffix.lower()- if suffix_lower in ("md", "mdx"):- stem_lower = stem.lower()- if stem_lower.endswith("_zh"):- stem = stem[:-3]- elif stem_lower.endswith("_en"):- stem = stem[:-3]- return f"{stem}.{suffix}" if stem else name---def _generate_agent_data(project_root: Path) -> None:- """Generate agent/workspace/agent-data.json from agent tree."""- agent_root = (project_root / "agent").resolve()- workspace_root = (agent_root / "workspace").resolve()- output_path = (workspace_root / "agent-data.json").resolve()- root_folder_key = "__root__"-- if not agent_root.exists():- raise FileNotFoundError("agent directory not found")- if not agent_root.is_dir():- raise NotADirectoryError("agent is not a directory")-- folder_data: dict[str, list[dict[str, str | bool]]] = {}- seen_paths: dict[str, set[str]] = {} # folder_key -> normalized paths,用于去重- for entry in sorted(workspace_root.rglob("*")):- if not entry.is_file() or entry.name.startswith("."):- continue- # Skip files in hidden directories (e.g., .agent_history)- if any(part.startswith(".") for part in entry.relative_to(workspace_root).parts):- continue- relative_folder_path = entry.parent.relative_to(agent_root).as_posix()- folder_key = root_folder_key if relative_folder_path == "." else relative_folder_path-- display_name = _normalize_lang_suffix(entry.name)- display_path = (- f"agent/{relative_folder_path}/{display_name}".replace("/.", "/").replace("//", "/")- if relative_folder_path != "."- else f"agent/{display_name}"- )- seen = seen_paths.setdefault(folder_key, set())- if display_path in seen:- continue # 同一文件夹内 _zh 与 _en 并存时只保留先出现的- seen.add(display_path)-- folder_data.setdefault(folder_key, []).append(- {- "name": display_name,- "path": display_path,- "isMarkdown": entry.suffix.lower() in {".md", ".mdx"},- }- )-- sorted_folder_data = {- folder_key: sorted(files, key=lambda item: item["path"])- for folder_key, files in sorted(folder_data.items(), key=lambda item: item[0])- }-- output_path.parent.mkdir(parents=True, exist_ok=True)- output_path.write_text(- json.dumps(sorted_folder_data, ensure_ascii=False, indent=2),- encoding="utf-8",- )---def _parse_single_byte_range(- range_header: str,- file_size: int,-) -> tuple[int, int] | None:- """Parse one HTTP byte range, returning inclusive start and end offsets."""- if file_size == 0 or not range_header.startswith("bytes=") or "," in range_header:- return None-- range_value = range_header[6:]- if "-" not in range_value:- return None-- start_text, end_text = range_value.split("-", 1)- if not start_text:- if not end_text.isascii() or not end_text.isdecimal():- return None- suffix_length = int(end_text)- if suffix_length <= 0:- return None- return max(0, file_size - suffix_length), file_size - 1-- if not start_text.isascii() or not start_text.isdecimal():- return None- if end_text and (not end_text.isascii() or not end_text.isdecimal()):- return None-- start = int(start_text)- end = int(end_text) if end_text else file_size - 1- if start >= file_size or end < start:- return None- return start, min(end, file_size - 1)--class _SpaStaticHandler(SimpleHTTPRequestHandler):"""Static file handler with SPA fallback to index.html."""@@ -196,13 +83,8 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):api_target = ""ws_target = ""+ web_http_target = ""ws_disable_compress = False- project_root = get_user_workspace_dir()- workspace_root = get_agent_root_dir()- agent_teams_root = _get_agent_teams_root()- logs_root = get_logs_dir()- auto_harness_root = project_root / "auto-harness"- history_db = ""logger = logging.getLogger(__name__)_HOP_BY_HOP_HEADERS = {@@ -386,12 +268,6 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):def _is_ws_route(self) -> bool:return urlparse(self.path).path.startswith("/ws")- def _is_file_api_route(self) -> bool:- return urlparse(self.path).path.startswith("/file-api/")-- def _is_share_api_route(self) -> bool:- return urlparse(self.path).path.startswith("/share-api/")-def _is_websocket_upgrade(self) -> bool:upgrade = self.headers.get("Upgrade", "")connection = self.headers.get("Connection", "")@@ -599,13 +475,9 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):if sock is self.connection:for text_message in client_parser.feed(data):self._log_ws_business_message("frontend->backend", text_message)- if _history_runner is not None:- _history_runner.submit("browser", text_message)else:for text_message in server_parser.feed(data):self._log_ws_business_message("backend->frontend", text_message)- if _history_runner is not None:- _history_runner.submit("uplink", text_message)# 非阻塞 socket 写入:循环增量 send,缓冲区满时等待可写后继续,# 跨平台覆盖 Windows WSAEWOULDBLOCK (10035) 与 POSIX EAGAIN/EWOULDBLOCK。pending = data@@ -660,6 +532,10 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):passdef _dispatch_proxy(self) -> bool:+ # /api/sessions* is handled by _is_web_http_route (Gateway Web HTTP), not WebChannel.+ if self._is_web_http_route():+ self._proxy_web_http()+ return Trueif self._is_api_route():self._proxy_http()return True@@ -671,596 +547,39 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):return Truereturn False- @staticmethod- def _is_markdown(path_obj: Path) -> bool:- ext = path_obj.suffix.lower()- return ext in {".md", ".mdx"}-- @classmethod- def _is_path_under_allowed_root(cls, target: Path) -> bool:- target_resolved = target.resolve()- try:- in_workspace = (- os.path.commonpath([str(cls.workspace_root), str(target_resolved)])- == str(cls.workspace_root)- )- in_agent_teams = (- os.path.commonpath([str(cls.agent_teams_root), str(target_resolved)]) == str(cls.agent_teams_root)- )- in_logs = os.path.commonpath([str(cls.logs_root), str(target_resolved)]) == str(cls.logs_root)- in_auto_harness = \- os.path.commonpath([str(cls.auto_harness_root), str(target_resolved)]) == str(cls.auto_harness_root)- return in_workspace or in_agent_teams or in_logs or in_auto_harness- except ValueError:- return False-- def _write_json(self, status: int, payload: dict) -> None:- data = json.dumps(payload, ensure_ascii=False).encode("utf-8")- self.send_response(status)- self.send_header("Content-Type", "application/json; charset=utf-8")- self.send_header("Content-Length", str(len(data)))- self.end_headers()- if self.command != "HEAD":- self.wfile.write(data)-- @staticmethod- def _parse_query(query: str) -> dict[str, str]:- parsed: dict[str, str] = {}- if not query:- return parsed- for pair in query.split("&"):- if "=" in pair:- k, v = pair.split("=", 1)- else:- k, v = pair, ""- parsed[unquote(k)] = unquote(v)- return parsed-- def _resolve_session_title(self, session_dir: Path, history: list[dict[str, Any]]) -> str:- metadata_path = session_dir / "metadata.json"- if metadata_path.exists():- try:- metadata = json.loads(metadata_path.read_text(encoding="utf-8"))- title = metadata.get("title") if isinstance(metadata, dict) else None- if isinstance(title, str) and title.strip():- return title.strip()- except (OSError, json.JSONDecodeError, UnicodeDecodeError):- pass- for record in history:- if record.get("role") == "user":- content = record.get("content")- if isinstance(content, str) and content.strip():- return content.strip().replace("\n", " ")[:80]- return session_dir.name-- def _build_share_snapshot(- self,- *,- session_id: str,- ) -> tuple[dict[str, Any], str]:- sessions_root = get_agent_sessions_dir().resolve()- session_dir = (sessions_root / session_id).resolve()- try:- if os.path.commonpath([str(sessions_root), str(session_dir)]) != str(sessions_root):- raise FileNotFoundError("history_not_found")- except ValueError as exc:- raise FileNotFoundError("history_not_found") from exc- if not session_dir.exists() or not history_exists(session_id):- raise FileNotFoundError("history_not_found")- try:- history_raw = load_history_records(session_id)- except Exception as exc:- raise ValueError("invalid_history_json") from exc- if not isinstance(history_raw, list):- raise ValueError("invalid_history_shape")-- history = [item for item in history_raw if isinstance(item, dict)]- exported_at = time.strftime("%Y-%m-%dT%H:%M:%S%z")- timestamp = time.strftime("%Y%m%d-%H%M%S")- filename = f"jiuwenswarm-share-{timestamp}.png"- snapshot = {- "session_id": session_id,- "metadata": {- "title": self._resolve_session_title(session_dir, history),- "exported_at": exported_at,- "filename": filename,- },- "records": history_raw,- }- return snapshot, filename-- def _handle_share_api_get(self, parsed) -> None:- if parsed.path != "/share-api/snapshot":- self._write_json(404, {"error": "not_found"})- return- query = self._parse_query(parsed.query)- session_id = query.get("session_id", "").strip()- if not session_id:- self._write_json(400, {"error": "missing_session_id"})- return- try:- snapshot, filename = self._build_share_snapshot(- session_id=session_id,- )- except FileNotFoundError:- self._write_json(404, {"error": "history_not_found"})- return- except ValueError as exc:- self._write_json(400, {"error": str(exc)})- return- self._write_json(200, {"filename": filename, "snapshot": snapshot})-- def _handle_history_api_get(self, parsed) -> bool:- """Enterprise local session history (SQLite); not proxied to Gateway."""- if not os.getenv("AGENT_RUNTIME", "").strip():- return False- if not self.history_db:- return False- path = parsed.path- if path == "/api/sessions":- query = self._parse_query(parsed.query)- try:- limit = int(query.get("limit", "20") or 20)- offset = int(query.get("offset", "0") or 0)- except ValueError:- limit, offset = 20, 0- limit = max(1, min(limit, 100))- offset = max(0, offset)- user = query.get("user") or None- self._write_json(- 200,- {- "sessions": list_sessions_sync(- self.history_db,- limit=limit,- offset=offset,- user=user,- ),- },- )+ def _is_web_http_route(self) -> bool:+ """Paths served by Gateway Web HTTP; proxy when Ingress still points at Web static."""+ path = urlparse(self.path).path+ if path.startswith("/file-api/") or path.startswith("/share-api/"):return True- if path.startswith("/api/sessions/"):- session_id = path[len("/api/sessions/"):]- query = self._parse_query(parsed.query)- user = query.get("user") or None- detail = get_session_detail_sync(self.history_db, session_id, user=user)- if detail is None:- self._write_json(404, {"error": "not_found"})- else:- self._write_json(200, detail)+ if path == "/api/sessions" or path.startswith("/api/sessions/"):+ return True+ if path == "/api/v1" or path.startswith("/api/v1/"):return Truereturn False- def _handle_file_api_get(self, parsed) -> None:- path = parsed.path- query = self._parse_query(parsed.query)-- if path == "/file-api/list-markdown":- dir_arg = query.get("dir", "")- if not dir_arg:- self._write_json(400, {"error": "missing_dir"})- return- full_dir = (self.project_root / dir_arg).resolve()- if not self._is_path_under_allowed_root(full_dir):- self._write_json(403, {"error": "forbidden_dir"})- return- if not full_dir.exists() or not full_dir.is_dir():- self._write_json(200, {"files": []})- return- files = []- for entry in sorted(full_dir.iterdir(), key=lambda p: p.name.lower()):- if not entry.is_file() or not self._is_markdown(entry):- continue- files.append(- {- "name": entry.name,- "path": str(entry.relative_to(self.project_root)),- }- )- self._write_json(200, {"files": files})- return-- if path == "/file-api/list-files":- dir_arg = query.get("dir", "")- if not dir_arg:- self._write_json(400, {"error": "missing_dir"})- return- full_dir = (self.project_root / dir_arg).resolve()- if not self._is_path_under_allowed_root(full_dir):- self._write_json(403, {"error": "forbidden_dir"})- return- if not full_dir.exists() or not full_dir.is_dir():- self._write_json(200, {"files": []})- return- files = []- entries = sorted(- full_dir.iterdir(),- key=lambda p: (not p.is_dir(), p.name.lower()),- )- for entry in entries:- files.append(- {- "name": entry.name,- "path": str(entry.relative_to(self.project_root)),- "isMarkdown": self._is_markdown(entry) if entry.is_file() else False,- "isDirectory": entry.is_dir(),- }- )- self._write_json(200, {"files": files})- return-- if path == "/file-api/raw-file":- file_arg = query.get("path", "")- if not file_arg:- self._write_json(400, {"error": "missing_file_path"})- return- full_path = (self.project_root / file_arg).resolve()- if not self._is_path_under_allowed_root(full_path):- self._write_json(403, {"error": "forbidden_path"})- return- if not full_path.is_file():- self._write_json(404, {"error": "file_not_found"})- return-- mime_type, _ = mimetypes.guess_type(full_path.name)- self.send_response(200)- self.send_header("Content-Type", mime_type or "application/octet-stream")- self.send_header("Content-Length", str(full_path.stat().st_size))- self.send_header("Cache-Control", "no-store")- self.end_headers()- if self.command != "HEAD":- with full_path.open("rb") as file_obj:- while True:- chunk = file_obj.read(65536)- if not chunk:- break- self.wfile.write(chunk)- return-- if path == "/file-api/file-content":- file_arg = query.get("path", "")- encoding_arg = query.get("encoding", "utf-8")- if not file_arg:- self._write_json(400, {"error": "missing_file_path"})- return- full_path = (self.project_root / file_arg).resolve()- if not self._is_path_under_allowed_root(full_path):- self._write_json(403, {"error": "forbidden_path"})- return- if not full_path.exists():- if file_arg.replace("\\", "/") == "agent/workspace/agent-data.json":- try:- _generate_agent_data(self.project_root)- except Exception as exc: # noqa: BLE001- self._write_json(500, {"error": "generate_failed", "detail": str(exc)})- return- if not full_path.exists():- self._write_json(404, {"error": "file_not_found", "fullPath": str(full_path)})- return-- def read_file_with_encoding(file_path: Path, encoding: str) -> tuple[str, str]:- if encoding == "auto":- import charset_normalizer- raw_data = file_path.read_bytes()- detected = charset_normalizer.from_bytes(raw_data).best()- if detected is None:- detected_encoding = "utf-8"- else:- detected_encoding = detected.encoding or "utf-8"- try:- return raw_data.decode(detected_encoding), detected_encoding- except (UnicodeDecodeError, LookupError) as decode_exc:- for try_encoding in ["gbk", "gb2312", "big5", "shift_jis", "euc_kr"]:- try:- return raw_data.decode(try_encoding), try_encoding- except (UnicodeDecodeError, LookupError):- continue- raise OSError(f"Unable to decode file with any known encoding") from decode_exc- else:- return file_path.read_text(encoding=encoding), encoding-- try:- data, used_encoding = read_file_with_encoding(full_path, encoding_arg)- except OSError as exc:- self._write_json(500, {"error": str(exc)})- return- body = data.encode("utf-8")- self.send_response(200)- self.send_header("Content-Type", "text/plain; charset=utf-8")- self.send_header("Content-Length", str(len(body)))- self.send_header("X-Original-Encoding", used_encoding)- self.end_headers()- if self.command != "HEAD":- self.wfile.write(body)- return-- if path == "/file-api/download":- self._handle_file_download(query)- return-- if path == "/file-api/ws-debug-config":- self._write_json(- 200,- {- "wsDisableCompress": bool(type(self).ws_disable_compress),- },- )- return-- self._write_json(404, {"error": "not_found"})-- def _handle_file_download(self, query: dict[str, str]) -> None:- token = query.get("token", "")- if not token:- self._write_json(400, {"error": "missing_token"})- return-- try:- from jiuwenswarm.agents.harness.common.tools.web_file_download import (- validate_file_download_token,- )- except ImportError:- self._write_json(500, {"error": "download_module_unavailable"})- return-- payload = validate_file_download_token(token)- if payload is None:- self._write_json(403, {"error": "invalid_or_expired_token"})- return-- file_path = payload.get("path", "")- if not file_path or not os.path.isfile(file_path):- self._write_json(404, {"error": "file_not_found"})- return-- try:- file_size = os.path.getsize(file_path)- file_name = os.path.basename(file_path)-- mime_type, _ = mimetypes.guess_type(file_name)- if not mime_type:- mime_type = "application/octet-stream"-- range_header = self.headers.get("Range")- byte_range = None- if range_header:- byte_range = _parse_single_byte_range(range_header, file_size)- if byte_range is None:- self.send_response(416)- self.send_header("Content-Range", f"bytes */{file_size}")- self.end_headers()- return-- start, end = byte_range or (0, max(0, file_size - 1))- content_length = 0 if file_size == 0 else end - start + 1- self.send_response(206 if byte_range is not None else 200)- self.send_header("Content-Type", mime_type)- self.send_header("Content-Length", str(content_length))- self.send_header("Accept-Ranges", "bytes")- encoded_name = quote(file_name, safe="")- disposition = (- "inline"- if query.get("inline", "").lower() in {"1", "true"}- else "attachment"- )- self.send_header(- "Content-Disposition",- f"{disposition}; filename*=UTF-8''{encoded_name}",- )- self.send_header("Cache-Control", "no-store")- if byte_range is not None:- self.send_header(- "Content-Range",- f"bytes {start}-{end}/{file_size}",- )- self.end_headers()-- if self.command != "HEAD":- with open(file_path, "rb") as f:- f.seek(start)- remaining = content_length- while remaining > 0:- chunk = f.read(min(65536, remaining))- if not chunk:- break- self.wfile.write(chunk)- remaining -= len(chunk)- except Exception as exc:- self.log_error("file download error: %s", exc)- try:- self._write_json(500, {"error": "download_failed", "detail": str(exc)})- except Exception:- # Connection may already be closed or broken; nothing more we can do.- self.log_error("failed to send download error response")-- def _handle_file_push(self) -> None:- """接收来自 Gateway 的文件推送(企业版 AGENT_RUNTIME 反向推送方案)."""- if not os.getenv("AGENT_RUNTIME", "").strip():- self._write_json(404, {"error": "not_available"})+ def _proxy_web_http(self) -> None:+ if not self.web_http_target:+ self.send_error(502, "web http proxy target not configured")return-- from jiuwenswarm.agents.harness.common.tools.web_file_download import (- build_file_download_info,- )-- content_type = self.headers.get("Content-Type", "")- if "multipart/form-data" not in content_type:- self._write_json(400, {"error": "expected_multipart_form_data"})- return-+ self.__dict__["api_target"] = self.web_http_targettry:- content_length = int(self.headers.get("Content-Length", 0))- body = self.rfile.read(content_length)-- environ = {- "REQUEST_METHOD": "POST",- "CONTENT_TYPE": content_type,- "CONTENT_LENGTH": str(content_length),- }- fs = cgi.FieldStorage(- fp=io.BytesIO(body),- headers=self.headers,- environ=environ,- )-- file_item = fs["file"]- session_id = fs.getvalue("session_id", "default")- filename = fs.getvalue("filename", file_item.filename or "unnamed")-- if not file_item.file:- self._write_json(400, {"error": "missing_file_field"})- return-- received_dir = Path("./web_received_files")- received_dir.mkdir(parents=True, exist_ok=True)-- safe_name = f"{int(time.time())}_{filename}"- local_path = received_dir / safe_name-- with open(local_path, "wb") as f:- while True:- chunk = file_item.file.read(65536)- if not chunk:- break- f.write(chunk)-- self.logger.info(- "[WebServer] 接收文件推送: %s -> %s", filename, local_path- )-- download_info = build_file_download_info(- file_path=str(local_path),- file_name=filename,- session_id=session_id,- )-- self._write_json(- 200,- {- "success": True,- "file_path": str(local_path),- "download_url": download_info["download_url"],- "download_token": download_info["download_token"],- "expires_at": download_info.get("expires_at"),- },- )-- except Exception as exc:- self.logger.error(- "[WebServer] 处理文件推送失败: %s", exc, exc_info=True- )- self._write_json(500, {"error": "push_failed", "detail": str(exc)})-- def _handle_obs_upload(self) -> None:- """Upload browser file payload to self-hosted MinIO (企业版)."""- if not os.getenv("AGENT_RUNTIME", "").strip():- self._write_json(404, {"error": "not_available"})- return-- length = int(self.headers.get("Content-Length", "0") or "0")- raw = self.rfile.read(length) if length > 0 else b""- status, payload = _process_obs_upload_body(raw, logger=self.logger)- self._write_json(status, payload)-- def _handle_file_api_post(self, parsed) -> None:- if parsed.path == "/file-api/push":- self._handle_file_push()- return-- if parsed.path == "/file-api/upload-obs":- self._handle_obs_upload()- return-- if parsed.path == "/file-api/rebuild-agent-data":- try:- _generate_agent_data(self.project_root)- except Exception as exc: # noqa: BLE001- self._write_json(500, {"error": "rebuild_failed", "detail": str(exc)})- return-- self._write_json(200, {"ok": True})- return-- if parsed.path == "/file-api/file-content":- length = int(self.headers.get("Content-Length", "0") or "0")- raw = self.rfile.read(length) if length > 0 else b""- try:- payload = json.loads(raw.decode("utf-8") if raw else "{}")- except json.JSONDecodeError:- self._write_json(400, {"error": "invalid_json"})- return-- request_path = payload.get("path")- request_content = payload.get("content")- if not isinstance(request_path, str) or not request_path.strip():- self._write_json(400, {"error": "missing_file_path"})- return- if not isinstance(request_content, str):- self._write_json(400, {"error": "missing_file_content"})- return-- full_path = (self.project_root / request_path).resolve()- if not self._is_path_under_allowed_root(full_path):- self._write_json(403, {"error": "forbidden_path"})- return- if not self._is_markdown(full_path):- self._write_json(400, {"error": "only_markdown_supported"})- return- if not full_path.exists():- self._write_json(404, {"error": "file_not_found"})- return-- try:- full_path.write_text(request_content, encoding="utf-8")- except OSError as exc:- self._write_json(500, {"error": str(exc)})- return- self._write_json(200, {"ok": True})- return-- if parsed.path == "/file-api/ws-debug-config":- length = int(self.headers.get("Content-Length", "0") or "0")- raw = self.rfile.read(length) if length > 0 else b""- try:- payload = json.loads(raw.decode("utf-8") if raw else "{}")- except json.JSONDecodeError:- self._write_json(400, {"error": "invalid_json"})- return-- ws_disable_compress = payload.get("wsDisableCompress")- if not isinstance(ws_disable_compress, bool):- self._write_json(400, {"error": "invalid_ws_disable_compress"})- return-- type(self).ws_disable_compress = ws_disable_compress- self.logger.info(- "[jiuwenswarm-web] ws disable compress updated: %s",- ws_disable_compress,- )- self._write_json(200, {"ok": True, "wsDisableCompress": ws_disable_compress})- return-- self._write_json(404, {"error": "not_found"})+ self._proxy_http()+ finally:+ self.__dict__.pop("api_target", None)def do_GET(self) -> None: # noqa: N802- parsed = urlparse(self.path)- if self._handle_history_api_get(parsed):- return- if self._is_share_api_route():- self._handle_share_api_get(parsed)- return- if self._is_file_api_route():- self._handle_file_api_get(parsed)+ if self._is_web_http_route():+ self._proxy_web_http()returnif self._dispatch_proxy():returnsuper().do_GET()def do_POST(self) -> None: # noqa: N802- parsed = urlparse(self.path)- if self._is_file_api_route():- self._handle_file_api_post(parsed)+ if self._is_web_http_route():+ self._proxy_web_http()returnif self._dispatch_proxy():return@@ -1282,14 +601,16 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):self.send_error(405, "method not allowed")def do_OPTIONS(self) -> None: # noqa: N802+ if self._is_web_http_route():+ self._proxy_web_http()+ returnif self._dispatch_proxy():returnself.send_error(405, "method not allowed")def do_HEAD(self) -> None: # noqa: N802- parsed = urlparse(self.path)- if self._is_file_api_route():- self._handle_file_api_get(parsed)+ if self._is_web_http_route():+ self._proxy_web_http()returnif self._dispatch_proxy():return@@ -1373,64 +694,6 @@ def _wait_for_gateway(ws_target: str, logger: logging.Logger) -> None:logger.warning("[jiuwenswarm-web] gateway not available after 15 seconds")-def _process_obs_upload_body(- raw: bytes, *, logger: logging.Logger | None = None-) -> tuple[int, dict[str, Any]]:- try:- payload = json.loads(raw.decode("utf-8") if raw else "{}")- except json.JSONDecodeError:- return 400, {"ok": False, "error": "invalid_json"}- if not isinstance(payload, dict):- return 400, {"ok": False, "error": "invalid_payload"}- try:- from jiuwenswarm.channels.web.minio_upload import upload_base64_payload-- return 200, upload_base64_payload(payload)- except Exception as exc:- if logger is not None:- logger.error("[WebServer] MinIO upload failed: %s", exc, exc_info=True)- return 500, {"ok": False, "error": str(exc)}---def _run_upload_api_server(*, host: str, port: int, log_level: str) -> None:- """Minimal HTTP server for POST /file-api/upload-obs (企业版 Vite dev)."""- if not os.getenv("AGENT_RUNTIME", "").strip():- raise ValueError("upload-api-only requires AGENT_RUNTIME")-- logs_root = get_logs_dir().resolve()- logger = _setup_logger(logs_root, log_level)-- class _UploadApiHandler(SimpleHTTPRequestHandler):- def log_message(self, fmt: str, *args: Any) -> None:- logger.debug(fmt, *args)-- def do_POST(self) -> None: # noqa: N802- if urlparse(self.path).path != "/file-api/upload-obs":- self.send_error(404)- return- length = int(self.headers.get("Content-Length", "0") or "0")- raw = self.rfile.read(length) if length > 0 else b""- status, payload = _process_obs_upload_body(raw, logger=logger)- data = json.dumps(payload, ensure_ascii=False).encode("utf-8")- self.send_response(status)- self.send_header("Content-Type", "application/json; charset=utf-8")- self.send_header("Content-Length", str(len(data)))- self.end_headers()- self.wfile.write(data)-- server = ThreadingHTTPServer((host, port), _UploadApiHandler)- logger.info(- "[jiuwenswarm-upload-api] POST http://%s:%s/file-api/upload-obs", host, port- )- try:- server.serve_forever()- except KeyboardInterrupt:- pass- finally:- server.server_close()- logger.info("[jiuwenswarm-upload-api] server closed")--def main() -> None:from jiuwenswarm.dotenv_early import get_parsed_dotenv@@ -1487,11 +750,6 @@ def main() -> None:action="store_true",help="Disable websocket compression for easier ws req/res/event debug logging.",)- parser.add_argument(- "--upload-api-only",- action="store_true",- help="Run a minimal HTTP server that only serves POST /file-api/upload-obs (enterprise Vite dev).",- )parser.add_argument("--name",metavar="<name>",@@ -1504,13 +762,6 @@ def main() -> None:)args = parser.parse_args()- if args.upload_api_only:- try:- _run_upload_api_server(host=args.host, port=args.port, log_level=args.log_level)- except ValueError as exc:- raise SystemExit(str(exc)) from exc- return-install_async_dump_handler("web")dist_dir = Path(args.dist).expanduser().resolve()@@ -1526,38 +777,24 @@ def main() -> None:except ValueError as exc:raise SystemExit(str(exc)) from exc- # default_project_root should be the user workspace root (~/.jiuwenswarm in package mode)- # get_root_dir() already handles this correctly- default_project_root = get_user_workspace_dir()-- project_root = default_project_root- workspace_root = (project_root / "agent").resolve()- agent_teams_root = _get_agent_teams_root()logs_root = get_logs_dir().resolve()logger = _setup_logger(logs_root, args.log_level)- global _history_runner- history_db = ""- if os.getenv("AGENT_RUNTIME", "").strip():- tenant_root = get_multi_tenant_user_workspace_dir("default", "default")- history_db = str((tenant_root or get_user_workspace_dir()) / "web_history.db")- store = ChatHistoryStore(history_db)- _history_runner = HistoryFrameRunner(store)- _history_runner.start()- logger.info("[jiuwenswarm-web] enterprise history db: %s", history_db)+ web_port_int = int(os.getenv("WEB_PORT", "19000"))+ web_http_port = resolve_web_http_port(web_port_int)+ web_http_target = f"http://127.0.0.1:{web_http_port}"+ explicit_web_http = os.getenv("GATEWAY_WEB_HTTP_URL", "").strip()+ if explicit_web_http:+ web_http_target = explicit_web_http.rstrip("/")class _ConfiguredHandler(_SpaStaticHandler):pass_ConfiguredHandler.api_target = api_target_ConfiguredHandler.ws_target = ws_target+ _ConfiguredHandler.web_http_target = web_http_target_ConfiguredHandler.ws_disable_compress = args.ws_disable_compress- _ConfiguredHandler.project_root = project_root- _ConfiguredHandler.workspace_root = workspace_root- _ConfiguredHandler.agent_teams_root = agent_teams_root- _ConfiguredHandler.logs_root = logs_root_ConfiguredHandler.logger = logger- _ConfiguredHandler.history_db = history_dbhandler = partial(_ConfiguredHandler, directory=str(dist_dir))server = ThreadingHTTPServer((args.host, args.port), handler)@@ -1565,8 +802,11 @@ def main() -> None:logger.info("[jiuwenswarm-web] http://%s:%s", args.host, args.port)logger.info("[jiuwenswarm-web] /api -> %s", api_target)logger.info("[jiuwenswarm-web] /ws -> %s", ws_target)+ logger.info(+ "[jiuwenswarm-web] /file-api,/share-api,/api/sessions*,/api/v1* -> %s",+ web_http_target,+ )logger.info("[jiuwenswarm-web] ws disable compress: %s", args.ws_disable_compress)- logger.info("[jiuwenswarm-web] /file-api roots -> %s, %s, %s", workspace_root, agent_teams_root, logs_root)_wait_for_gateway(ws_target, logger)diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.tsindex 5f4e6e2596..60e21507ff 100644--- a/jiuwenswarm/channels/web/frontend/vite.config.ts+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts@@ -2,10 +2,7 @@ import type { Plugin } from 'vite'import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'import svgr from 'vite-plugin-svgr'-import { spawnSync } from 'child_process'import { createHash } from 'node:crypto'-import { createHmac, timingSafeEqual } from 'node:crypto'-import type { ServerResponse } from 'http'import path from 'path'import fs from 'fs'@@ -179,132 +176,6 @@ function resolveProjectRootDir(): string {return repoRoot}-const FILE_CONTENT_ENCODING_ALIASES: Record<string, string> = {- utf8: 'utf-8',- 'utf_8': 'utf-8',- gb2312: 'gb18030',- gbk: 'gb18030',- 'shift-jis': 'shift_jis',- sjis: 'shift_jis',- euc_kr: 'euc-kr',- latin1: 'iso-8859-1',-}--function normalizeFileContentEncoding(encoding: string): string {- const key = encoding.trim().toLowerCase()- return FILE_CONTENT_ENCODING_ALIASES[key] ?? key-}--function decodeFileContent(raw: Buffer, requestedEncoding: string): { content: string; encoding: string } {- const normalizedEncoding = normalizeFileContentEncoding(requestedEncoding || 'utf-8')- if (normalizedEncoding !== 'auto') {- return {- content: new TextDecoder(normalizedEncoding, { fatal: true }).decode(raw),- encoding: normalizedEncoding,- }- }-- const candidates = ['utf-8', 'gb18030', 'big5', 'shift_jis', 'euc-kr', 'iso-8859-1']- for (const candidate of candidates) {- try {- return {- content: new TextDecoder(candidate, { fatal: true }).decode(raw),- encoding: candidate,- }- } catch {- /* try next encoding */- }- }- throw new Error('Unable to decode file with any known encoding')-}--const DOWNLOAD_CONTENT_TYPES: Record<string, string> = {- '.md': 'text/markdown; charset=utf-8',- '.markdown': 'text/markdown; charset=utf-8',- '.txt': 'text/plain; charset=utf-8',- '.json': 'application/json; charset=utf-8',- '.jsonl': 'application/x-ndjson; charset=utf-8',- '.csv': 'text/csv; charset=utf-8',- '.html': 'text/html; charset=utf-8',- '.htm': 'text/html; charset=utf-8',- '.js': 'text/javascript; charset=utf-8',- '.mjs': 'text/javascript; charset=utf-8',- '.ts': 'text/plain; charset=utf-8',- '.tsx': 'text/plain; charset=utf-8',- '.py': 'text/plain; charset=utf-8',- '.png': 'image/png',- '.jpg': 'image/jpeg',- '.jpeg': 'image/jpeg',- '.webp': 'image/webp',- '.gif': 'image/gif',- '.svg': 'image/svg+xml',- '.bmp': 'image/bmp',- '.avif': 'image/avif',- '.pdf': 'application/pdf',- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',- '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',-}--function downloadContentType(filePath: string): string {- return DOWNLOAD_CONTENT_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream'-}--function handleFileStreamError(res: ServerResponse, error: NodeJS.ErrnoException): void {- if (res.headersSent) {- res.destroy(error)- return- }-- res.statusCode = error.code === 'EACCES' || error.code === 'EPERM' ? 403 : 500- res.removeHeader('content-length')- res.removeHeader('content-disposition')- res.removeHeader('accept-ranges')- res.removeHeader('content-range')- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({- error: res.statusCode === 403 ? 'file_access_denied' : 'file_read_failed',- }))-}--function resolveFileDownloadSecret(): string | null {- const envSecret = process.env.JIUWENSWARM_FILE_DOWNLOAD_SECRET- if (envSecret && envSecret.length >= 32) return envSecret-- const workspace = process.env.JIUWENSWARM_WORKSPACE || path.join(process.env.HOME || process.env.USERPROFILE || '', '.jiuwenswarm')- const secretPath = path.join(workspace, 'config', '.file_download_secret')- try {- const secret = fs.readFileSync(secretPath, 'utf8').trim()- return secret.length >= 32 ? secret : null- } catch {- return null- }-}--function validateFileDownloadToken(token: string): { path: string } | null {- const parts = token.split('.')- if (parts.length !== 2) return null- const [payloadBase64, signature] = parts-- const secret = resolveFileDownloadSecret()- if (!secret) return null- const expected = createHmac('sha256', secret).update(payloadBase64).digest('hex')- const actual = Buffer.from(signature, 'hex')- const expectedBuffer = Buffer.from(expected, 'hex')- if (actual.length !== expectedBuffer.length || !timingSafeEqual(actual, expectedBuffer)) return null-- try {- const payload = JSON.parse(Buffer.from(payloadBase64, 'base64url').toString('utf8')) as Record<string, unknown>- if (- typeof payload.path !== 'string' ||- !payload.path ||- typeof payload.sid !== 'string'- ) return null- return { path: payload.path }- } catch {- return null- }-}-/** WS proxy 中常见的、可安全忽略的 socket 错误码(跨平台) */const WS_PROXY_IGNORABLE_CODES = new Set(['EPIPE', // 对端已关闭@@ -430,577 +301,7 @@ function devWsTrafficLogger(): Plugin {}}-/** 将文件读取接口挂到 Vite dev server,避免额外占用 3003 端口 */-function devFileContentApi(): Plugin {- const projectRootDir = resolveProjectRootDir()- const workspaceRootDir = path.resolve(projectRootDir, 'agent')- const sessionsRootDir = path.resolve(workspaceRootDir, 'sessions')- const agentTeamsRootDir = path.resolve(projectRootDir, '.agent_teams')- const webLogsRootDir = path.resolve(workspaceRootDir, '.logs')- const autoHarnessDir = path.resolve(projectRootDir, 'auto-harness')- const generateAgentFoldersScriptPath = path.resolve(__dirname, '../../../scripts/generate-agent-folders.js')- // dev 模式默认开启调试视图,与“前端 dev 即调试模式”一致。- let wsDisableCompress = true- const isMarkdownFile = (targetPath: string) => {- const ext = path.extname(targetPath).toLowerCase()- return ext === '.md' || ext === '.mdx'- }- const isPathUnderAllowedRoot = (targetPath: string) => {- const relativeWorkspacePath = path.relative(workspaceRootDir, targetPath)- const inWorkspace = !relativeWorkspacePath.startsWith('..') && !path.isAbsolute(relativeWorkspacePath)- const relativeAgentTeamsPath = path.relative(agentTeamsRootDir, targetPath)- const inAgentTeams = !relativeAgentTeamsPath.startsWith('..') && !path.isAbsolute(relativeAgentTeamsPath)- const relativeLogsPath = path.relative(webLogsRootDir, targetPath)- const inWebLogs = !relativeLogsPath.startsWith('..') && !path.isAbsolute(relativeLogsPath)- const relativeAutoHarnessPath = path.relative(autoHarnessDir, targetPath)- const inAutoHarness = !relativeAutoHarnessPath.startsWith('..') && !path.isAbsolute(relativeAutoHarnessPath)- return inWorkspace || inAgentTeams || inWebLogs || inAutoHarness- }-- return {- name: 'dev-file-content-api',- configureServer(server) {- server.middlewares.use('/share-api/snapshot', (req, res) => {- const writeJson = (statusCode: number, payload: unknown) => {- res.statusCode = statusCode- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify(payload))- }-- if (req.method !== 'GET' && req.method !== 'HEAD') {- writeJson(405, { error: 'method_not_allowed' })- return- }- const url = new URL(req.url || '/share-api/snapshot', 'http://localhost')- const sessionId = (url.searchParams.get('session_id') || '').trim()- if (!sessionId) {- writeJson(400, { error: 'missing_session_id' })- return- }-- const sessionDir = path.resolve(sessionsRootDir, sessionId)- const relativeSessionPath = path.relative(sessionsRootDir, sessionDir)- if (relativeSessionPath.startsWith('..') || path.isAbsolute(relativeSessionPath)) {- writeJson(404, { error: 'history_not_found' })- return- }-- const jsonlHistoryPath = path.resolve(sessionDir, 'history.jsonl')- const legacyHistoryPath = path.resolve(sessionDir, 'history.json')- const historyPath = fs.existsSync(legacyHistoryPath) ? legacyHistoryPath : jsonlHistoryPath- if (!fs.existsSync(sessionDir) || !fs.existsSync(historyPath)) {- writeJson(404, { error: 'history_not_found' })- return- }-- try {- const historyText = fs.readFileSync(historyPath, 'utf-8')- const trimmedHistory = historyText.trim()- const historyRaw = !trimmedHistory- ? []- : trimmedHistory.startsWith('[')- ? (JSON.parse(trimmedHistory) as unknown)- : historyText- .split(/\r?\n/)- .map((line) => line.trim())- .filter(Boolean)- .map((line) => JSON.parse(line) as unknown)- if (!Array.isArray(historyRaw)) {- writeJson(400, { error: 'invalid_history_shape' })- return- }-- let title = path.basename(sessionDir)- const metadataPath = path.resolve(sessionDir, 'metadata.json')- if (fs.existsSync(metadataPath)) {- const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')) as { title?: unknown }- if (typeof metadata.title === 'string' && metadata.title.trim()) {- title = metadata.title.trim()- }- }- if (title === path.basename(sessionDir)) {- for (const record of historyRaw) {- if (!record || typeof record !== 'object') continue- const item = record as { role?: unknown; content?: unknown }- if (item.role === 'user' && typeof item.content === 'string' && item.content.trim()) {- title = item.content.trim().replace(/\n/g, ' ').slice(0, 80)- break- }- }- }-- const now = new Date()- const filename = `jiuwenswarm-share-${now.toISOString().replace(/[-:]/g, '').replace(/\..+$/, '').replace('T', '-')}.png`- const snapshot = {- session_id: sessionId,- metadata: {- title,- exported_at: now.toISOString(),- filename,- },- records: historyRaw,- }-- writeJson(200, { filename, snapshot })- } catch (error) {- writeJson(500, { error: 'snapshot_failed', detail: (error as Error).message })- }- })-- server.middlewares.use('/file-api/ws-debug-config', (req, res) => {- if (req.method === 'GET') {- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ wsDisableCompress }))- return- }-- if (req.method !== 'POST') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }-- let raw = ''- req.on('data', (chunk) => {- raw += chunk.toString()- })- req.on('end', () => {- try {- const payload = raw ? JSON.parse(raw) : {}- if (typeof payload.wsDisableCompress !== 'boolean') {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'invalid_ws_disable_compress' }))- return- }- wsDisableCompress = payload.wsDisableCompress- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ ok: true, wsDisableCompress }))- } catch {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'invalid_json' }))- }- })- })-- server.middlewares.use('/file-api/rebuild-agent-data', (_req, res) => {- if (_req.method !== 'POST') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }-- try {- const runResult = spawnSync(process.execPath, [generateAgentFoldersScriptPath], {- encoding: 'utf-8',- })- if (runResult.status !== 0) {- const output = `${runResult.stdout || ''}\n${runResult.stderr || ''}`.trim()- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'rebuild_failed', detail: output || 'unknown_error' }))- return- }- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ ok: true }))- } catch (error) {- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'rebuild_failed', detail: (error as Error).message }))- }- })-- server.middlewares.use('/file-api/list-markdown', (req, res) => {- if (req.method !== 'GET') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }- const url = new URL(req.url || '/file-api/list-markdown', 'http://localhost')- const dir = url.searchParams.get('dir')- if (!dir) {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'missing_dir' }))- return- }- try {- const fullDirPath = path.resolve(projectRootDir, dir)- if (!isPathUnderAllowedRoot(fullDirPath)) {- res.statusCode = 403- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'forbidden_dir' }))- return- }- if (!fs.existsSync(fullDirPath) || !fs.statSync(fullDirPath).isDirectory()) {- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ files: [] }))- return- }- const files = fs- .readdirSync(fullDirPath, { withFileTypes: true })- .filter((entry) => entry.isFile())- .map((entry) => entry.name)- .filter((name) => isMarkdownFile(name))- .sort((a, b) => a.localeCompare(b))- .map((name) => ({- name,- path: path.relative(projectRootDir, path.resolve(fullDirPath, name)),- }))- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ files }))- } catch (error) {- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: (error as Error).message }))- }- })-- server.middlewares.use('/file-api/list-files', (req, res) => {- if (req.method !== 'GET') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }- const url = new URL(req.url || '/file-api/list-files', 'http://localhost')- const dir = url.searchParams.get('dir')- if (!dir) {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'missing_dir' }))- return- }- try {- const fullDirPath = path.resolve(projectRootDir, dir)- if (!isPathUnderAllowedRoot(fullDirPath)) {- res.statusCode = 403- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'forbidden_dir' }))- return- }- if (!fs.existsSync(fullDirPath) || !fs.statSync(fullDirPath).isDirectory()) {- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ files: [] }))- return- }- const files = fs- .readdirSync(fullDirPath, { withFileTypes: true })- .sort((a, b) => {- if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1- return a.name.localeCompare(b.name)- })- .map((entry) => {- const absolutePath = path.resolve(fullDirPath, entry.name)- if (entry.isDirectory()) {- return {- name: entry.name,- path: path.relative(projectRootDir, absolutePath),- isMarkdown: false,- isDirectory: true,- }- }- return {- name: entry.name,- path: path.relative(projectRootDir, absolutePath),- isMarkdown: isMarkdownFile(absolutePath),- isDirectory: false,- }- })- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ files }))- } catch (error) {- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: (error as Error).message }))- }- })-- server.middlewares.use('/file-api/download', (req, res) => {- if (req.method !== 'GET' && req.method !== 'HEAD') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }-- const url = new URL(req.url || '/file-api/download', 'http://localhost')- const token = url.searchParams.get('token') || ''- const payload = validateFileDownloadToken(token)- if (!payload) {- res.statusCode = 403- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'invalid_or_expired_token' }))- return- }-- let stat: fs.Stats- try {- stat = fs.statSync(payload.path)- } catch {- res.statusCode = 404- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'file_not_found' }))- return- }- if (!stat.isFile()) {- res.statusCode = 404- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'file_not_found' }))- return- }-- const fileSize = stat.size- let start = 0- let end = Math.max(0, fileSize - 1)- let partial = false- const range = req.headers.range- if (range) {- if (!range.startsWith('bytes=') || range.includes(',') || fileSize === 0) {- res.statusCode = 416- res.setHeader('content-range', `bytes */${fileSize}`)- res.end()- return- }- const [startText, endText] = range.slice(6).split('-', 2)- try {- if (startText) {- start = Number(startText)- end = endText ? Number(endText) : end- } else {- const suffixLength = Number(endText)- if (!Number.isInteger(suffixLength) || suffixLength <= 0) throw new Error('invalid_suffix')- start = Math.max(0, fileSize - suffixLength)- }- if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= fileSize || end < start) throw new Error('invalid_range')- end = Math.min(end, fileSize - 1)- partial = true- } catch {- res.statusCode = 416- res.setHeader('content-range', `bytes */${fileSize}`)- res.end()- return- }- }-- const contentLength = fileSize === 0 ? 0 : end - start + 1- const inline = ['1', 'true'].includes((url.searchParams.get('inline') || '').toLowerCase())- const fileName = path.basename(payload.path)- res.statusCode = partial ? 206 : 200- res.setHeader('content-type', downloadContentType(payload.path))- res.setHeader('content-length', String(contentLength))- res.setHeader('accept-ranges', 'bytes')- res.setHeader('content-disposition', `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(fileName)}`)- res.setHeader('cache-control', 'no-store')- if (partial) res.setHeader('content-range', `bytes ${start}-${end}/${fileSize}`)- if (req.method === 'HEAD') {- res.end()- return- }- const fileStream = fs.createReadStream(payload.path, fileSize === 0 ? undefined : { start, end })- fileStream.once('error', (error) => {- server.config.logger.error(`[file-api] Failed to read ${payload.path}: ${(error as Error).message}`)- handleFileStreamError(res, error)- })- fileStream.pipe(res)- })-- server.middlewares.use('/file-api/raw-file', (req, res) => {- if (req.method !== 'GET' && req.method !== 'HEAD') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }-- const url = new URL(req.url || '/file-api/raw-file', 'http://localhost')- const filePath = url.searchParams.get('path')- if (!filePath) {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '缺少文件路径' }))- return- }-- try {- const fullPath = path.resolve(projectRootDir, filePath)- if (!isPathUnderAllowedRoot(fullPath)) {- res.statusCode = 403- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'forbidden_path' }))- return- }- if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {- res.statusCode = 404- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '文件不存在', fullPath }))- return- }-- res.statusCode = 200- res.setHeader('content-type', downloadContentType(fullPath))- res.setHeader('cache-control', 'no-store')- if (req.method === 'HEAD') {- res.end()- return- }- const fileStream = fs.createReadStream(fullPath)- fileStream.once('error', (error) => {- server.config.logger.error(`[file-api] Failed to read ${fullPath}: ${(error as Error).message}`)- handleFileStreamError(res, error)- })- fileStream.pipe(res)- } catch (error) {- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: (error as Error).message }))- }- })-- server.middlewares.use('/file-api/file-content', (req, res) => {- if (req.method === 'GET') {- const url = new URL(req.url || '/file-api/file-content', 'http://localhost')- const filePath = url.searchParams.get('path')- const requestedEncoding = url.searchParams.get('encoding') || 'utf-8'- if (!filePath) {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '缺少文件路径' }))- return- }-- try {- const fullPath = path.resolve(projectRootDir, filePath)- if (!isPathUnderAllowedRoot(fullPath)) {- res.statusCode = 403- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'forbidden_path' }))- return- }- if (!fs.existsSync(fullPath)) {- if (filePath.replace(/\\/g, '/') === 'agent/workspace/agent-data.json') {- try {- const runResult = spawnSync(process.execPath, [generateAgentFoldersScriptPath], {- encoding: 'utf-8',- env: { ...process.env, JIUWENSWARM_ROOT: projectRootDir },- cwd: path.dirname(path.dirname(generateAgentFoldersScriptPath)),- })- if (runResult.status === 0 && fs.existsSync(fullPath)) {- const { content, encoding } = decodeFileContent(fs.readFileSync(fullPath), requestedEncoding)- res.statusCode = 200- res.setHeader('content-type', 'text/plain; charset=utf-8')- res.setHeader('X-Original-Encoding', encoding)- res.end(content)- return- }- } catch {- /* fall through to 404 */- }- }- res.statusCode = 404- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '文件不存在', fullPath }))- return- }-- const { content, encoding } = decodeFileContent(fs.readFileSync(fullPath), requestedEncoding)- res.statusCode = 200- res.setHeader('content-type', 'text/plain; charset=utf-8')- res.setHeader('X-Original-Encoding', encoding)- res.end(content)- } catch (error) {- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: (error as Error).message }))- }- return- }-- if (req.method !== 'POST') {- res.statusCode = 405- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'method_not_allowed' }))- return- }-- let raw = ''- req.on('data', (chunk) => {- raw += chunk.toString()- })- req.on('end', () => {- let payload: { path?: unknown; content?: unknown } = {}- try {- payload = raw ? JSON.parse(raw) : {}- } catch {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'invalid_json' }))- return- }-- const requestPath = payload.path- const requestContent = payload.content- if (typeof requestPath !== 'string' || !requestPath.trim()) {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '缺少文件路径' }))- return- }- if (typeof requestContent !== 'string') {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '缺少文件内容' }))- return- }-- const fullPath = path.resolve(projectRootDir, requestPath)- if (!isPathUnderAllowedRoot(fullPath)) {- res.statusCode = 403- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: 'forbidden_path' }))- return- }- if (!isMarkdownFile(fullPath)) {- res.statusCode = 400- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '仅支持保存 Markdown 文件' }))- return- }- if (!fs.existsSync(fullPath)) {- res.statusCode = 404- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: '文件不存在' }))- return- }-- fs.writeFile(fullPath, requestContent, 'utf-8', (error) => {- if (error) {- res.statusCode = 500- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ error: error.message }))- return- }-- res.statusCode = 200- res.setHeader('content-type', 'application/json; charset=utf-8')- res.end(JSON.stringify({ ok: true }))- })- })- })- },- }-}+/** file/share HTTP 已迁 Gateway Web HTTP;dev 经 proxy 转发(见 server.proxy)。 */// https://vitejs.dev/config/function portFromEnv(name: string, fallback: number): number {@@ -1008,12 +309,26 @@ function portFromEnv(name: string, fallback: number): number {return Number.isInteger(value) && value > 0 && value <= 65535 ? value : fallback}+function resolveWebHttpPort(wsPort: number): number {+ const envPort = portFromEnv('GATEWAY_WEB_HTTP_PORT', 0)+ let port = envPort || wsPort + 2+ const gatewayPort = portFromEnv('GATEWAY_PORT', wsPort + 1)+ if (port === wsPort || port === gatewayPort) {+ port = Math.max(wsPort, gatewayPort) + 1+ }+ return port+}+const frontendPort = portFromEnv('FRONTEND_PORT', 5173)const webPort = portFromEnv('WEB_PORT', 19000)const webTarget = `http://127.0.0.1:${webPort}`+const webHttpPort = resolveWebHttpPort(webPort)+const webHttpTarget =+ process.env.GATEWAY_WEB_HTTP_URL?.replace(/\/$/, '') ||+ `http://127.0.0.1:${webHttpPort}`export default defineConfig({- plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), devFileContentApi(), react(), svgr()],+ plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), react(), svgr()],optimizeDeps: {include: ['exceljs', 'jszip', 'saxes', 'ssf'],},@@ -1026,6 +341,23 @@ export default defineConfig({port: frontendPort,strictPort: true,proxy: {+ '/file-api': {+ target: webHttpTarget,+ changeOrigin: true,+ },+ '/share-api': {+ target: webHttpTarget,+ changeOrigin: true,+ },+ // More specific than '/api' — enterprise HTTP APIs live on Web HTTP, not WS port.+ '/api/v1': {+ target: webHttpTarget,+ changeOrigin: true,+ },+ '/api/sessions': {+ target: webHttpTarget,+ changeOrigin: true,+ },'/api': {target: webTarget,changeOrigin: true,diff --git a/jiuwenswarm/channels/web/history_store.py b/jiuwenswarm/channels/web/history_store.pyindex d658de733a..04ed9bd365 100644--- a/jiuwenswarm/channels/web/history_store.py+++ b/jiuwenswarm/channels/web/history_store.py@@ -1,14 +1,18 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.-"""Web Pod 会话历史采集与查询(release 旧架构版:http.server + WS 代理)。+"""会话历史采集与查询。-职责:-- ``ChatHistoryStore``:aiosqlite + WAL,落 sessions / messages 两表,幂等去重(由 ws loop 写)。-- ``make_history_callback(store)``:产出 on_frame 回调——白名单过滤 +- pending(首条请求无 session_id 时暂存、final 回填)+ 调 store 落盘。-- ``list_sessions_sync`` / ``get_session_detail_sync``:标准库 sqlite3 同步只读,- 供 http.server 的 ``_SpaStaticHandler``(同步线程)调用;与 ws loop 的 aiosqlite 写共享同一 WAL db。-- ``HistoryFrameRunner``:在同步 WS 代理线程中向后台 asyncio loop 投递采集任务。+写路径可来自:+- ``app_web`` WS 反代(``HistoryFrameRunner``)+- Gateway ``WebChannel`` Listen(无 Pod 时的主路径)++存储按库类型分支:+- ``sqlite``:本地 ``web_history.db``(``WEB_HISTORY_SQLITE_PATH`` 可覆盖)+- ``mysql``:独立库 ``web``(``WEB_DB_*``);缺 ``WEB_DB_HOST`` 则不可用,不回退 SQLite+- ``postgresql`` 等:暂不支持,明确不可用++选型与 Gateway ``GATEWAY_DB_TYPE`` 对齐:``WEB_DB_TYPE`` → ``DB_TYPE`` →+已配 ``WEB_DB_HOST`` 则视为 mysql → 默认 sqlite。"""from __future__ import annotations@@ -16,29 +20,75 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import osimport sqlite3import threadingimport time+from dataclasses import dataclassfrom pathlib import Path-from typing import Any, Awaitable, Callable--import aiosqlite+from typing import Any, Awaitable, Callable, Literallogger = logging.getLogger("jiuwenswarm.web.history")-# 用户对话请求白名单(其余 method 不采集)。_REQUEST_METHODS = frozenset({"chat.send", "chat.resume", "chat.user_answer"})-# 终态回复事件(流式增量 / 工具调用等中间事件不采集)。_FINAL_EVENTS = frozenset({"chat.final", "chat.error"})_TITLE_LEN = 30_PREVIEW_LEN = 100_MAX_LIST_LIMIT = 100-# on_frame 回调签名:(direction, raw, conn_id)FrameCallback = Callable[[str, str, "str | None"], Awaitable[None]]+HistoryBackend = Literal["memory", "sqlite", "mysql"]++_DEFAULT_DB_NAME = "web"+_DEFAULT_SQLITE_NAME = "web_history.db"++_CREATE_DATABASE_SQL = (+ "CREATE DATABASE IF NOT EXISTS `{db}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"+)++_MYSQL_CREATE_TABLES_SQL = """+CREATE TABLE IF NOT EXISTS sessions (+ session_id VARCHAR(128) NOT NULL,+ user VARCHAR(128) NOT NULL DEFAULT 'guest',+ title VARCHAR(255) NULL,+ message_count INT NOT NULL DEFAULT 0,+ last_preview TEXT NULL,+ created_at DOUBLE NOT NULL,+ updated_at DOUBLE NOT NULL,+ PRIMARY KEY (session_id),+ KEY idx_sessions_user_updated (user, updated_at)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;+CREATE TABLE IF NOT EXISTS messages (+ id BIGINT NOT NULL AUTO_INCREMENT,+ session_id VARCHAR(128) NOT NULL,+ request_id VARCHAR(128) NOT NULL,+ role VARCHAR(32) NOT NULL,+ content MEDIUMTEXT NOT NULL,+ event_type VARCHAR(64) NULL,+ timestamp DOUBLE NOT NULL,+ PRIMARY KEY (id),+ UNIQUE KEY uk_msg_sid_rid_role (session_id, request_id, role),+ KEY idx_msg_session_ts (session_id, timestamp)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;+"""++_MYSQL_INSERT_MESSAGE_SQL = (+ "INSERT IGNORE INTO messages (session_id, request_id, role, content, event_type, timestamp) "+ "VALUES (%s, %s, %s, %s, %s, %s)"+)-_SCHEMA = """+_MYSQL_UPSERT_SESSION_SQL = """+INSERT INTO sessions (session_id, user, title, message_count, last_preview, created_at, updated_at)+VALUES (%s, %s, %s, 1, %s, %s, %s)+ON DUPLICATE KEY UPDATE+ message_count = message_count + 1,+ last_preview = VALUES(last_preview),+ updated_at = VALUES(updated_at),+ title = COALESCE(title, VALUES(title))+"""++_SQLITE_SCHEMA = """CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY,user TEXT,@@ -61,48 +111,376 @@ CREATE TABLE IF NOT EXISTS messages (CREATE INDEX IF NOT EXISTS idx_msg_session_ts ON messages(session_id, timestamp);"""-_UPSERT_SESSION = """+_SQLITE_INSERT_MESSAGE_SQL = (+ "INSERT OR IGNORE INTO messages (session_id, request_id, role, content, event_type, timestamp) "+ "VALUES (?, ?, ?, ?, ?, ?)"+)++_SQLITE_UPSERT_SESSION_SQL = """INSERT INTO sessions (session_id, user, title, message_count, last_preview, created_at, updated_at)VALUES (?, ?, ?, 1, ?, ?, ?)ON CONFLICT(session_id) DO UPDATE SETmessage_count = message_count + 1,last_preview = excluded.last_preview,- updated_at = excluded.updated_at+ updated_at = excluded.updated_at,+ title = COALESCE(sessions.title, excluded.title)"""+def _env(*names: str, default: str = "") -> str:+ for name in names:+ raw = os.getenv(name)+ if raw is not None and str(raw).strip():+ return str(raw).strip()+ return default+++def resolve_history_db_type() -> str:+ """解析 Web 会话历史库类型。++ 优先级:``WEB_DB_TYPE`` → ``DB_TYPE`` → 已配 ``WEB_DB_HOST`` 则 ``mysql`` → 默认 ``sqlite``。+ """+ explicit = _env("WEB_DB_TYPE") or _env("DB_TYPE")+ if explicit:+ return explicit.strip().lower()+ if _env("WEB_DB_HOST"):+ return "mysql"+ return "sqlite"+++def default_history_sqlite_path() -> Path:+ """SQLite 历史默认路径;``WEB_HISTORY_SQLITE_PATH`` 可覆盖。"""+ override = _env("WEB_HISTORY_SQLITE_PATH")+ if override:+ return Path(override).expanduser().resolve()+ from jiuwenswarm.common.utils import (+ get_multi_tenant_user_workspace_dir,+ get_user_workspace_dir,+ )++ tenant_root = get_multi_tenant_user_workspace_dir("default", "default")+ return (tenant_root or get_user_workspace_dir()) / _DEFAULT_SQLITE_NAME+++def default_enterprise_history_db_path() -> str:+ """兼容旧调用:返回 sqlite 默认路径字符串。"""+ return str(default_history_sqlite_path())+++@dataclass(frozen=True)+class WebHistoryDbSettings:+ """Web 历史库 MySQL 连接(独立 database ``web``)。"""++ host: str+ port: int+ user: str+ password: str+ database: str = _DEFAULT_DB_NAME++ @classmethod+ def from_env(cls) -> WebHistoryDbSettings | None:+ host = _env("WEB_DB_HOST")+ if not host:+ return None+ port_raw = _env("WEB_DB_PORT", default="3306")+ try:+ port = int(port_raw)+ except ValueError:+ port = 3306+ return cls(+ host=host,+ port=port,+ user=_env("WEB_DB_USER", default="root"),+ password=_env("WEB_DB_PASSWORD"),+ database=_env("WEB_DB_NAME", default=_DEFAULT_DB_NAME) or _DEFAULT_DB_NAME,+ )+++def _quote_ident(name: str) -> str:+ cleaned = "".join(ch for ch in name if ch.isalnum() or ch in {"_", "$"})+ return cleaned or _DEFAULT_DB_NAME++class ChatHistoryStore:- """会话历史 SQLite 存储(aiosqlite + WAL,懒初始化,幂等)。"""-- def __init__(self, db_path: str | Path) -> None:- self._db_path = Path(db_path)- self._db: aiosqlite.Connection | None = None- self._init_lock: Any = None # 懒建:首次用时创建(避免 import 时无 event loop)-- async def _ensure(self) -> aiosqlite.Connection:- if self._db is not None:- return self._db- if self._init_lock is None:- self._init_lock = asyncio.Lock()- async with self._init_lock:- if self._db is not None:- return self._db- self._db_path.parent.mkdir(parents=True, exist_ok=True)- conn = await aiosqlite.connect(str(self._db_path))- await conn.execute("PRAGMA journal_mode=WAL")- await conn.execute("PRAGMA foreign_keys=ON")- await conn.executescript(_SCHEMA)+ """会话历史存储:SQLite / MySQL;单测可用 memory=True。"""++ def __init__(+ self,+ settings: WebHistoryDbSettings | str | Path | None = None,+ *,+ db_path: str | Path | None = None,+ memory: bool = False,+ ) -> None:+ if isinstance(settings, (str, Path)):+ db_path = settings+ settings = None+ self._settings = settings+ self._db_path = Path(db_path) if db_path is not None else None+ self._memory = memory+ self._ready = False+ self._init_lock = threading.Lock()+ self._mem_lock = threading.Lock()+ self._mem_sessions: dict[str, dict[str, Any]] = {}+ self._mem_messages: list[dict[str, Any]] = []++ @classmethod+ def for_db_type(cls, db_type: str) -> ChatHistoryStore:+ normalized = str(db_type or "").strip().lower() or "sqlite"+ if normalized in ("postgresql", "postgres", "pg"):+ logger.warning(+ "[history] Web 会话历史暂不支持 PostgreSQL(db_type=%s),历史不可用(不回退 SQLite)",+ normalized,+ )+ return cls(settings=None, memory=False)+ if normalized == "mysql":+ return cls(settings=WebHistoryDbSettings.from_env(), memory=False)+ if normalized == "sqlite":+ return cls(db_path=default_history_sqlite_path(), memory=False)+ logger.warning(+ "[history] 不支持的历史库类型 %r,会话历史不可用(不回退 SQLite)",+ normalized,+ )+ return cls(settings=None, memory=False)++ @classmethod+ def from_env(cls) -> ChatHistoryStore:+ return cls.for_db_type(resolve_history_db_type())++ @classmethod+ def memory(cls) -> ChatHistoryStore:+ return cls(settings=None, db_path=None, memory=True)++ @property+ def backend(self) -> HistoryBackend:+ if self._memory:+ return "memory"+ if self._db_path is not None:+ return "sqlite"+ return "mysql"++ @property+ def db_path(self) -> Path | None:+ return self._db_path++ @property+ def mysql_settings(self) -> WebHistoryDbSettings | None:+ return self._settings++ @property+ def available(self) -> bool:+ if self._memory:+ return True+ if self._db_path is not None:+ return True+ return self._settings is not None++ def _connect_mysql(self, *, with_database: bool):+ import pymysql++ if self._settings is None:+ raise RuntimeError("MySQL settings 未配置,无法建立连接")+ kwargs: dict[str, Any] = {+ "host": self._settings.host,+ "port": self._settings.port,+ "user": self._settings.user,+ "password": self._settings.password,+ "charset": "utf8mb4",+ "autocommit": False,+ "cursorclass": pymysql.cursors.DictCursor,+ }+ if with_database:+ kwargs["database"] = self._settings.database+ return pymysql.connect(**kwargs)++ def _connect_sqlite(self) -> sqlite3.Connection:+ if self._db_path is None:+ raise RuntimeError("SQLite db_path 未配置,无法建立连接")+ conn = sqlite3.connect(str(self._db_path), check_same_thread=False)+ conn.row_factory = sqlite3.Row+ return conn++ def _ensure_schema(self) -> bool:+ if self._memory:+ return True+ if self.backend == "sqlite":+ return self._ensure_sqlite_schema()+ return self._ensure_mysql_schema()++ def _ensure_sqlite_schema(self) -> bool:+ if self._db_path is None:+ logger.error("[history] SQLite 未配置 db_path,会话历史不可用")+ return False+ if self._ready:+ return True+ with self._init_lock:+ if self._ready:+ return True+ try:+ self._db_path.parent.mkdir(parents=True, exist_ok=True)+ conn = self._connect_sqlite()+ try:+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute("PRAGMA foreign_keys=ON")+ conn.executescript(_SQLITE_SCHEMA)+ try:+ conn.execute("ALTER TABLE sessions ADD COLUMN user TEXT")+ except sqlite3.OperationalError as e:+ if "duplicate column" not in str(e).lower():+ raise+ logger.debug("[history] sessions.user 列已存在,跳过 ALTER")+ conn.execute("UPDATE sessions SET user = 'guest' WHERE user IS NULL")+ conn.commit()+ finally:+ conn.close()+ self._ready = True+ logger.info("[history] SQLite store 初始化完成 db=%s", self._db_path)+ return True+ except Exception:+ logger.exception("[history] SQLite 初始化失败,会话历史暂不可用")+ return False++ def _ensure_mysql_schema(self) -> bool:+ if self._settings is None:+ logger.error("[history] MySQL 未配置(缺少 WEB_DB_HOST),会话历史不可用")+ return False+ if self._ready:+ return True+ with self._init_lock:+ if self._ready:+ return True+ db_name = _quote_ident(self._settings.database)+ try:+ conn = self._connect_mysql(with_database=False)+ try:+ with conn.cursor() as cur:+ cur.execute(_CREATE_DATABASE_SQL.format(db=db_name))+ conn.commit()+ finally:+ conn.close()+ conn = self._connect_mysql(with_database=True)+ try:+ with conn.cursor() as cur:+ for stmt in _MYSQL_CREATE_TABLES_SQL.split(";"):+ sql = stmt.strip()+ if sql:+ cur.execute(sql)+ conn.commit()+ finally:+ conn.close()+ self._ready = True+ logger.info(+ "[history] MySQL store 初始化完成 %s:%s/%s",+ self._settings.host,+ self._settings.port,+ self._settings.database,+ )+ return True+ except Exception:+ logger.exception("[history] MySQL 初始化失败,会话历史暂不可用")+ return False++ def _run_write(self, fn: Callable[[Any], bool]) -> bool:+ if self._memory:+ return fn(None)+ if not self._ensure_schema():+ return False+ try:+ if self.backend == "sqlite":+ conn = self._connect_sqlite()+ try:+ inserted = fn(conn)+ conn.commit()+ return inserted+ finally:+ conn.close()+ conn = self._connect_mysql(with_database=True)try:- await conn.execute("ALTER TABLE sessions ADD COLUMN user TEXT")- except sqlite3.OperationalError as e:- if "duplicate column" not in str(e).lower():- raise- logger.debug("[history] sessions.user 列已存在,跳过 ALTER")- await conn.execute("UPDATE sessions SET user = 'guest' WHERE user IS NULL")- await conn.commit()- self._db = conn- logger.info("[history] store 初始化完成: db=%s", self._db_path)- return self._db+ inserted = fn(conn)+ conn.commit()+ return inserted+ finally:+ conn.close()+ except Exception:+ logger.exception("[history] %s 写入失败", self.backend.upper())+ return False++ async def _run_write_async(self, fn: Callable[[Any], bool]) -> bool:+ return await asyncio.to_thread(self._run_write, fn)++ def _insert_message_and_upsert_session(+ self,+ conn: Any,+ *,+ session_id: str,+ request_id: str,+ role: str,+ content: str,+ event_type: str | None,+ ts: float,+ user: str | None,+ title: str | None,+ preview: str,+ ) -> bool:+ if self._memory:+ key = (session_id, request_id, role)+ with self._mem_lock:+ if any(+ (m["session_id"], m["request_id"], m["role"]) == key+ for m in self._mem_messages+ ):+ return False+ self._mem_messages.append({+ "session_id": session_id,+ "request_id": request_id,+ "role": role,+ "content": content,+ "event_type": event_type,+ "timestamp": ts,+ })+ existing = self._mem_sessions.get(session_id)+ if existing is None:+ self._mem_sessions[session_id] = {+ "session_id": session_id,+ "user": user or "guest",+ "title": title,+ "message_count": 1,+ "last_preview": preview,+ "created_at": ts,+ "updated_at": ts,+ }+ else:+ existing["message_count"] = int(existing.get("message_count") or 0) + 1+ existing["last_preview"] = preview+ existing["updated_at"] = ts+ if not existing.get("title") and title:+ existing["title"] = title+ return True++ if self.backend == "sqlite":+ cur = conn.execute(+ _SQLITE_INSERT_MESSAGE_SQL,+ (session_id, request_id, role, content, event_type, ts),+ )+ inserted = cur.rowcount > 0+ if inserted:+ conn.execute(+ _SQLITE_UPSERT_SESSION_SQL,+ (session_id, user or "guest", title, preview, ts, ts),+ )+ return inserted++ with conn.cursor() as cur:+ cur.execute(+ _MYSQL_INSERT_MESSAGE_SQL,+ (session_id, request_id, role, content, event_type, ts),+ )+ inserted = cur.rowcount > 0+ if inserted:+ cur.execute(+ _MYSQL_UPSERT_SESSION_SQL,+ (session_id, user or "guest", title, preview, ts, ts),+ )+ return insertedasync def record_user(self,@@ -113,31 +491,28 @@ class ChatHistoryStore:ts: float,user: str | None = None,) -> bool:- """落盘一条 user 消息。重发幂等(UNIQUE 命中则不增计数)。user 写 sessions.user(首条定)。"""- # 空 user 归一为默认身份 'guest'(与 _ensure 里的存量回填一致),- # 避免写入 NULL 而读取时不过滤 → 跨用户历史泄漏。if not user:user = "guest"- conn = await self._ensure()- cur = await conn.execute(- "INSERT OR IGNORE INTO messages (session_id, request_id, role, content, event_type, timestamp) "- "VALUES (?, ?, 'user', ?, NULL, ?)",- (session_id, request_id, query, ts),- )- inserted = cur.rowcount > 0- if inserted:- await conn.execute(- _UPSERT_SESSION,- (session_id, user, query[:_TITLE_LEN], query[:_PREVIEW_LEN], ts, ts),+ title = query[:_TITLE_LEN]+ preview = query[:_PREVIEW_LEN]+ inserted = await self._run_write_async(+ lambda conn: self._insert_message_and_upsert_session(+ conn,+ session_id=session_id,+ request_id=request_id,+ role="user",+ content=query,+ event_type=None,+ ts=ts,+ user=user,+ title=title,+ preview=preview,)- await conn.commit()+ )if inserted:logger.info("[history] 落盘 user: rid=%s sid=%s user=%s len=%d",- request_id,- session_id,- user,- len(query),+ request_id, session_id, user, len(query),)return inserted@@ -150,92 +525,161 @@ class ChatHistoryStore:event_type: str,ts: float,) -> bool:- """落盘一条 assistant 终态消息(chat.final / chat.error)。重发幂等。"""- conn = await self._ensure()- cur = await conn.execute(- "INSERT OR IGNORE INTO messages (session_id, request_id, role, content, event_type, timestamp) "- "VALUES (?, ?, 'assistant', ?, ?, ?)",- (session_id, request_id, content, event_type, ts),- )- inserted = cur.rowcount > 0- if inserted:- await conn.execute(- _UPSERT_SESSION,- (session_id, None, None, content[:_PREVIEW_LEN], ts, ts),+ preview = content[:_PREVIEW_LEN]+ inserted = await self._run_write_async(+ lambda conn: self._insert_message_and_upsert_session(+ conn,+ session_id=session_id,+ request_id=request_id,+ role="assistant",+ content=content,+ event_type=event_type,+ ts=ts,+ user="guest",+ title=None,+ preview=preview,)- await conn.commit()+ )if inserted:logger.info("[history] 落盘 assistant: rid=%s sid=%s event=%s len=%d",- request_id,- session_id,- event_type,- len(content),+ request_id, session_id, event_type, len(content),)return inserted- async def list_sessions(self, *, limit: int = 20, offset: int = 0) -> list[dict[str, Any]]:- conn = await self._ensure()+ def list_sessions_blocking(+ self, *, limit: int, offset: int, user: str | None,+ ) -> list[dict[str, Any]]:limit = max(1, min(limit, _MAX_LIST_LIMIT))offset = max(0, offset)- cur = await conn.execute(- "SELECT session_id, title, message_count, last_preview, created_at, updated_at "- "FROM sessions ORDER BY updated_at DESC LIMIT ? OFFSET ?",- (limit, offset),+ if not user:+ user = "guest"+ if self._memory:+ with self._mem_lock:+ rows = [+ dict(s) for s in self._mem_sessions.values()+ if s.get("user") == user+ ]+ rows.sort(key=lambda r: float(r.get("updated_at") or 0), reverse=True)+ return rows[offset:offset + limit]+ if not self._ensure_schema():+ return []+ if self.backend == "sqlite":+ try:+ conn = self._connect_sqlite()+ try:+ rows = conn.execute(+ "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "+ "FROM sessions WHERE user = ? ORDER BY updated_at DESC LIMIT ? OFFSET ?",+ (user, limit, offset),+ ).fetchall()+ return [dict(r) for r in rows]+ finally:+ conn.close()+ except Exception:+ logger.exception("[history] SQLite 读取会话列表失败")+ return []+ try:+ conn = self._connect_mysql(with_database=True)+ try:+ with conn.cursor() as cur:+ cur.execute(+ "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "+ "FROM sessions WHERE user = %s ORDER BY updated_at DESC LIMIT %s OFFSET %s",+ (user, limit, offset),+ )+ return list(cur.fetchall() or [])+ finally:+ conn.close()+ except Exception:+ logger.exception("[history] MySQL 读取会话列表失败")+ return []++ def get_session_detail_blocking(+ self, session_id: str, *, user: str | None,+ ) -> dict[str, Any] | None:+ if not user:+ user = "guest"+ if self._memory:+ with self._mem_lock:+ s = self._mem_sessions.get(session_id)+ if s is None or s.get("user") != user:+ return None+ msgs = [+ {+ "role": m["role"],+ "content": m["content"],+ "event_type": m["event_type"],+ "timestamp": m["timestamp"],+ "request_id": m["request_id"],+ }+ for m in self._mem_messages+ if m["session_id"] == session_id+ ]+ msgs.sort(key=lambda m: float(m.get("timestamp") or 0))+ return {**s, "messages": msgs}+ if not self._ensure_schema():+ return None+ if self.backend == "sqlite":+ try:+ conn = self._connect_sqlite()+ try:+ s = conn.execute(+ "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "+ "FROM sessions WHERE session_id = ? AND user = ?",+ (session_id, user),+ ).fetchone()+ if s is None:+ return None+ msgs = conn.execute(+ "SELECT role, content, event_type, timestamp, request_id "+ "FROM messages WHERE session_id = ? ORDER BY timestamp ASC",+ (session_id,),+ ).fetchall()+ return {**dict(s), "messages": [dict(m) for m in msgs]}+ finally:+ conn.close()+ except Exception:+ logger.exception("[history] SQLite 读取会话详情失败")+ return None+ try:+ conn = self._connect_mysql(with_database=True)+ try:+ with conn.cursor() as cur:+ cur.execute(+ "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "+ "FROM sessions WHERE session_id = %s AND user = %s",+ (session_id, user),+ )+ s = cur.fetchone()+ if s is None:+ return None+ cur.execute(+ "SELECT role, content, event_type, timestamp, request_id "+ "FROM messages WHERE session_id = %s ORDER BY timestamp ASC",+ (session_id,),+ )+ msgs = list(cur.fetchall() or [])+ return {**s, "messages": msgs}+ finally:+ conn.close()+ except Exception:+ logger.exception("[history] MySQL 读取会话详情失败")+ return None++ async def list_sessions(self, *, limit: int = 20, offset: int = 0) -> list[dict[str, Any]]:+ return await asyncio.to_thread(+ self.list_sessions_blocking, limit=limit, offset=offset, user=None,)- rows = await cur.fetchall()- return [- {- "session_id": r[0],- "title": r[1],- "message_count": r[2],- "last_preview": r[3],- "created_at": r[4],- "updated_at": r[5],- }- for r in rows- ]async def get_session_detail(self, session_id: str) -> dict[str, Any] | None:- conn = await self._ensure()- cur = await conn.execute(- "SELECT session_id, title, message_count, last_preview, created_at, updated_at "- "FROM sessions WHERE session_id = ?",- (session_id,),- )- s = await cur.fetchone()- if s is None:- return None- cur = await conn.execute(- "SELECT role, content, event_type, timestamp, request_id "- "FROM messages WHERE session_id = ? ORDER BY timestamp ASC",- (session_id,),+ return await asyncio.to_thread(+ self.get_session_detail_blocking, session_id, user=None,)- msgs = await cur.fetchall()- return {- "session_id": s[0],- "title": s[1],- "message_count": s[2],- "last_preview": s[3],- "created_at": s[4],- "updated_at": s[5],- "messages": [- {- "role": m[0],- "content": m[1],- "event_type": m[2],- "timestamp": m[3],- "request_id": m[4],- }- for m in msgs- ],- }async def close(self) -> None:- if self._db is not None:- await self._db.close()- self._db = None- logger.info("[history] store 已关闭: db=%s", self._db_path)+ self._ready = False+ logger.info("[history] store 已关闭 backend=%s", self.backend)def make_history_callback(store: ChatHistoryStore) -> FrameCallback:@@ -257,25 +701,21 @@ def make_history_callback(store: ChatHistoryStore) -> FrameCallback:if not isinstance(request_id, str):returnsession_id = params.get("session_id")- user = params.get("user")- if not isinstance(user, str):+ user = params.get("user") or params.get("user_id")+ if not isinstance(user, str) or not user.strip():user = None+ else:+ user = user.strip()ts = time.time()if isinstance(session_id, str) and session_id:await store.record_user(- request_id=request_id,- session_id=session_id,- query=query,- ts=ts,- user=user,+ request_id=request_id, session_id=session_id, query=query, ts=ts, user=user,)else:pending[request_id] = {"query": query, "ts": ts, "method": method, "user": user}logger.debug("[history] 暂存 pending user(无 sid): rid=%s method=%s pending=%d",- request_id,- method,- len(pending),+ request_id, method, len(pending),)async def _handle_uplink(data: dict[str, Any]) -> None:@@ -284,6 +724,10 @@ def make_history_callback(store: ChatHistoryStore) -> FrameCallback:event = data.get("event")payload = data.get("payload") if isinstance(data.get("payload"), dict) else {}request_id = data.get("request_id")+ if not isinstance(request_id, str) or not request_id:+ payload_rid = payload.get("request_id")+ if isinstance(payload_rid, str) and payload_rid:+ request_id = payload_ridif event == "chat.delta" and isinstance(request_id, str):delta = payload.get("content")@@ -297,8 +741,7 @@ def make_history_callback(store: ChatHistoryStore) -> FrameCallback:if not isinstance(session_id, str) or not session_id:logger.warning("[history] 终态帧缺 session_id,丢弃: event=%s rid=%s",- event,- request_id if isinstance(request_id, str) else "",+ event, request_id if isinstance(request_id, str) else "",)returnif event == "chat.final":@@ -312,19 +755,13 @@ def make_history_callback(store: ChatHistoryStore) -> FrameCallback:if isinstance(request_id, str) and request_id in pending:p = pending.pop(request_id)await store.record_user(- request_id=request_id,- session_id=session_id,- query=p["query"],- ts=p["ts"],- user=p.get("user"),+ request_id=request_id, session_id=session_id,+ query=p["query"], ts=p["ts"], user=p.get("user"),)logger.info("[history] pending 回填 user: rid=%s sid=%s", request_id, session_id)await store.record_assistant(request_id=request_id if isinstance(request_id, str) else "",- session_id=session_id,- content=content,- event_type=event,- ts=ts,+ session_id=session_id, content=content, event_type=event, ts=ts,)async def cb(direction: str, raw: str, conn_id: str | None = None) -> None: # noqa: ARG001@@ -346,8 +783,87 @@ def make_history_callback(store: ChatHistoryStore) -> FrameCallback:return cb+_default_store: ChatHistoryStore | None = None+_default_store_lock = threading.Lock()+++def get_default_store() -> ChatHistoryStore:+ """进程内单例,避免 HTTP 每次请求重建库。"""+ global _default_store+ with _default_store_lock:+ if _default_store is None:+ _default_store = ChatHistoryStore.from_env()+ return _default_store+++def set_default_store(store: ChatHistoryStore) -> None:+ global _default_store+ with _default_store_lock:+ _default_store = store+++def _coerce_store(store: ChatHistoryStore | str | Path | None) -> ChatHistoryStore | None:+ if store is None:+ st = get_default_store()+ return st if st.available else None+ if isinstance(store, ChatHistoryStore):+ return store if store.available else None+ path = Path(store)+ if not path.exists():+ return None+ return ChatHistoryStore(db_path=path)+++def list_sessions_sync(+ store: ChatHistoryStore | str | Path | None = None,+ *,+ limit: int = 20,+ offset: int = 0,+ user: str | None = None,+) -> list[dict[str, Any]]:+ """同步读会话列表(http.server 线程用)。库不可用返回空。"""+ st = _coerce_store(store)+ if st is None:+ return []+ return st.list_sessions_blocking(limit=limit, offset=offset, user=user)+++def _is_legacy_db_path_call(+ session_id: str | Path,+ store: ChatHistoryStore | str | Path | None,+) -> bool:+ if isinstance(session_id, Path):+ return True+ if store is None or isinstance(store, ChatHistoryStore):+ return False+ return isinstance(session_id, str) and session_id.endswith(".db")+++def get_session_detail_sync(+ session_id: str | Path,+ store: ChatHistoryStore | str | Path | None = None,+ *,+ user: str | None = None,+) -> dict[str, Any] | None:+ """同步读会话详情。兼容旧调用 ``(db_path, session_id)``。"""+ if _is_legacy_db_path_call(session_id, store):+ db_path, sid = session_id, str(store or "")+ if not sid:+ return None+ st = _coerce_store(db_path)+ if st is None:+ return None+ return st.get_session_detail_blocking(sid, user=user)+ if not session_id:+ return None+ st = _coerce_store(store)+ if st is None:+ return None+ return st.get_session_detail_blocking(str(session_id), user=user)++class HistoryFrameRunner:- """Run async history callbacks from sync WS proxy threads."""+ """Run async history callbacks from sync WS proxy / Listen enqueue threads."""def __init__(self, store: ChatHistoryStore) -> None:self._callback = make_history_callback(store)@@ -373,86 +889,13 @@ class HistoryFrameRunner:except Exception:logger.warning("[history] submit frame failed dir=%s", direction, exc_info=True)--def _open_readonly(db_path: str | Path) -> sqlite3.Connection:- conn = sqlite3.connect(str(db_path))- conn.row_factory = sqlite3.Row- return conn---def list_sessions_sync(- db_path: str | Path,- *,- limit: int = 20,- offset: int = 0,- user: str | None = None,-) -> list[dict[str, Any]]:- """同步读会话列表(http.server 线程用)。db 不存在或无表返回空。按 user 过滤(空归一为 'guest')。"""- if not Path(db_path).exists():- return []- limit = max(1, min(limit, _MAX_LIST_LIMIT))- offset = max(0, offset)- if not user:- user = "guest"- conn = _open_readonly(db_path)- try:- if user:- rows = conn.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- "FROM sessions WHERE user = ? ORDER BY updated_at DESC LIMIT ? OFFSET ?",- (user, limit, offset),- ).fetchall()- else:- rows = conn.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- "FROM sessions ORDER BY updated_at DESC LIMIT ? OFFSET ?",- (limit, offset),- ).fetchall()- return [dict(r) for r in rows]- except sqlite3.OperationalError:- return []- finally:- conn.close()---def get_session_detail_sync(- db_path: str | Path,- session_id: str,- *,- user: str | None = None,-) -> dict[str, Any] | None:- """同步读会话详情。db 不存在 / 无表 / 会话不存在均返回 None。校验 user 归属(空归一为 'guest')。"""- if not Path(db_path).exists():- return None- if not user:- user = "guest"- conn = _open_readonly(db_path)- try:- where = "WHERE session_id = ? AND user = ?"- params: tuple = (session_id, user)- s = conn.execute(- "SELECT session_id, user, title, message_count, last_preview, created_at, updated_at "- f"FROM sessions {where}",- params,- ).fetchone()- if s is None:- return None- msgs = conn.execute(- "SELECT role, content, event_type, timestamp, request_id "- "FROM messages WHERE session_id = ? ORDER BY timestamp ASC",- (session_id,),- ).fetchall()- return {- "session_id": s["session_id"],- "user": s["user"],- "title": s["title"],- "message_count": s["message_count"],- "last_preview": s["last_preview"],- "created_at": s["created_at"],- "updated_at": s["updated_at"],- "messages": [dict(m) for m in msgs],- }- except sqlite3.OperationalError:- return None- finally:- conn.close()+ def stop(self) -> None:+ if not self._started:+ return+ try:+ self._loop.call_soon_threadsafe(self._loop.stop)+ except Exception: # noqa: BLE001+ logger.debug("[history] stop loop failed", exc_info=True)+ if self._thread.is_alive():+ self._thread.join(timeout=5.0)+ self._started = Falsediff --git a/jiuwenswarm/common/request_ext.py b/jiuwenswarm/common/request_ext.pynew file mode 100644index 0000000000..86a0093602--- /dev/null+++ b/jiuwenswarm/common/request_ext.py@@ -0,0 +1,139 @@+"""请求级扩展字段透传(Web 握手 query / header → Message.metadata['ext'])。++将一个 ``dict[str, Any]`` 从 Channel 入口写入 ``Message.metadata[METADATA_KEY]``,+由 AgentServer 入口抬升到请求级 ContextVar,供 Agent rail 通过 :func:`get_ext` 读取。++要透传哪些字段由环境变量声明(逗号分隔),两套名字等价,先读 Swarm 名:++- ``JIUWENSWARM_REQUEST_EXT_FORWARD_HEADERS``+- ``JIUWENCLAW_REQUEST_EXT_FORWARD_HEADERS``(企业 kub 兼容)++运行时可调 :func:`set_forward_headers` 覆盖。载体内的键名与值含义由集成方约定。+"""+from __future__ import annotations++import os+from contextvars import ContextVar, Token+from typing import Any, Mapping++ENV_FORWARD_HEADERS = "JIUWENSWARM_REQUEST_EXT_FORWARD_HEADERS"+ENV_FORWARD_HEADERS_LEGACY = "JIUWENCLAW_REQUEST_EXT_FORWARD_HEADERS"+METADATA_KEY = "ext"++_request_ext: ContextVar["dict[str, Any] | None"] = ContextVar(+ "jw_request_ext", default=None,+)++# 运行时覆盖。优先级:set_forward_headers > 环境变量 > 空(关闭)。+_runtime_override: "list[str] | None" = None+++def set_forward_headers(headers: "list[str] | None") -> None:+ """整体覆盖 forward_headers(管控面 / DB 监听器使用)。++ 传 None 等价于撤销覆盖,回落到环境变量;传空 list 等价于关闭透传。+ """+ global _runtime_override+ if headers is None:+ _runtime_override = None+ else:+ _runtime_override = [str(x).strip() for x in headers if str(x).strip()]+++def register_forward_header(name: str) -> None:+ """加法注册单个字段名(扩展加载时使用)。"""+ global _runtime_override+ name = str(name).strip()+ if not name:+ return+ if _runtime_override is None:+ _runtime_override = list(_env_forward_headers())+ if name not in _runtime_override:+ _runtime_override.append(name)+++def register_forward_headers(names: "list[str]") -> None:+ """加法注册多个字段名。"""+ for n in names or []:+ register_forward_header(n)+++def _env_forward_headers() -> "list[str]":+ raw = os.environ.get(ENV_FORWARD_HEADERS, "") or os.environ.get(ENV_FORWARD_HEADERS_LEGACY, "")+ if not raw:+ return []+ return [x.strip() for x in raw.split(",") if x.strip()]+++def _read_forward_headers() -> "list[str]":+ if _runtime_override is not None:+ return list(_runtime_override)+ return _env_forward_headers()+++def build_ext_from_source(source: "Mapping[str, Any] | None") -> "dict[str, Any] | None":+ """从入站 mapping(HTTP header 或 WS query 字典)按配置抽取扩展字段。++ 支持值为字符串或字符串列表(``parse_qs`` 输出);列表取首元素。+ 键名匹配大小写不敏感。+ """+ names = _read_forward_headers()+ if not names or not source:+ return None+ lower_to_actual = {k.lower(): k for k in source.keys() if isinstance(k, str)}+ out: dict[str, Any] = {}+ for name in names:+ actual = lower_to_actual.get(name.lower())+ if actual is None:+ continue+ val = source[actual]+ if isinstance(val, (list, tuple)):+ val = val[0] if val else None+ if val is None or val == "":+ continue+ out[name] = val+ return out or None+++def set_current(ext: "dict[str, Any] | None") -> "Token":+ """Channel 入口使用:将 ext 写入 ContextVar,返回还原 token。"""+ return _request_ext.set(dict(ext) if ext else None)+++def attach_to_metadata(+ metadata: "dict[str, Any] | None",+ ext: "dict[str, Any] | None" = None,+) -> "dict[str, Any] | None":+ """构造 Message 时使用:将 ext 写入 metadata。++ ``ext`` 缺省时读取当前 ContextVar 中的 ext。无 ext 时返回原 metadata。+ """+ if ext is None:+ ext = _request_ext.get()+ if not ext:+ return metadata+ out = dict(metadata or {})+ out[METADATA_KEY] = dict(ext)+ return out+++def lift_from_metadata(metadata: "Mapping[str, Any] | None") -> "Token | None":+ """AgentServer 入口使用:从 request.metadata 抬升 ext 到 ContextVar。"""+ if not isinstance(metadata, Mapping):+ return None+ raw = metadata.get(METADATA_KEY)+ if not isinstance(raw, dict) or not raw:+ return None+ return _request_ext.set(dict(raw))+++def reset_ext(token: "Token | None") -> None:+ """与 :func:`set_current` / :func:`lift_from_metadata` 配对,还原 ContextVar。"""+ if token is not None:+ _request_ext.reset(token)+++def get_ext() -> "dict[str, Any]":+ """Agent rail 使用:读取当前请求的扩展字段。无字段时返回空 dict。"""+ cur = _request_ext.get()+ return dict(cur) if cur else {}diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 091f58831c..5bbc23a7fd 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1866,7 +1866,12 @@ async def _run_with_telemetry(web_channel = Nonetui_channel = None- web_config = WebChannelConfig(enabled=True, host=web_host, port=web_port, path=web_path)+ web_config = WebChannelConfig(+ enabled=True,+ host=web_host,+ ws_port=web_port,+ path=web_path,+ )web_channel = WebChannel(web_config, _DummyBus())# 注入 Git diff 监控注册表(设计文档阶段10):@@ -2738,12 +2743,24 @@ async def _run_with_telemetry(if web_channel is not Noneelse None)+ # Give WebChannel.start() a tick to bind WS + start Web HTTP before logging.+ if web_task is not None:+ for _ in range(40):+ if getattr(web_channel, "web_http_port", None):+ break+ await asyncio.sleep(0.05)+ web_http_port_for_log: int | str = "-"+ if web_channel is not None:+ port_val = getattr(web_channel, "web_http_port", None)+ web_http_port_for_log = port_val if port_val is not None else "-"if web_channel is not None:logger.info(- "[App] started: Web ws://%s:%s%s AgentServer: %s Press Ctrl+C to exit.",+ "[App] started: Web ws://%s:%s%s WebHTTP http://%s:%s/api/v1 AgentServer: %s Press Ctrl+C to exit.",web_host,web_port,web_path,+ web_host,+ web_http_port_for_log,agent_server_url,)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 881a253ef4..dedad38cfd 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -2369,6 +2369,180 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:logger.warning("[models.replace_all] %s", exc)await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")+ def _entry_model_name(entry: dict) -> str:+ raw = (entry.get("model_client_config") or {}).get("model_name", "")+ return str(raw or "").strip()++ def _get_raw_model_list() -> list[dict]:+ raw = get_config_raw()+ raw_models = raw.get("models", {}) if isinstance(raw, dict) else {}+ if "defaults" in raw_models and isinstance(raw_models["defaults"], list) and raw_models["defaults"]:+ return list(raw_models["defaults"])+ if "default" in raw_models and isinstance(raw_models["default"], dict):+ return [dict(raw_models["default"])]+ return []++ async def _models_save(ws, req_id, params, session_id):+ """新增或更新一个模型配置。model_name 已存在则更新,否则新增。++ 企业 kub 前端契约;支持 original_model_name 原子重命名。+ """+ if not isinstance(params, dict):+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")+ return+ model_name = str(params.get("model_name") or "").strip()+ if not model_name:+ await channel.send_response(ws, req_id, ok=False, error="model_name is required", code="BAD_REQUEST")+ return+ _raw_original = params.get("original_model_name")+ original_model_name = str(_raw_original).strip() if _raw_original is not None else None+ if original_model_name == "":+ original_model_name = None+ api_base = str(params.get("api_base") or "").strip()+ api_key = str(params.get("api_key") or "").strip()+ model_provider = _normalize_provider_value(str(params.get("model_provider") or "").strip())+ try:+ temperature = float(params.get("temperature", 0.95))+ except (TypeError, ValueError):+ temperature = 0.95++ available_model_providers = [p.value for p in ProviderType]+ if model_provider and model_provider not in available_model_providers:+ await channel.send_response(+ ws, req_id, ok=False,+ error=f"Model provider must be one of: {available_model_providers}",+ code="BAD_REQUEST",+ )+ return++ if api_key:+ from jiuwenswarm.extensions.registry import ExtensionRegistry+ crypto = ExtensionRegistry.get_instance().get_crypto_provider()+ if crypto:+ api_key = crypto.encrypt(api_key)+ else:+ logger.warning(+ "[models.save] crypto provider unavailable; api_key for %s stored in plaintext",+ model_name,+ )++ new_entry = {+ "model_client_config": {+ "api_base": api_base,+ "api_key": api_key,+ "model_name": model_name,+ "client_provider": model_provider,+ "timeout": int(params.get("timeout", 1800)),+ "verify_ssl": bool(params.get("verify_ssl", False)),+ },+ "model_config_obj": {+ "temperature": temperature,+ },+ }++ try:+ models = _get_raw_model_list()+ action = "created"+ if original_model_name and original_model_name != model_name:+ models = [m for m in models if _entry_model_name(m) != original_model_name]+ action = "renamed"+ for i, entry in enumerate(models):+ if _entry_model_name(entry) == model_name:+ models[i] = new_entry+ if action != "renamed":+ action = "updated"+ break+ else:+ models.append(new_entry)++ update_default_models_in_config(models)+ applied_without_restart = await _apply_config_change_set(+ _ConfigChangeSet({}, ["models.defaults"], force=True)+ )+ await channel.send_response(ws, req_id, ok=True, payload={+ "model_name": model_name,+ "action": action,+ "applied_without_restart": applied_without_restart,+ })+ except Exception as exc: # noqa: BLE001+ logger.warning("[models.save] %s", exc)+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")++ async def _models_remove(ws, req_id, params, session_id):+ """删除一个模型配置。至少保留一个模型。"""+ if not isinstance(params, dict):+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")+ return+ model_name = str(params.get("model_name") or "").strip()+ if not model_name:+ await channel.send_response(ws, req_id, ok=False, error="model_name is required", code="BAD_REQUEST")+ return++ try:+ models = _get_raw_model_list()+ if len(models) <= 1:+ await channel.send_response(+ ws, req_id, ok=False,+ error="At least one model configuration is required",+ code="BAD_REQUEST",+ )+ return+ new_models = [m for m in models if _entry_model_name(m) != model_name]+ if len(new_models) == len(models):+ await channel.send_response(+ ws, req_id, ok=False,+ error=f"Model '{model_name}' not found",+ code="NOT_FOUND",+ )+ return+ update_default_models_in_config(new_models)+ applied_without_restart = await _apply_config_change_set(+ _ConfigChangeSet({}, ["models.defaults"], force=True)+ )+ await channel.send_response(ws, req_id, ok=True, payload={+ "model_name": model_name,+ "applied_without_restart": applied_without_restart,+ })+ except Exception as exc: # noqa: BLE001+ logger.warning("[models.remove] %s", exc)+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")++ async def _models_set_active(ws, req_id, params, session_id):+ """设置默认选中的模型(将其移到列表第一位)。"""+ if not isinstance(params, dict):+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")+ return+ model_name = str(params.get("model_name") or "").strip()+ if not model_name:+ await channel.send_response(ws, req_id, ok=False, error="model_name is required", code="BAD_REQUEST")+ return++ try:+ models = _get_raw_model_list()+ target_idx = None+ for i, entry in enumerate(models):+ if _entry_model_name(entry) == model_name:+ target_idx = i+ break+ if target_idx is None:+ await channel.send_response(+ ws, req_id, ok=False,+ error=f"Model '{model_name}' not found",+ code="NOT_FOUND",+ )+ return+ if target_idx != 0:+ target = models.pop(target_idx)+ models.insert(0, target)+ update_default_models_in_config(models)+ await _apply_config_change_set(+ _ConfigChangeSet({}, ["models.defaults"], force=True)+ )+ await channel.send_response(ws, req_id, ok=True, payload={"model_name": model_name})+ except Exception as exc: # noqa: BLE001+ logger.warning("[models.set_active] %s", exc)+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")+async def _config_save_all(ws, req_id, params, session_id):"""Batch-save config panel changes and trigger a single hot reload.@@ -6010,12 +6184,29 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:except Exception as e: # noqa: BLE001await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")+ async def _connection_status(ws, req_id, params, session_id):+ """返回 Gateway / AgentServer 就绪状态,供 Web 客户端探测后端链路。"""+ ac = _resolve(agent_client)+ await channel.send_response(+ ws,+ req_id,+ ok=True,+ payload={+ "agent_ready": ac is not None and bool(getattr(ac, "server_ready", False)),+ "protocol_version": "1.0",+ },+ )++ channel.register_method("connection.status", _connection_status)channel.register_method("config.get", _config_get)channel.register_method("config.set", _config_set)channel.register_method("config.save_all", _config_save_all)channel.register_method("config.validate_model", _config_validate_model)channel.register_method("models.list", _models_list)channel.register_method("models.replace_all", _models_replace_all)+ channel.register_method("models.save", _models_save)+ channel.register_method("models.remove", _models_remove)+ channel.register_method("models.set_active", _models_set_active)channel.register_method("models.validate", _models_validate)channel.register_method("channel.get", _channel_get)channel.register_method("openai_account.auth.status", _openai_account_auth_status)diff --git a/jiuwenswarm/gateway/channel_manager/web/file_http.py b/jiuwenswarm/gateway/channel_manager/web/file_http.pynew file mode 100644index 0000000000..79c083d088--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/file_http.py@@ -0,0 +1,546 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""File / share / upload HTTP helpers (formerly ``app_web`` /file-api + /share-api).++Enterprise list/preview of remote Agent workspace is **not** guaranteed (1-A):+handlers read Gateway-local disks. Share uses disk history personally and+``ChatHistoryStore`` under ``AGENT_RUNTIME`` (2-A). Push lands on Gateway disk+and signs a download token (3-A); no POST to Web Pod.+"""++from __future__ import annotations++import json+import logging+import mimetypes+import os+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any+from urllib.parse import quote++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class FileHttpRoots:+ """Allowed roots for path sandbox (same semantics as legacy app_web)."""++ project_root: Path+ workspace_root: Path+ agent_teams_root: Path+ logs_root: Path+ auto_harness_root: Path+++def default_file_http_roots() -> FileHttpRoots:+ from openjiuwen.agent_teams.paths import get_agent_teams_home++ from jiuwenswarm.common.utils import (+ get_logs_dir,+ get_user_workspace_dir,+ )++ project_root = get_user_workspace_dir().resolve()+ # Legacy app_web sandbox: paths like ``agent/workspace`` live under+ # ``<user_workspace>/agent/``, not only multi-tenant ``get_agent_root_dir()``.+ workspace_root = (project_root / "agent").resolve()+ return FileHttpRoots(+ project_root=project_root,+ workspace_root=workspace_root,+ agent_teams_root=get_agent_teams_home().resolve(),+ logs_root=get_logs_dir().resolve(),+ auto_harness_root=(project_root / "auto-harness").resolve(),+ )+++def is_markdown(path_obj: Path) -> bool:+ return path_obj.suffix.lower() in {".md", ".mdx"}+++def is_path_under_allowed_root(roots: FileHttpRoots, target: Path) -> bool:+ return _is_under_file_roots(roots, target)+++def is_path_under_directory(base: Path, target: Path) -> bool:+ """Return True when ``target`` resolves inside ``base``."""+ try:+ base_resolved = base.resolve()+ target_resolved = target.resolve()+ return os.path.commonpath([str(base_resolved), str(target_resolved)]) == str(+ base_resolved,+ )+ except ValueError:+ return False+++def _is_under_file_roots(roots: FileHttpRoots, target: Path) -> bool:+ target_resolved = target.resolve()+ try:+ checks: list[Path] = [+ roots.workspace_root,+ (roots.project_root / "agent").resolve(),+ roots.agent_teams_root,+ roots.logs_root,+ roots.auto_harness_root,+ ]+ try:+ from jiuwenswarm.common.utils import get_agent_root_dir++ bound_agent = get_agent_root_dir().resolve()+ if bound_agent not in checks:+ checks.append(bound_agent)+ except Exception: # noqa: BLE001+ pass+ for root in checks:+ if os.path.commonpath([str(root), str(target_resolved)]) == str(root):+ return True+ return False+ except ValueError:+ return False+++def safe_filename(filename: str, *, default: str = "unnamed") -> str:+ """Return a single path segment safe for joining under a sandbox root."""+ name = Path(str(filename or "")).name.strip()+ if not name or name in {".", ".."}:+ return default+ return name+++def resolve_path_under_directory(base: Path, *parts: str) -> Path | None:+ """Join ``parts`` under ``base``; return None when the result escapes ``base``."""+ base_resolved = base.resolve()+ candidate = base_resolved.joinpath(*parts).resolve()+ if is_path_under_directory(base_resolved, candidate):+ return candidate+ return None+++def is_download_path_allowed(target: Path, roots: FileHttpRoots | None = None) -> bool:+ """Token downloads must stay under push inbox or configured file roots."""+ resolved = target.resolve()+ if is_path_under_directory(received_files_dir(), resolved):+ return True+ if roots is not None and is_path_under_allowed_root(roots, resolved):+ return True+ return False+++def resolve_under_project(roots: FileHttpRoots, rel_or_abs: str) -> Path:+ return (roots.project_root / rel_or_abs).resolve()+++def _normalize_lang_suffix(name: str) -> str:+ stem, suffix = name.rpartition(".")[0], name.rpartition(".")[2]+ suffix_lower = suffix.lower()+ if suffix_lower in ("md", "mdx"):+ stem_lower = stem.lower()+ if stem_lower.endswith("_zh"):+ stem = stem[:-3]+ elif stem_lower.endswith("_en"):+ stem = stem[:-3]+ return f"{stem}.{suffix}" if stem else name+++def generate_agent_data(project_root: Path) -> None:+ """Generate agent/workspace/agent-data.json from agent tree."""+ agent_root = (project_root / "agent").resolve()+ workspace_root = (agent_root / "workspace").resolve()+ output_path = (workspace_root / "agent-data.json").resolve()+ root_folder_key = "__root__"++ if not agent_root.exists():+ raise FileNotFoundError("agent directory not found")+ if not agent_root.is_dir():+ raise NotADirectoryError("agent is not a directory")++ folder_data: dict[str, list[dict[str, str | bool]]] = {}+ seen_paths: dict[str, set[str]] = {}+ for entry in sorted(workspace_root.rglob("*")):+ if not entry.is_file() or entry.name.startswith("."):+ continue+ if any(part.startswith(".") for part in entry.relative_to(workspace_root).parts):+ continue+ relative_folder_path = entry.parent.relative_to(agent_root).as_posix()+ folder_key = root_folder_key if relative_folder_path == "." else relative_folder_path++ display_name = _normalize_lang_suffix(entry.name)+ display_path = (+ f"agent/{relative_folder_path}/{display_name}".replace("/.", "/").replace("//", "/")+ if relative_folder_path != "."+ else f"agent/{display_name}"+ )+ seen = seen_paths.setdefault(folder_key, set())+ if display_path in seen:+ continue+ seen.add(display_path)++ folder_data.setdefault(folder_key, []).append(+ {+ "name": display_name,+ "path": display_path,+ "isMarkdown": entry.suffix.lower() in {".md", ".mdx"},+ }+ )++ sorted_folder_data = {+ folder_key: sorted(files, key=lambda item: item["path"])+ for folder_key, files in sorted(folder_data.items(), key=lambda item: item[0])+ }++ output_path.parent.mkdir(parents=True, exist_ok=True)+ output_path.write_text(+ json.dumps(sorted_folder_data, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+++def parse_single_byte_range(+ range_header: str,+ file_size: int,+) -> tuple[int, int] | None:+ """Parse one HTTP byte range, returning inclusive start and end offsets."""+ if file_size == 0 or not range_header.startswith("bytes=") or "," in range_header:+ return None++ range_value = range_header[6:]+ if "-" not in range_value:+ return None++ start_text, end_text = range_value.split("-", 1)+ if not start_text:+ if not end_text.isascii() or not end_text.isdecimal():+ return None+ suffix_length = int(end_text)+ if suffix_length <= 0:+ return None+ return max(0, file_size - suffix_length), file_size - 1++ if not start_text.isascii() or not start_text.isdecimal():+ return None+ if end_text and (not end_text.isascii() or not end_text.isdecimal()):+ return None++ start = int(start_text)+ end = int(end_text) if end_text else file_size - 1+ if start >= file_size or end < start:+ return None+ return start, min(end, file_size - 1)+++def list_markdown(roots: FileHttpRoots, dir_arg: str) -> tuple[int, dict[str, Any]]:+ if not dir_arg:+ return 400, {"error": "missing_dir"}+ full_dir = resolve_under_project(roots, dir_arg)+ if not is_path_under_allowed_root(roots, full_dir):+ return 403, {"error": "forbidden_dir"}+ if not full_dir.exists() or not full_dir.is_dir():+ return 200, {"files": []}+ files = []+ for entry in sorted(full_dir.iterdir(), key=lambda p: p.name.lower()):+ if not entry.is_file() or not is_markdown(entry):+ continue+ files.append(+ {+ "name": entry.name,+ "path": str(entry.relative_to(roots.project_root)),+ }+ )+ return 200, {"files": files}+++def list_files(roots: FileHttpRoots, dir_arg: str) -> tuple[int, dict[str, Any]]:+ if not dir_arg:+ return 400, {"error": "missing_dir"}+ full_dir = resolve_under_project(roots, dir_arg)+ if not is_path_under_allowed_root(roots, full_dir):+ return 403, {"error": "forbidden_dir"}+ if not full_dir.exists() or not full_dir.is_dir():+ return 200, {"files": []}+ files = []+ entries = sorted(+ full_dir.iterdir(),+ key=lambda p: (not p.is_dir(), p.name.lower()),+ )+ for entry in entries:+ files.append(+ {+ "name": entry.name,+ "path": str(entry.relative_to(roots.project_root)),+ "isMarkdown": is_markdown(entry) if entry.is_file() else False,+ "isDirectory": entry.is_dir(),+ }+ )+ return 200, {"files": files}+++def read_file_text(+ roots: FileHttpRoots,+ file_arg: str,+ encoding_arg: str = "utf-8",+) -> tuple[int, dict[str, Any] | None, bytes | None, str | None]:+ """Return (status, json_error, body_utf8, used_encoding)."""+ if not file_arg:+ return 400, {"error": "missing_file_path"}, None, None+ full_path = resolve_under_project(roots, file_arg)+ if not is_path_under_allowed_root(roots, full_path):+ return 403, {"error": "forbidden_path"}, None, None+ if not full_path.exists():+ if file_arg.replace("\\", "/") == "agent/workspace/agent-data.json":+ try:+ generate_agent_data(roots.project_root)+ except Exception as exc: # noqa: BLE001+ return 500, {"error": "generate_failed", "detail": str(exc)}, None, None+ if not full_path.exists():+ return (+ 404,+ {"error": "file_not_found", "fullPath": str(full_path)},+ None,+ None,+ )++ try:+ data, used_encoding = _read_file_with_encoding(full_path, encoding_arg)+ except OSError as exc:+ return 500, {"error": str(exc)}, None, None+ return 200, None, data.encode("utf-8"), used_encoding+++def _read_file_with_encoding(file_path: Path, encoding: str) -> tuple[str, str]:+ if encoding == "auto":+ import charset_normalizer++ raw_data = file_path.read_bytes()+ detected = charset_normalizer.from_bytes(raw_data).best()+ if detected is None:+ detected_encoding = "utf-8"+ else:+ detected_encoding = detected.encoding or "utf-8"+ try:+ return raw_data.decode(detected_encoding), detected_encoding+ except (UnicodeDecodeError, LookupError) as decode_exc:+ for try_encoding in ["gbk", "gb2312", "big5", "shift_jis", "euc_kr"]:+ try:+ return raw_data.decode(try_encoding), try_encoding+ except (UnicodeDecodeError, LookupError):+ continue+ raise OSError("Unable to decode file with any known encoding") from decode_exc+ return file_path.read_text(encoding=encoding), encoding+++def write_markdown_content(+ roots: FileHttpRoots,+ request_path: Any,+ request_content: Any,+) -> tuple[int, dict[str, Any]]:+ if not isinstance(request_path, str) or not request_path.strip():+ return 400, {"error": "missing_file_path"}+ if not isinstance(request_content, str):+ return 400, {"error": "missing_file_content"}+ full_path = resolve_under_project(roots, request_path)+ if not is_path_under_allowed_root(roots, full_path):+ return 403, {"error": "forbidden_path"}+ if not is_markdown(full_path):+ return 400, {"error": "only_markdown_supported"}+ if not full_path.exists():+ return 404, {"error": "file_not_found"}+ try:+ full_path.write_text(request_content, encoding="utf-8")+ except OSError as exc:+ return 500, {"error": str(exc)}+ return 200, {"ok": True}+++def resolve_raw_file_path(+ roots: FileHttpRoots,+ file_arg: str,+) -> tuple[int, dict[str, Any] | None, Path | None]:+ if not file_arg:+ return 400, {"error": "missing_file_path"}, None+ full_path = resolve_under_project(roots, file_arg)+ if not is_path_under_allowed_root(roots, full_path):+ return 403, {"error": "forbidden_path"}, None+ if not full_path.is_file():+ return 404, {"error": "file_not_found"}, None+ return 200, None, full_path+++def guess_mime(path: Path | str) -> str:+ name = path.name if isinstance(path, Path) else os.path.basename(path)+ mime_type, _ = mimetypes.guess_type(name)+ return mime_type or "application/octet-stream"+++def content_disposition(file_name: str, *, inline: bool) -> str:+ disposition = "inline" if inline else "attachment"+ encoded_name = quote(file_name, safe="")+ return f"{disposition}; filename*=UTF-8''{encoded_name}"+++def received_files_dir() -> Path:+ """Gateway-local directory for enterprise push payloads (replaces Web Pod)."""+ override = os.getenv("JIUWENSWARM_WEB_RECEIVED_FILES", "").strip()+ if override:+ path = Path(override).expanduser().resolve()+ else:+ from jiuwenswarm.common.utils import get_user_workspace_dir++ path = (get_user_workspace_dir() / "web_received_files").resolve()+ path.mkdir(parents=True, exist_ok=True)+ return path+++def save_pushed_file(+ *,+ file_bytes: bytes,+ filename: str,+ session_id: str,+) -> dict[str, Any]:+ """Persist upload and return download metadata (3-A: no Web Pod push)."""+ from jiuwenswarm.agents.harness.common.tools.web_file_download import (+ build_file_download_info,+ )++ clean_name = safe_filename(filename)+ safe_name = f"{int(time.time())}_{clean_name}"+ local_path = resolve_path_under_directory(received_files_dir(), safe_name)+ if local_path is None:+ raise ValueError("invalid_filename")+ local_path.write_bytes(file_bytes)+ download_info = build_file_download_info(+ file_path=str(local_path),+ file_name=clean_name,+ session_id=session_id,+ )+ return {+ "success": True,+ "file_path": str(local_path),+ "download_url": download_info["download_url"],+ "download_token": download_info["download_token"],+ "expires_at": download_info.get("expires_at"),+ }+++def process_obs_upload_body(raw: bytes) -> tuple[int, dict[str, Any]]:+ try:+ payload = json.loads(raw.decode("utf-8") if raw else "{}")+ except json.JSONDecodeError:+ return 400, {"ok": False, "error": "invalid_json"}+ if not isinstance(payload, dict):+ return 400, {"ok": False, "error": "invalid_payload"}+ try:+ from jiuwenswarm.channels.web.minio_upload import upload_base64_payload++ return 200, upload_base64_payload(payload)+ except Exception as exc:+ logger.error("[file_http] MinIO upload failed: %s", exc, exc_info=True)+ return 500, {"ok": False, "error": str(exc)}+++def _resolve_session_title(session_dir: Path, history: list[dict[str, Any]]) -> str:+ metadata_path = session_dir / "metadata.json"+ if metadata_path.exists():+ try:+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ title = metadata.get("title") if isinstance(metadata, dict) else None+ if isinstance(title, str) and title.strip():+ return title.strip()+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):+ pass+ for record in history:+ if record.get("role") == "user":+ content = record.get("content")+ if isinstance(content, str) and content.strip():+ return content.strip().replace("\n", " ")[:80]+ return session_dir.name+++def build_share_snapshot(+ *,+ session_id: str,+ user: str | None = None,+) -> tuple[dict[str, Any], str]:+ """Build share payload.++ Personal: disk session history. Enterprise (``AGENT_RUNTIME``): ChatHistoryStore (2-A).+ """+ exported_at = time.strftime("%Y-%m-%dT%H:%M:%S%z")+ timestamp = time.strftime("%Y%m%d-%H%M%S")+ filename = f"jiuwenswarm-share-{timestamp}.png"++ if os.getenv("AGENT_RUNTIME", "").strip():+ from jiuwenswarm.channels.web.history_store import get_session_detail_sync++ detail = get_session_detail_sync(session_id, user=user)+ if detail is None:+ raise FileNotFoundError("history_not_found")+ messages = detail.get("messages") if isinstance(detail, dict) else None+ if not isinstance(messages, list):+ raise ValueError("invalid_history_shape")+ history_raw = [m for m in messages if isinstance(m, dict)]+ title = ""+ if isinstance(detail, dict):+ raw_title = detail.get("title")+ if isinstance(raw_title, str) and raw_title.strip():+ title = raw_title.strip()+ if not title:+ title = _resolve_session_title(Path(session_id), history_raw)+ snapshot = {+ "session_id": session_id,+ "metadata": {+ "title": title,+ "exported_at": exported_at,+ "filename": filename,+ },+ "records": history_raw,+ }+ return snapshot, filename++ from jiuwenswarm.common.utils import get_agent_sessions_dir+ from jiuwenswarm.server.runtime.session.session_history import (+ history_exists,+ load_history_records,+ )++ sessions_root = get_agent_sessions_dir().resolve()+ session_dir = (sessions_root / session_id).resolve()+ try:+ if os.path.commonpath([str(sessions_root), str(session_dir)]) != str(sessions_root):+ raise FileNotFoundError("history_not_found")+ except ValueError as exc:+ raise FileNotFoundError("history_not_found") from exc++ if not session_dir.exists() or not history_exists(session_id):+ raise FileNotFoundError("history_not_found")++ metadata_path = session_dir / "metadata.json"+ if metadata_path.exists():+ try:+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ owner = metadata.get("user_id") if isinstance(metadata, dict) else None+ if isinstance(owner, str) and owner.strip():+ if not user or owner.strip() != user.strip():+ raise FileNotFoundError("history_not_found")+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):+ pass++ try:+ history_raw = load_history_records(session_id)+ except Exception as exc:+ raise ValueError("invalid_history_json") from exc+ if not isinstance(history_raw, list):+ raise ValueError("invalid_history_shape")++ history = [item for item in history_raw if isinstance(item, dict)]+ snapshot = {+ "session_id": session_id,+ "metadata": {+ "title": _resolve_session_title(session_dir, history),+ "exported_at": exported_at,+ "filename": filename,+ },+ "records": history_raw,+ }+ return snapshot, filenamediff --git a/jiuwenswarm/gateway/channel_manager/web/invoke.py b/jiuwenswarm/gateway/channel_manager/web/invoke.pynew file mode 100644index 0000000000..186284cda5--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/invoke.py@@ -0,0 +1,78 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Unique WebChannel inbound dispatch (WS and HTTP share this pipeline)."""++from __future__ import annotations++import inspect+import logging+from typing import Any++from jiuwenswarm.common.schema.message import Message++logger = logging.getLogger(__name__)+++async def dispatch_web_request(+ channel: Any,+ *,+ method: str,+ params: dict[str, Any],+ request_id: str,+ outbound: Any,+ session_id: str,+ user_message: Message,+) -> None:+ """Run HANDLER_BEFORE → on_message (or bus) → local handler / METHOD_NOT_FOUND.++ ``outbound`` is the reply target: a real WebSocket peer or request-scoped+ HTTP Outbound (``HttpJsonOutbound`` / ``HttpSseOutbound``).+ """+ # Lazy import: avoid import cycle with web_connect (which calls this module).+ from jiuwenswarm.gateway.channel_manager.web.web_rpc_host import (+ HANDLER_BEFORE_CALLBACK_METHODS as _HANDLER_BEFORE_CALLBACK_METHODS,+ MethodHandlerInvocation as _MethodHandlerInvocation,+ )++ handler = channel.rpc.method_handlers.get(method)+ handler_already_called = False+ if method in _HANDLER_BEFORE_CALLBACK_METHODS and handler is not None:+ handler_already_called = await channel.rpc.invoke_method_handler(+ _MethodHandlerInvocation(+ outbound, method, request_id, params, session_id, handler,+ ),+ )+ if not handler_already_called:+ return++ handled_by_callback = False+ on_message_cb = channel.rpc.on_message_cb+ if on_message_cb is not None:+ result = on_message_cb(user_message)+ if inspect.isawaitable(result):+ result = await result+ handled_by_callback = bool(result)+ else:+ bus = getattr(channel, "bus", None)+ if bus is not None and hasattr(bus, "publish_user_messages"):+ await bus.publish_user_messages(user_message)++ if handled_by_callback:+ return+ if handler_already_called:+ return++ if handler is not None:+ await channel.rpc.invoke_method_handler(+ _MethodHandlerInvocation(+ outbound, method, request_id, params, session_id, handler,+ ),+ )+ else:+ await channel.send_response(+ outbound,+ request_id,+ ok=False,+ error=f"unknown method: {method}",+ code="METHOD_NOT_FOUND",+ )diff --git a/jiuwenswarm/gateway/channel_manager/web/outbound.py b/jiuwenswarm/gateway/channel_manager/web/outbound.pynew file mode 100644index 0000000000..df9bb9ffb4--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/outbound.py@@ -0,0 +1,327 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Request-scoped HTTP outbounds for Gateway Web HTTP (JSON unary / SSE)."""++from __future__ import annotations++import asyncio+import json+import logging+import uuid+from typing import Any, AsyncIterator, Protocol, runtime_checkable++logger = logging.getLogger(__name__)++_STREAM_END_EVENTS = frozenset({"chat.final", "chat.error"})++# Agent ``session.create`` rejects params.session_id (restore via session.switch).+_METHODS_WITHOUT_PARAM_SESSION_ID = frozenset({"session.create"})+++def bind_http_session(+ method: str,+ params: dict[str, Any] | None,+ *,+ header_session_id: str = "",+ bind_param: bool = True,+) -> tuple[str, dict[str, Any]]:+ """Return ``(envelope_session_id, params)`` for an HTTP call.++ Envelope session_id is always set (routing / request outbound). Client-supplied+ ``params.session_id`` is not invented for methods that Agent rejects.+ When ``bind_param`` is False, a missing session_id is not injected into+ params (settings / catalog RPCs).+ """+ out = dict(params or {})+ client_sid = str(out.get("session_id") or header_session_id or "").strip()+ if method in _METHODS_WITHOUT_PARAM_SESSION_ID:+ out.pop("session_id", None)+ if method == "session.create" and not str(out.get("create_token") or "").strip():+ out["create_token"] = uuid.uuid4().hex+ return f"webhttp_{uuid.uuid4().hex[:12]}", out+ envelope = client_sid or f"webhttp_{uuid.uuid4().hex[:12]}"+ if not bind_param:+ if client_sid:+ out["session_id"] = client_sid+ else:+ out.pop("session_id", None)+ return envelope, out+ if not client_sid:+ out.setdefault("session_id", envelope)+ else:+ out["session_id"] = client_sid+ return envelope, out+++def _is_sse_end_frame(frame: dict[str, Any]) -> bool:+ ev = str(frame.get("event") or "")+ if ev in _STREAM_END_EVENTS:+ return True+ payload = frame.get("payload") if isinstance(frame.get("payload"), dict) else {}+ return ev == "history.message" and payload.get("status") == "done"+++def _normalize_frame(data: Any) -> dict[str, Any] | None:+ if isinstance(data, dict):+ return data+ if isinstance(data, (bytes, bytearray)):+ try:+ data = data.decode("utf-8")+ except Exception: # noqa: BLE001+ return None+ if isinstance(data, str):+ try:+ parsed = json.loads(data)+ except json.JSONDecodeError:+ return None+ return parsed if isinstance(parsed, dict) else None+ return None+++@runtime_checkable+class Outbound(Protocol):+ """Minimal request-scoped reply target for Web HTTP."""++ is_http_outbound: bool+ closed: bool+ outbound_id: str++ def accept_frame(self, frame: dict[str, Any]) -> None:+ ...++ async def close(self) -> None:+ ...+++class _HttpOutboundBase:+ """Shared fields for JSON / SSE HTTP outbounds."""++ is_http_outbound = True++ def __init__(+ self,+ *,+ headers: dict[str, str] | None = None,+ remote: tuple[str, int] = ("127.0.0.1", 0),+ path: str = "/api/v1",+ session_id: str = "",+ ) -> None:+ self.request_headers = {str(k): str(v) for k, v in (headers or {}).items()}+ self.remote_address = remote+ self.path = path+ self.session_id = str(session_id or "")+ self.closed = False+ self.outbound_id = uuid.uuid4().hex+ # Compatible with WebChannel metadata.ws_id / _lookup_peer.+ self._jiuwen_ws_id = self.outbound_id++ async def reply(+ self,+ req_id: str,+ *,+ ok: bool,+ payload: dict[str, Any] | None = None,+ error: str | None = None,+ code: str | None = None,+ ) -> None:+ frame: dict[str, Any] = {+ "type": "res",+ "id": req_id,+ "ok": ok,+ "payload": payload or {},+ }+ if not ok:+ frame["error"] = error or "request failed"+ if code:+ frame["code"] = code+ self.accept_frame(frame)++ def emit(+ self,+ event: str,+ payload: dict[str, Any],+ *,+ seq: int | None = None,+ stream_id: str | None = None,+ ) -> None:+ frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}+ if seq is not None:+ frame["seq"] = seq+ if stream_id is not None:+ frame["stream_id"] = stream_id+ self.accept_frame(frame)++ def accept_frame(self, frame: dict[str, Any]) -> None: # pragma: no cover - abstract+ raise NotImplementedError++ async def send(self, data: str | bytes) -> None:+ """Compat with writer-style ``ws.send`` (JSON string or bytes)."""+ if self.closed:+ raise ConnectionError("http outbound closed")+ frame = _normalize_frame(data)+ if frame is not None:+ self.accept_frame(frame)++ async def close(self) -> None:+ self.closed = True+++class HttpJsonOutbound(_HttpOutboundBase):+ """Capture the matching ``res`` frame for unary HTTP handlers."""++ def __init__(self, **kwargs: Any) -> None:+ super().__init__(**kwargs)+ self._frames: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue(maxsize=256)++ def accept_frame(self, frame: dict[str, Any]) -> None:+ if self.closed:+ return+ try:+ self._frames.put_nowait(frame)+ except asyncio.QueueFull: # pragma: no cover+ logger.warning("[WebHTTP] HttpJsonOutbound queue full; dropping frame")++ async def wait_response(+ self,+ req_id: str,+ *,+ timeout: float = 60.0,+ ) -> dict[str, Any]:+ loop = asyncio.get_running_loop()+ deadline = loop.time() + timeout+ while True:+ remaining = deadline - loop.time()+ if remaining <= 0:+ return {+ "type": "res",+ "id": req_id,+ "ok": False,+ "error": "request timeout",+ "code": "TIMEOUT",+ "payload": {},+ }+ try:+ frame = await asyncio.wait_for(self._frames.get(), timeout=remaining)+ except asyncio.TimeoutError:+ return {+ "type": "res",+ "id": req_id,+ "ok": False,+ "error": "request timeout",+ "code": "TIMEOUT",+ "payload": {},+ }+ if frame is None:+ return {+ "type": "res",+ "id": req_id,+ "ok": False,+ "error": "connection closed",+ "code": "INTERNAL_ERROR",+ "payload": {},+ }+ if frame.get("type") == "res" and frame.get("id") == req_id:+ return frame++ async def close(self) -> None:+ if self.closed:+ return+ self.closed = True+ try:+ self._frames.put_nowait(None)+ except asyncio.QueueFull:+ pass+++class HttpSseOutbound(_HttpOutboundBase):+ """Queue outbound frames for SSE / history aggregation consumers."""++ def __init__(self, *, maxsize: int = 256, **kwargs: Any) -> None:+ super().__init__(**kwargs)+ self._frames: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue(maxsize=maxsize)++ def accept_frame(self, frame: dict[str, Any]) -> None:+ if self.closed:+ return+ try:+ self._frames.put_nowait(frame)+ except asyncio.QueueFull:+ logger.warning(+ "[WebHTTP] HttpSseOutbound queue full outbound_id=%s; dropping frame",+ self.outbound_id,+ )++ async def iter_sse_frames(+ self,+ req_id: str,+ *,+ timeout: float = 600.0,+ idle_timeout: float = 0.0,+ keepalive: float = 30.0,+ ) -> AsyncIterator[dict[str, Any]]:+ """Yield frames until stream end, total timeout, or optional idle timeout.++ ``idle_timeout<=0`` keeps the historical behaviour: emit keepalive while+ waiting until ``timeout`` elapses. When ``idle_timeout>0``, end with+ ``chat.error`` if no real frame arrives within that idle window.+ """+ loop = asyncio.get_running_loop()+ deadline = loop.time() + max(float(timeout), 0.1)+ idle_limit = float(idle_timeout) if idle_timeout and idle_timeout > 0 else 0.0+ last_frame_at = loop.time()+ ping = max(float(keepalive), 0.5)+ while True:+ now = loop.time()+ remaining = deadline - now+ if remaining <= 0:+ yield {+ "type": "event",+ "event": "chat.error",+ "payload": {"error": "stream timeout", "session_id": ""},+ }+ return+ if idle_limit > 0 and (now - last_frame_at) >= idle_limit:+ yield {+ "type": "event",+ "event": "chat.error",+ "payload": {"error": "stream idle timeout", "session_id": ""},+ }+ return+ wait_for = min(remaining, ping)+ if idle_limit > 0:+ wait_for = min(wait_for, idle_limit - (now - last_frame_at))+ wait_for = max(wait_for, 0.05)+ try:+ frame = await asyncio.wait_for(self._frames.get(), timeout=wait_for)+ except asyncio.TimeoutError:+ if idle_limit > 0 and (loop.time() - last_frame_at) >= idle_limit:+ yield {+ "type": "event",+ "event": "chat.error",+ "payload": {"error": "stream idle timeout", "session_id": ""},+ }+ return+ yield {"type": "keepalive"}+ continue+ if frame is None:+ return+ last_frame_at = loop.time()+ ftype = frame.get("type")+ if ftype == "res" and frame.get("id") == req_id:+ yield frame+ if not frame.get("ok", True):+ return+ continue+ if ftype == "event":+ yield frame+ if _is_sse_end_frame(frame):+ return++ async def close(self) -> None:+ if self.closed:+ return+ self.closed = True+ try:+ self._frames.put_nowait(None)+ except asyncio.QueueFull:+ passdiff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.pyindex 3474d090ee..1b8c007e26 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py@@ -1,1373 +1,274 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.-"""WebChannel - WebSocket 通道实现.+"""WebChannel facade: composes WS transport, HTTP transport, and RPC host.-提供可扩展的方法处理器注册机制 (`register_method`) 和连接钩子 (`on_connect`),-使上层应用可以灵活控制每个 req method 的行为,而无需修改通道本身。+Public API is unchanged (``WebChannel`` / ``WebChannelConfig``). Internally:++- ``WebWsTransport`` — WebSocket only (extends ``BaseWsChannel``)+- ``WebHttpTransport`` — uvicorn / FastAPI lifecycle+- ``WebRpcHost`` — ``register_method``, history capture, shared handlers+- ``WebDeliveryRegistry`` — HTTP request-scoped outbounds"""from __future__ import annotations-import asyncio-import inspect-import json-import logging-import os-import secrets-import time-import uuid-from dataclasses import dataclass, field-from typing import Any, Awaitable, Callable-from urllib.parse import parse_qs, urlparse--import aiohttp-from websockets.exceptions import ConnectionClosed as WebSocketConnectionClosed--from jiuwenswarm.common.utils import get_agent_workspace_dir-from jiuwenswarm.gateway.channel_manager.base import ChannelMetadata, RobotMessageRouter-from jiuwenswarm.gateway.routing.base_ws_channel import BaseWsChannel-from jiuwenswarm.gateway.routing.keys import AgentRef, RoutingKey+from typing import Any, Callable++from jiuwenswarm.common.schema.message import Message, Mode, ReqMethod+from jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenswarm.gateway.routing.session_sharing import RoutingTarget-from jiuwenswarm.common.security.ws_origin import (- extract_handshake_request,- forbidden_origin_response,- get_header_value,- is_origin_check_enabled,- is_allowed_browser_origin,-)-from jiuwenswarm.common.schema.message import EventType, Message, Mode, ReqMethod-from jiuwenswarm.common.ws_diagnostics import (- describe_ws_exception,- describe_ws_peer,- format_ws_diagnostics,-)-logger = logging.getLogger(__name__)--_WEB_CONNECTION_USER_ID_ATTR = "_web_connection_user_id"--_HANDLER_BEFORE_CALLBACK_METHODS = frozenset({ReqMethod.CHAT_SEND.value})--_STREAM_COALESCE_EVENT_TYPES = frozenset({"chat.delta", "chat.reasoning"})-_STREAM_COALESCE_MAX_FRAMES = 32--_WEB_FULL_PAYLOAD_EVENT_TYPES = frozenset(- {- "connection.ack",- "todo.updated",- "task.start",- "task.update",- "task.complete",- "chat.tool_call",- "chat.tool_update",- "chat.tool_result",- "chat.processing_status",- "chat.interrupt_result",- "chat.evolution_status",- "chat.error",- "heartbeat.relay",- "context.usage",- "context.compression_state",- "chat.ask_user_question",- "chat.subtask_update",- "chat.symphony_status",- "chat.notice",- "history.message",- "chat.session_result",- "chat.usage_metadata",- "chat.usage_summary",- "chat.file",- "chat.retract",- "security.alert",- "goal.snapshot",- "goal.updated",- "runtime.accepted",- "execution.error",- "proactive_recommendation",- }+from jiuwenswarm.gateway.channel_manager.web.web_delivery_registry import WebDeliveryRegistry+from jiuwenswarm.gateway.channel_manager.web.web_http_transport import WebHttpTransport+from jiuwenswarm.gateway.channel_manager.web.web_rpc_host import (+ HANDLER_BEFORE_CALLBACK_METHODS,+ MethodHandler,+ MethodHandlerInvocation,+ WebRpcHost,+)+from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import (+ WebChannelConfig,+ WebWsTransport,+ _WEB_CONNECTION_USER_ID_ATTR,)-# ── 类型别名 ──────────────────────────────────────────────-# 方法处理器签名: (ws, req_id, params, session_id) -> None-MethodHandler = Callable[..., Awaitable[None]]-# 连接钩子签名: (ws) -> None | Awaitable[None]-ConnectHook = Callable[..., Any]---@dataclass(frozen=True)-class _MethodHandlerInvocation:- ws: Any- method: str- req_id: str- params: dict[str, Any]- session_id: str- handler: MethodHandler---@dataclass-class WebChannelConfig:- """WebChannel 配置."""-- enabled: bool = False- host: str = "127.0.0.1"- port: int = 19000- path: str = "/ws"- allow_from: list[str] = field(default_factory=list)+# Backward-compatible re-exports for invoke.py and tests.+_HANDLER_BEFORE_CALLBACK_METHODS = HANDLER_BEFORE_CALLBACK_METHODS+_MethodHandlerInvocation = MethodHandlerInvocation+__all__ = [+ "WebChannel",+ "WebChannelConfig",+ "_HANDLER_BEFORE_CALLBACK_METHODS",+ "_MethodHandlerInvocation",+ "_WEB_CONNECTION_USER_ID_ATTR",+]-class WebChannel(BaseWsChannel):- """Web 前端 WebSocket 通道.- 核心职责:- 1. 管理 WebSocket 连接生命周期- 2. 解析帧协议 (req / res / event)- 3. 将入站消息发布到 RobotMessageRouter- 4. 将方法路由委托给通过 `register_method` 注册的处理器- 5. V2: 基于 _clients_by_key[RoutingKey] 的 5 维精确路由- """+class WebChannel(BaseChannel):+ """Northbound Web gateway: WS + HTTP share one RPC host and delivery registry."""name = "web"channel_id = "web"- def __init__(self, config: WebChannelConfig, router: RobotMessageRouter):+ def __init__(self, config: WebChannelConfig, router: RobotMessageRouter) -> None:super().__init__(config, router)- self.config: WebChannelConfig = config- self._server: Any = None- self._on_message_cb: Callable[[Message], Any] | None = None- self._method_handlers: dict[str, MethodHandler] = {}- self._connect_hooks: list[ConnectHook] = []- self._disconnect_hooks: list[ConnectHook] = []- # ws -> set[session_id]: 追踪每个连接上活跃的 session- self._ws_sessions: dict[int, set[str]] = {}- # session_id -> is_processing: 由 chat.processing_status 事件维护,- # 供 /ws/git 写操作(如 discard_turn_changes)查询 agent 是否正在执行。- # 未跟踪的 session 默认返回 False(不忙碌)。- self._session_busy: dict[str, bool] = {}- # Git diff 监控注册表(设计文档阶段10):由 app_gateway 在启动期注入,- # handler 通过 ``getattr(channel, "git_watcher_registry", None)`` 防御性读取。+ self.config = config+ self.delivery = WebDeliveryRegistry()+ self.rpc = WebRpcHost(self)+ self.ws = WebWsTransport(config, router, self)+ self.http = WebHttpTransport(self)self.git_watcher_registry: Any = None- @staticmethod- def _coalescible_stream_frame(- frame: Any,- ) -> tuple[dict[str, Any], str] | None:- """Return (decoded frame, content) for a merge-safe stream frame.-- 帧已是 dict(入队时不预序列化),故无需 json.loads;返回 decoded 与- content 供 _coalesce 直接在 dict 层合并,省去 str↔dict 往返。- """- if not isinstance(frame, dict) or frame.get("type") != "event":- return None- if frame.get("event") not in _STREAM_COALESCE_EVENT_TYPES:- return None- payload = frame.get("payload")- if not isinstance(payload, dict):- return None- content = payload.get("content")- if not isinstance(content, str):- return None- return frame, content-- @staticmethod- def _same_stream_identity(- a: dict[str, Any],- b: dict[str, Any],- ) -> bool:- """两帧除 payload.content 外是否同流(可合并)。-- 逐键比对 payload 非 content 字段 + 外层 event 等键,避免构造 comparable- dict 副本与整 dict 哈希比对的开销。- """- a_payload = a["payload"]- b_payload = b["payload"]- if a.get("event") != b.get("event"):- return False- if a.get("type") != b.get("type"):- return False- for key in set(a_payload) | set(b_payload):- if key == "content":- continue- if a_payload.get(key) != b_payload.get(key):- return False- return True-- def _coalesce(- self,- first_frame: Any,- queue: asyncio.Queue,- ) -> list[Any]:- """Merge only contiguous stream frames with identical non-content data."""- parsed = self._coalescible_stream_frame(first_frame)- if parsed is None:- return [first_frame]-- decoded, merged_content = parsed- merged_count = 1- trailing: list[Any] = []-- while merged_count < _STREAM_COALESCE_MAX_FRAMES:- try:- candidate = queue.get_nowait()- except asyncio.QueueEmpty:- break- if candidate is None:- trailing.append(None)- break- candidate_parsed = self._coalescible_stream_frame(candidate)- if (- candidate_parsed is None- or not self._same_stream_identity(decoded, candidate_parsed[0])- ):- trailing.append(candidate)- break- merged_content += candidate_parsed[1]- merged_count += 1-- if merged_count == 1:- return [first_frame, *trailing]-- merged_payload = {**decoded["payload"], "content": merged_content}- return [{**decoded, "payload": merged_payload}, *trailing]-- # ── 公共属性 ──────────────────────────────────────────-- # channel_id 属性由 name 提供,BaseWsChannel.channel_id 通过 __init_subclass__ 或直接赋值为 "web"+ # ── Compatibility shims (invoke / handlers access private attrs) ──@property- def clients(self) -> set[Any]:- """当前活跃的 WebSocket 客户端集合(从 _clients_by_key 推导,只读副本)."""- result: set[Any] = set()- for ws_list in self._clients_by_key.values():- result.update(ws_list)- return result+ def _method_handlers(self) -> dict[str, MethodHandler]:+ return self.rpc.method_handlers- # ── 扩展注册 API ──────────────────────────────────────+ @_method_handlers.setter+ def _method_handlers(self, value: dict[str, MethodHandler]) -> None:+ self.rpc.method_handlers.clear()+ self.rpc.method_handlers.update(value)- def register_method(self, method: str, handler: MethodHandler) -> None:- """注册 req method 处理器.+ @property+ def _on_message_cb(self) -> Callable[[Message], Any] | None:+ return self.rpc.on_message_cb- handler 签名: ``async def handler(ws, req_id, params, session_id) -> None``- handler 应通过 `send_response` / `send_event` 向客户端回复。- """- self._method_handlers[method] = handler+ @_on_message_cb.setter+ def _on_message_cb(self, value: Callable[[Message], Any] | None) -> None:+ self.rpc.on_message_cb = value- def on_connect(self, callback: ConnectHook) -> None:- """注册连接建立钩子,新客户端接入时依次调用."""- self._connect_hooks.append(callback)+ def lookup_peer(self, peer_id: str) -> Any | None:+ ws = self.ws.lookup_ws_by_id(peer_id)+ if ws is not None:+ return ws+ return self.delivery.lookup(peer_id)- def on_disconnect(self, callback: ConnectHook) -> None:- """注册连接断开钩子,客户端断连时依次调用.+ def peers_for_session(self, session_id: str) -> set[Any]:+ peers = self.ws.peers_for_session_ws(session_id)+ peers.update(self.delivery.peers_for_session(session_id))+ return peers- callback 签名: ``async def callback(ws, session_ids: set[str]) -> None``- """- self._disconnect_hooks.append(callback)+ def _lookup_peer(self, peer_id: str) -> Any | None:+ return self.lookup_peer(peer_id)- def on_message(self, callback: Callable[[Message], None]) -> None:- """注册消息接收回调(替代默认的 router.publish_user_messages)。"""- self._on_message_cb = callback+ def _peers_for_session(self, session_id: str) -> set[Any]:+ return self.peers_for_session(session_id)- def wrap_message_callback(- self, wrapper: Callable[[Callable[[Message], Any] | None, Message], Any],- ) -> None:- """包装现有的消息回调。wrapper 接收 (original_callback, msg) 并返回处理结果。"""- original = self._on_message_cb+ def _record_history_frame(self, direction: str, data: Any) -> None:+ self.rpc.record_history_frame(direction, data)- def wrapped(msg):- return wrapper(original, msg)+ async def _invoke_method_handler(self, invocation: MethodHandlerInvocation) -> bool:+ return await self.rpc.invoke_method_handler(invocation)- self._on_message_cb = wrapped+ def _parse_req_method(self, method: str) -> ReqMethod | None:+ return WebWsTransport.parse_req_method(method)- # ── 帧发送 API(公开给处理器使用)─────────────────────+ def _parse_mode(self, raw_mode: Any) -> Mode:+ return WebWsTransport.parse_mode(raw_mode)- async def send_response(- self,- ws: Any,- req_id: str,- *,- ok: bool,- payload: dict[str, Any] | None = None,- error: str | None = None,- code: str | None = None,- ) -> None:- """向指定客户端发送 ``res`` 帧."""- frame: dict[str, Any] = {- "type": "res",- "id": req_id,- "ok": ok,- "payload": payload or {},- }- if not ok:- frame["error"] = error or "request failed"- if code:- frame["code"] = code- try:- self._enqueue_send(ws, frame)- except Exception as e:- if bool(getattr(ws, "closed", False)):- logger.debug(- "WebChannel send_response skipped on closed websocket: %s",- format_ws_diagnostics(- {"id": req_id},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )- return- raise+ @staticmethod+ def _make_session_id() -> str:+ return WebWsTransport.make_session_id()- async def send_event(- self,- ws: Any,- event: str,- payload: dict[str, Any],- *,- seq: int | None = None,- stream_id: str | None = None,- ) -> None:- """向指定客户端发送 ``event`` 帧."""- frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}- if seq is not None:- frame["seq"] = seq- if stream_id is not None:- frame["stream_id"] = stream_id- try:- self._enqueue_send(ws, frame)- except Exception as e:- if bool(getattr(ws, "closed", False)):- logger.debug(- "WebChannel send_event skipped on closed websocket: %s",- format_ws_diagnostics(- {"event": event, "seq": seq, "stream_id": stream_id},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )- return- raise+ @classmethod+ def _build_event_payload(cls, msg: Message, event_name: str) -> dict[str, Any]:+ return WebWsTransport.build_event_payload(msg, event_name)++ @staticmethod+ def _coalescible_stream_frame(frame: Any) -> tuple[dict[str, Any], str] | None:+ return WebWsTransport.coalescible_stream_frame(frame)@staticmethoddef _extract_query_user_id(flat_query: dict[str, str]) -> str | None:- uid = str(flat_query.get("user_id", "") or "").strip()- return uid or None+ return WebWsTransport.extract_query_user_id(flat_query)@staticmethoddef _extract_ws_header_user_id(ws: Any) -> str | None:- headers = (- getattr(getattr(ws, "request", None), "headers", None)- or getattr(ws, "request_headers", None)- )- raw = get_header_value(headers, "X-User-Id")- if raw is None:- return None- text = str(raw).strip()- return text or None+ return WebWsTransport.extract_ws_header_user_id(ws)@classmethoddef _resolve_connection_user_id(cls, flat_query: dict[str, str], ws: Any) -> str | None:- connection_user_id = cls._extract_query_user_id(flat_query) or cls._extract_ws_header_user_id(ws)- setattr(ws, _WEB_CONNECTION_USER_ID_ATTR, connection_user_id)- return connection_user_id+ return WebWsTransport.resolve_connection_user_id(flat_query, ws)@staticmethoddef _connection_user_id(ws: Any) -> str | None:- """返回 Web 连接建立时缓存的 user_id(query 或 X-User-Id Header)。"""- uid = getattr(ws, _WEB_CONNECTION_USER_ID_ATTR, None)- if uid is None:- return None- text = str(uid).strip()- return text or None+ return WebWsTransport.connection_user_id(ws)@staticmethoddef _routing_key_user_id(connection_user_id: str | None, remote: Any) -> str:- if connection_user_id:- return connection_user_id- return str(remote or "unknown")-- @classmethod- def _resolve_ws_identity(- cls,- ws: Any,- flat_query: dict[str, str],- remote: Any,- *,- route_type: str = "ws",- ) -> tuple[str | None, str]:- """解析 ws 连接身份,供 /ws 和 /ws/git 共用(设计文档 §5.3.7)。-- Args:- route_type: ``"ws"`` 主路由或 ``"git"`` /ws/git 路由,仅用于日志区分。-- Returns:- ``(connection_user_id, routing_key_user_id)``- """- connection_user_id = cls._resolve_connection_user_id(flat_query, ws)- routing_key_user_id = cls._routing_key_user_id(connection_user_id, remote)- return connection_user_id, routing_key_user_id-- async def _invoke_method_handler(- self,- invocation: _MethodHandlerInvocation,- ) -> bool:- kwargs: dict[str, Any] = {}- if "user_id" in inspect.signature(invocation.handler).parameters:- kwargs["user_id"] = self._connection_user_id(invocation.ws)- try:- await invocation.handler(- invocation.ws,- invocation.req_id,- invocation.params,- invocation.session_id,- **kwargs,- )- return True- except Exception as e:- ws_closed = bool(getattr(invocation.ws, "closed", False))- if ws_closed:- logger.warning(- "WebChannel method handler aborted on closed websocket: %s",- format_ws_diagnostics(- {- "method": invocation.method,- "id": invocation.req_id,- "session_id": invocation.session_id,- },- describe_ws_peer(invocation.ws),- describe_ws_exception(e),- ),- )- return False-- logger.error(- "WebChannel method handler error: %s",- format_ws_diagnostics(- {- "method": invocation.method,- "id": invocation.req_id,- "session_id": invocation.session_id,- },- describe_ws_peer(invocation.ws),- describe_ws_exception(e),- ),- )- try:- await self.send_response(- invocation.ws, invocation.req_id, ok=False,- error=f"handler error: {e}", code="INTERNAL_ERROR",- )- except Exception as send_err:- logger.warning(- "WebChannel failed to send handler error response ({}): {}",- invocation.method, send_err,- )- return False-- async def broadcast_event(- self,- event: str,- payload: dict[str, Any],- *,- seq: int | None = None,- stream_id: str | None = None,- exclude_ws: Any = None,- ) -> None:- """向所有已连接客户端广播 ``event`` 帧.-- exclude_ws: 排除单个发起方 ws(如 config.changed 的保存发起方),- 避免发起方收到自身触发的广播而误弹「丢弃草稿」确认框。发起方靠- 保存响应的本地乐观合并自行刷新,无需这条广播。- """- frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}- if seq is not None:- frame["seq"] = seq- if stream_id is not None:- frame["stream_id"] = stream_id- clients = self.clients- if exclude_ws is not None:- clients = {c for c in clients if c is not exclude_ws}- await self._broadcast_to(frame, clients)-- async def _download_file(self, url: str) -> bytes | None:- try:- async with aiohttp.ClientSession() as session:- async with session.get(url) as response:- if response.status == 200:- return await response.read()- else:- logger.warning("WebChannel 文件下载失败: %s, 状态码: %s", url, response.status)- return None- except Exception as e:- logger.warning("WebChannel 文件下载异常: %s, 错误: %s", url, e)- return None-- async def _process_files(self, params: dict[str, Any]) -> dict[str, Any]:- files = params.get("files")- if not files or not isinstance(files, list):- return params-- # 企业态:有 url 时不落 Gateway 本地 path,避免 Agent 先 read_file 失败再 fetch_webpage- strip_path_for_url = bool(os.getenv("AGENT_RUNTIME", "").strip())- downloaded_files = []- workspace_dir = str(get_agent_workspace_dir())-- for file_info in files:- if not isinstance(file_info, dict):- downloaded_files.append(file_info)- continue-- file_url = file_info.get("url") or file_info.get("uri") or ""- file_name = file_info.get("name") or file_info.get("filename") or "unknown_file"-- if file_url and strip_path_for_url:- updated = dict(file_info)- updated["url"] = file_url- updated.pop("path", None)- downloaded_files.append(updated)- continue-- if file_url:- file_content = await self._download_file(file_url)- if file_content:- try:- os.makedirs(workspace_dir, exist_ok=True)- file_path = os.path.join(workspace_dir, file_name)- with open(file_path, "wb") as f:- f.write(file_content)- file_info["path"] = file_path- except Exception as e:- logger.warning("WebChannel 文件保存失败: %s", e)-- downloaded_files.append(file_info)-- params["files"] = downloaded_files- return params-- # ── Channel 生命周期 ──────────────────────────────────+ return WebWsTransport.routing_key_user_id(connection_user_id, remote)- async def start(self) -> None:- """启动 WebSocket 服务并监听客户端连接."""- if self._running:- logger.warning("WebChannel 已在运行")- return- if not self.config.enabled:- logger.warning("WebChannel 未启用(enabled=False)")- return+ # ── WS transport shims (tests / legacy callers) ────────────────────- try:- from websockets.legacy.server import serve as ws_serve- except Exception: # pragma: no cover- import websockets-- ws_serve = websockets.serve+ @property+ def _ws_sessions(self) -> dict[int, set[str]]:+ return self.ws.ws_sessions- from jiuwenswarm.common.ws_limits import WEB_WS_MAX_MESSAGE_BYTES+ @property+ def _send_queues(self) -> dict[str, Any]:+ return self.ws.send_queues- self._server = await ws_serve(- self._connection_handler,- self.config.host,- self.config.port,- process_request=self._process_request,- ping_interval=20,- ping_timeout=60,- max_size=WEB_WS_MAX_MESSAGE_BYTES,- )- self._running = True- logger.info(- f"WebChannel 已启动: ws://{self.config.host}:{self.config.port}{self.config.path}"- )- await self._server.wait_closed()+ @property+ def _request_outbounds(self) -> dict[str, Any]:+ return self.delivery.request_outbounds- async def stop(self) -> None:- """停止 WebSocket 服务并清理连接."""- self._running = False+ @property+ def _session_request_outbounds(self) -> dict[str, set[str]]:+ return self.delivery.session_request_outbounds- all_clients = list(self.clients)- close_tasks = [client.close(code=1001, reason="server shutdown") for client in all_clients]- if close_tasks:- await asyncio.gather(*close_tasks, return_exceptions=True)- self._clients_by_key.clear()+ def _coalesce(self, first: Any, queue: Any) -> list[Any]:+ return self.ws.coalesce(first, queue)- if self._server is not None:- self._server.close()- await self._server.wait_closed()- self._server = None- # 兜底清理未走正常断连路径的 writer 协程(正常断连已由 unregister_ws 清理)- await self._shutdown_all_writers()- logger.info("WebChannel 已停止")+ async def _writer_loop(self, ws: Any, ws_id: str) -> None:+ await self.ws.writer_loop(ws, ws_id)- async def connect(self) -> None:- """兼容方法:调用 start."""- await self.start()-- async def disconnect(self) -> None:- """兼容方法:调用 stop."""- await self.stop()+ async def _handle_raw_message(self, ws: Any, raw: str, query: dict[str, list[str]]) -> None:+ await self.ws.handle_raw_message(ws, raw, query)- async def _process_request(self, *args: Any) -> Any:- """在握手阶段执行 Origin 校验,兼容 legacy/new websockets APIs。"""- path, request_headers = extract_handshake_request(args)- origin = get_header_value(request_headers, "Origin")- enable_origin_check = is_origin_check_enabled()- if not enable_origin_check:- logger.info(- "WebChannel 握手检查 path=%s origin=%s enable_origin_check=%s allowed=%s",- path,- origin,- enable_origin_check,- True,- )- return None-- allowed = is_allowed_browser_origin(origin)- logger.info(- "WebChannel 握手检查 path=%s origin=%s enable_origin_check=%s allowed=%s",- path,- origin,- enable_origin_check,- allowed,- )- if allowed:- return None+ async def register_ws(self, ws: Any, routing_key: Any) -> None:+ await self.ws.register_ws(ws, routing_key)- logger.warning(- "WebChannel 握手拒绝 path=%s origin=%s reason=origin_not_allowed",- path,- origin,- )- return forbidden_origin_response(args)+ async def unregister_ws(self, ws: Any) -> None:+ await self.ws.unregister_ws(ws)- @staticmethod- def _should_preserve_full_payload(event_name: str) -> bool:- return (- event_name in _WEB_FULL_PAYLOAD_EVENT_TYPES- or event_name.startswith("team.")- or event_name.startswith("harness.")- )+ # ── Public API (delegates) ─────────────────────────────────────────- @classmethod- def _build_event_payload(cls, msg: Message, event_name: str) -> dict[str, Any]:- """Build the Web event payload without dropping structured control fields."""- if isinstance(msg.payload, dict):- if cls._should_preserve_full_payload(event_name):- payload = {**msg.payload}- if "session_id" not in payload and msg.session_id:- payload["session_id"] = msg.session_id- if event_name.startswith("chat.") and "request_id" not in payload and msg.id:- payload["request_id"] = msg.id- return payload-- content = str(msg.payload.get("content", "") or "")- if not content and not getattr(msg, "ok", True) and msg.payload.get("error"):- content = str(msg.payload.get("error", ""))- payload = {- "session_id": msg.session_id,- "content": content,- }- for _key in ("role", "member_name", "member_action", "source_channel", "user_id", "display_name"):- _val = msg.payload.get(_key)- if _val is not None:- payload[_key] = _val- if event_name == "chat.final":- cron_extra = msg.payload.get("cron")- if isinstance(cron_extra, dict):- payload["cron"] = cron_extra- source = msg.payload.get("source")- if source:- payload["source"] = source- ptype = msg.payload.get("proactive_type")- if ptype:- payload["proactive_type"] = ptype- if source == "proactive_recommendation":- logger.info(- "[WebChannel] proactive push frame: source=%s proactive_type=%s "- "content_len=%d payload_keys=%s",- source, ptype, len(str(payload.get("content", ""))), list(payload.keys()),- )- return payload-- content = str((msg.params or {}).get("content", "") or "")- return {- "session_id": msg.session_id,- "content": content,- }+ @property+ def clients(self) -> set[Any]:+ return self.ws.clients- async def send(- self,- msg: Message,- *,- routing_target: RoutingTarget | None = None,- ) -> None:- """向客户端发送消息。-- V2: 当 routing_target 非空时,按其 routing_keys 精确路由(_clients_by_key)。- 否则回退到全量广播(向后兼容)。- """- _pl = getattr(msg, "payload", None) or {}- _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""- _has_fanout = bool((getattr(msg, "metadata", None) or {}).get("fan_out_targets"))- logger.debug(- "[WebChannel] send() called: id=%s event_type=%s payload_et=%s has_fanout=%s"- " has_routing_target=%s client_count=%s",- getattr(msg, "id", ""), getattr(msg, "event_type", None), _et,- _has_fanout, routing_target is not None, len(self.clients),- )- # ── 心跳 relay:临时 session_id(heartbeat_{ts}_{suffix})不匹配任何前端连接,- # 按常规 session_id 路由会被当作"无连接"丢弃。心跳状态是全局的(非会话级),- # 前端 setHeartbeatStatus 也是全局 store,因此直接广播给所有 web 客户端。- # 与 wechat 等 IM 渠道在 send() 中对 HEARTBEAT_RELAY 的专属分支对齐。- if msg.event_type == EventType.HEARTBEAT_RELAY:- frame = self._serialize_frame(msg, None) # 返回 dict,由 writer 统一序列化- clients = self.clients- for w in clients:- self._enqueue_send(w, frame)- logger.debug(- "[WebChannel] heartbeat.relay broadcast to %d client(s) id=%s",- len(clients), getattr(msg, "id", ""),- )- return+ @property+ def web_http_port(self) -> int | None:+ return self.http.port- # ── 定时任务推 web:原设计绑定 job.session_id,但关闭 tab/换设备后旧会话再无连接,- # 按 session_id 路由会被丢弃。cron 推送(占位 + 结果)带 payload.cron 标记,普通对话- # chat.final 不带,以此为识别条件广播给所有 web 客户端。前端 _push_to_targets 已对 web- # 置空 session_id,shouldHandleSessionEvent 放行,消息进当前活跃会话流(含 placeholder 替换)。- if (- msg.event_type == EventType.CHAT_FINAL- and isinstance(msg.payload, dict)- and isinstance(msg.payload.get("cron"), dict)- ):- frame = self._serialize_frame(msg, None) # 返回 dict,由 writer 统一序列化- clients = self.clients- for w in clients:- self._enqueue_send(w, frame)- logger.debug(- "[WebChannel] cron push broadcast to %d client(s) id=%s run_id=%s",- len(clients), getattr(msg, "id", ""),- (msg.payload.get("cron") or {}).get("run_id", ""),- )- return+ def register_method(self, method: str, handler: MethodHandler) -> None:+ self.rpc.register_method(method, handler)- # ── 主动推荐系统通知推 web:与 cron 推送同理——后端主动推、无前端 session_id 绑定,- # 按 session_id 路由会被当"无 session"丢弃(旧路径 580 行 if not msg.session_id 兜底丢弃)。- # proactive notification("今日已达上限"等系统提醒)带 payload.source ==- # "proactive_notification" 标记,据此广播给所有 web 客户端。前端 shouldHandleSessionEvent- # 对无 session_id 的 payload 放行,作为普通 assistant 消息渲染。- if (- msg.event_type == EventType.CHAT_FINAL- and isinstance(msg.payload, dict)- and msg.payload.get("source") == "proactive_notification"- ):- frame = self._serialize_frame(msg, None) # 返回 dict,由 writer 统一序列化- clients = self.clients- for w in clients:- self._enqueue_send(w, frame)- logger.debug(- "[WebChannel] proactive_notification broadcast to %d client(s) id=%s",- len(clients), getattr(msg, "id", ""),- )- return+ def on_connect(self, callback: Any) -> None:+ self.rpc.on_connect(callback)- if msg.type == "res":- if isinstance(msg.payload, dict):- res_payload = {**msg.payload}- elif msg.payload is None:- res_payload = {}- else:- res_payload = {"content": str(msg.payload)}-- frame: dict[str, Any] = {- "type": "res",- "id": msg.id,- "ok": bool(msg.ok),- "payload": res_payload,- }- if not msg.ok:- # Prefer explicit error; fall back to message (e.g. command.goal- # unary failures put the human-readable text in payload.message).- error_text = res_payload.get("error") or res_payload.get("message")- if isinstance(error_text, str) and error_text:- frame["error"] = error_text- code_text = res_payload.get("code")- if isinstance(code_text, str) and code_text:- frame["code"] = code_text-- ws_set: set[Any] = set()- metadata = msg.metadata if isinstance(msg.metadata, dict) else {}- request_ws_id = str(metadata.get("ws_id") or "").strip()- if request_ws_id:- ws = self._ws_by_id.get(request_ws_id)- if ws is not None and not getattr(ws, "closed", False):- ws_set.add(ws)-- if not ws_set and routing_target is not None:- delivery = routing_target.delivery- if delivery is not None:- ws_id = getattr(delivery, "ws_id", "")- if ws_id:- ws = self._ws_by_id.get(ws_id)- if ws is not None and not getattr(ws, "closed", False):- ws_set.add(ws)- if not ws_set:- for rk in routing_target.routing_keys:- ws_list = self._clients_by_key.get(rk) or []- for w in ws_list:- if not getattr(w, "closed", False):- ws_set.add(w)-- if not ws_set and msg.session_id:- for rk, ws_list in self._clients_by_key.items():- if rk.session_id == msg.session_id:- for w in ws_list:- if not getattr(w, "closed", False):- ws_set.add(w)-- if not ws_set:- logger.debug(- "[WebChannel] response route miss: ws_id=%s session_id=%s id=%s",- request_ws_id,- msg.session_id,- getattr(msg, "id", ""),- )- return- await self._broadcast_to(frame, ws_set)- return+ def on_disconnect(self, callback: Any) -> None:+ self.rpc.on_disconnect(callback)- # ── V2 精确路由 ──- if routing_target is not None:- routing_keys = routing_target.routing_keys- member_names = list(routing_target.member_names)-- # ── 优先:按 delivery.ws_id 物理寻址 ──- ws_set: set[Any] = set()- delivery = routing_target.delivery- if delivery is not None:- ws_id = getattr(delivery, "ws_id", "")- if ws_id:- ws = self._ws_by_id.get(ws_id)- if ws is not None and not getattr(ws, "closed", False):- ws_set.add(ws)-- # ── 兜底:按 routing_keys 5 维逻辑查 _clients_by_key ──- if not ws_set and routing_keys:- for rk in routing_keys:- ws_list = self._clients_by_key.get(rk) or []- for w in ws_list:- if not getattr(w, "closed", False):- ws_set.add(w)- if ws_set:- frame_data = self._serialize_frame(msg, routing_target, member_names=member_names)- for w in ws_set:- self._enqueue_send(w, frame_data)- return- # V2 精确路由未命中 —— 回退到 session_id 路由- logger.debug(- "[WebChannel] V2 routing miss: looked up %d routing_keys + ws_id=%s,"- " ws_set empty — falling back to session_id=%s",- len(routing_keys), getattr(delivery, "ws_id", "") if delivery else "",- getattr(msg, "session_id", ""),- )-- # ── 旧路径:优先按请求 metadata.ws_id 物理寻址,再按 session_id 精确路由 ──- # 普通 stream event(chat.delta/final/usage_summary 等)由 ChannelManager- # 调 channel.send(msg),不会携带 RoutingTarget;但原始 Web 请求注入的- # metadata.ws_id 会经 _chunk_to_message 保留下来。先用它收窄到发起请求的- # 物理连接,避免同一个 session 桶里的陈旧 ws 一起收到迟到事件。- ws_set: set[Any] = set()- metadata = msg.metadata if isinstance(msg.metadata, dict) else {}- request_ws_id = str(metadata.get("ws_id") or "").strip()- if request_ws_id:- ws = self._ws_by_id.get(request_ws_id)- if ws is not None and not getattr(ws, "closed", False):- ws_set.add(ws)-- if not ws_set and not msg.session_id:- logger.warning(- "[WebChannel] msg has no session_id, cannot route -- "- "dropping msg id=%s to avoid cross-session broadcast",- getattr(msg, "id", ""),- )- return- if not ws_set:- for rk, ws_list in self._clients_by_key.items():- if rk.session_id == msg.session_id:- for w in ws_list:- if not getattr(w, "closed", False):- ws_set.add(w)- if not ws_set:- logger.debug(- "[WebChannel] session_id=%s has no connected ws, dropping msg id=%s ws_id=%s",- msg.session_id, getattr(msg, "id", ""), request_ws_id,- )- return- all_clients = ws_set-- # 确定事件名称- event_name = "chat.final"- if msg.event_type is not None:- event_name = msg.event_type.value- elif isinstance(msg.payload, dict):- payload_event_type = msg.payload.get("event_type")- if isinstance(payload_event_type, str) and payload_event_type.strip():- event_name = payload_event_type.strip()-- payload = self._build_event_payload(msg, event_name)-- # ── V2: 诊断日志 ──- if routing_target is not None:- logger.info(- "[WebChannel] frame: id=%s event=%s intent=%s",- getattr(msg, "id", ""), event_name, routing_target.intent,- )- if getattr(msg, "agent_ref", None):- payload["agent_ref"] = msg.agent_ref if isinstance(msg.agent_ref, dict) else {- "mode": getattr(msg.agent_ref, "mode", ""),- "id": getattr(msg.agent_ref, "id", ""),- }-- frame_data: dict[str, Any] = {- "type": "event",- "event": event_name,- "payload": payload,- }- await self._broadcast_to(frame_data, all_clients)-- # 维护 session busy 状态(供 /ws/git 写操作查询)- if event_name == "chat.processing_status" and isinstance(payload, dict):- sid = payload.get("session_id") or msg.session_id- if sid:- self._session_busy[sid] = bool(payload.get("is_processing", False))-- # interrupt_result 根据 intent 决定 is_processing 状态- if event_name == "chat.interrupt_result":- intent = payload.get("intent", "cancel") if isinstance(payload, dict) else "cancel"- is_processing = intent in ("pause", "supplement", "resume")- # 同步更新 busy 映射- if msg.session_id:- self._session_busy[msg.session_id] = is_processing- await self._broadcast_to({- "type": "event",- "event": "chat.processing_status",- "payload": {"session_id": msg.session_id, "is_processing": is_processing},- }, all_clients)+ def on_message(self, callback: Callable[[Message], None]) -> None:+ self.rpc.on_message(callback)- def is_session_busy(self, session_id: str) -> bool:- """查询 session 是否正在执行(agent 处理中)。+ def wrap_message_callback(self, wrapper: Any) -> None:+ self.rpc.wrap_message_callback(wrapper)- 基于 ``chat.processing_status`` 事件维护的映射。- 未跟踪的 session 默认返回 False(不忙碌)。+ async def send_response(self, ws: Any, req_id: str, **kwargs: Any) -> None:+ await self.ws.send_response(ws, req_id, **kwargs)- 供 /ws/git 写操作(如 ``project.git.discard_turn_changes``)在执行前- 校验会话非忙碌,避免与正在进行的 agent 文件写入冲突。- """- return self._session_busy.get(session_id, False)+ async def send_event(+ self,+ ws: Any,+ event: str,+ payload: dict[str, Any],+ *,+ seq: int | None = None,+ stream_id: str | None = None,+ ) -> None:+ await self.ws.send_event(ws, event, payload, seq=seq, stream_id=stream_id)- def get_metadata(self) -> ChannelMetadata:- """获取 Channel 元数据."""- return ChannelMetadata(- channel_id=self.channel_id,- source="websocket",- extra={"host": self.config.host, "port": self.config.port, "path": self.config.path},- )+ def register_request_outbound(self, outbound: Any) -> str:+ return self.delivery.register(outbound)- # ── 内部实现 ──────────────────────────────────────────-- 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)- request_path = parsed.path or raw_path- query = parse_qs(parsed.query)- remote = getattr(ws, "remote_address", None)- _flat_query = {k: (v[0] if v else "") for k, v in query.items()}-- # ── Path 分发(设计文档 §5.3.7) ──- # /ws/git → GitDiffWebSocketHandler- # /ws → 现有主 RPC- # 其他 → 1008 close- if request_path == "/ws/git":- await self._handle_git_ws_connection(ws, _flat_query, remote)- return+ async def unregister_request_outbound(self, outbound: Any) -> None:+ await self.delivery.unregister(outbound)- if request_path != self.config.path:- await ws.close(code=1008, reason=f"unsupported path: {request_path}")- return+ async def clear_request_outbounds(self) -> None:+ await self.delivery.clear()- connection_user_id, _user_id = self._resolve_ws_identity(- ws, _flat_query, remote, route_type="ws",- )- uid_marker = "" if connection_user_id else " uid_empty=yes"- logger.info(- "WebChannel 新连接: remote=%s query=%s user_id=%r%s",- remote,- query,- connection_user_id,- uid_marker,- )+ async def broadcast_event(self, *args: Any, **kwargs: Any) -> None:+ await self.ws.broadcast_event(*args, **kwargs)- # ── V2: 从 query 提取身份字段,构造默认 RoutingKey ──- # session_id 和 agent_id 可能在首条消息中更新- _app_id = _flat_query.get("app_id", "default")- _mode = _flat_query.get("mode", "agent")- _agent_id = _flat_query.get("agent_id", "default")- _initial_sid = _flat_query.get("session_id", self._make_session_id())- _initial_rk = RoutingKey(- user_id=_user_id,- channel_id=self.channel_id,- app_id=_app_id,- agent_ref=AgentRef(mode=_mode, id=_agent_id),- session_id=_initial_sid,- )- await self.register_ws(ws, _initial_rk)- # 将握手阶段占位 session_id 挂到 ws 上,供 _on_connect 等连接级钩子复用,- # 确保 connection.ack 与 ws 在 _clients_by_key 中的注册 key 一致,- # 否则 send() 按 session_id 反查会落空导致 ACK 丢弃。- # 注:此 sid 仅为传输层占位,首条 chat.send 携带真实 session_id 时会 re-register 覆盖。- setattr(ws, "_jiuwen_initial_sid", _initial_sid)-- # 触发连接钩子(如发送 connection.ack)- for hook in self._connect_hooks:- try:- result = hook(ws)- if inspect.isawaitable(result):- await result- except Exception as e: # pragma: no cover- logger.warning(- "WebChannel on_connect hook error: %s",- format_ws_diagnostics(- {"remote": remote, "path": request_path},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )-- try:- async for raw in ws:- await self._handle_raw_message(ws, raw, query)- except WebSocketConnectionClosed as e: # pragma: no cover - 连接生命周期容错- logger.info(- "WebChannel 连接关闭: %s",- format_ws_diagnostics(- {"remote": remote, "path": request_path},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )- except Exception as e: # pragma: no cover - 连接生命周期容错- logger.warning(- "WebChannel 连接异常: %s",- format_ws_diagnostics(- {"remote": remote, "path": request_path},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )- finally:- await self.unregister_ws(ws)-- logger.info(- "WebChannel 连接清理完成: %s",- format_ws_diagnostics(- {"remote": remote, "path": request_path, "clients": len(self._clients_by_key)},- describe_ws_peer(ws),- ),- )- # 取出该 ws 关联的 session_ids,清理映射- ws_id = id(ws)- disconnected_sessions = self._ws_sessions.pop(ws_id, set())- logger.info(- "WebChannel 连接关闭: remote=%s sessions=%s",- remote,- disconnected_sessions or "none",- )- # 注意:此处不清理 _session_busy。ws 断开不等价于 agent 已停止——- # 用户关 tab / 刷新 / 网络断开期间,后端 run 仍可能在写文件。若按- # ws ownership 清掉 busy,新的 discard_turn_changes 会通过 busy 校验,- # 与仍在运行的 agent 文件写入并发,造成数据损坏。stale busy 的治理- # 应基于 TTL / 心跳 / agentserver run 状态源,而非 ws 连接状态。- # 触发断连钩子,传入 session_ids(签名: (ws, session_ids))- for hook in self._disconnect_hooks:- try:- result = hook(ws, disconnected_sessions)- if inspect.isawaitable(result):- await result- except Exception as e: # pragma: no cover- logger.warning("WebChannel on_disconnect hook error: %s", e)-- async def _handle_git_ws_connection(+ async def send(self,- ws: Any,- flat_query: dict[str, str],- remote: Any,+ msg: Message,+ *,+ routing_target: RoutingTarget | None = None,) -> None:- """处理 /ws/git 路由的连接(设计文档 §5.3.7)。-- 构建 ``AgentRef(mode="git", id="diff")`` 哨兵 RoutingKey,- 注册后委托 ``GitDiffWebSocketHandler.handle_connection`` 处理消息循环。- 断连 ``finally`` 先后调 ``unregister_ws(ws)`` 和- ``git_watcher_registry.cleanup_ws(ws)``,避免 watcher 仍继续轮询推送。- """- registry = getattr(self, "git_watcher_registry", None)- if registry is None:- await ws.close(code=1011, reason="git watcher registry not available")- return-- from jiuwenswarm.gateway.channel_manager.web.git_ws_handler import (- GitDiffWebSocketHandler,- )- handler = GitDiffWebSocketHandler(self, registry)+ await self.ws.send(msg, routing_target=routing_target)- connection_user_id, _user_id = self._resolve_ws_identity(- ws, flat_query, remote, route_type="git",- )- _app_id = flat_query.get("app_id", "default")- # session_id 为传输层占位,不是聊天会话(设计文档 §5.3.7)- _session_id = flat_query.get("session_id") or f"gitws_{uuid.uuid4().hex[:12]}"- _rk = RoutingKey(- user_id=_user_id,- channel_id=self.channel_id,- app_id=_app_id,- agent_ref=AgentRef(mode="git", id="diff"),- session_id=_session_id,- )- await self.register_ws(ws, _rk)-- logger.info(- "[WebChannel] /ws/git 新连接: remote=%s user_id=%r session_id=%s",- remote,- connection_user_id,- _session_id,- )+ def is_session_busy(self, session_id: str) -> bool:+ return self.ws.is_session_busy(session_id)- try:- await handler.handle_connection(ws, flat_query)- except WebSocketConnectionClosed as e:- logger.info(- "[WebChannel] /ws/git 连接关闭: %s",- format_ws_diagnostics(- {"remote": remote, "path": "/ws/git"},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )- except Exception as e:- logger.warning(- "[WebChannel] /ws/git 连接异常: %s",- format_ws_diagnostics(- {"remote": remote, "path": "/ws/git"},- describe_ws_peer(ws),- describe_ws_exception(e),- ),- )- finally:- await self.unregister_ws(ws)- try:- registry.cleanup_ws(ws)- except Exception as exc: # noqa: BLE001- logger.debug(- "[WebChannel] /ws/git cleanup_ws failed: %s", exc,- )- logger.info(- "[WebChannel] /ws/git 连接清理完成: remote=%s",- remote,- )+ def get_metadata(self) -> ChannelMetadata:+ return self.ws.get_metadata()- async def _handle_raw_message(self, ws: Any, raw: str, query: dict[str, list[str]]) -> None:- try:- data = json.loads(raw)- except json.JSONDecodeError:- await self.send_response(ws, "", ok=False, error="invalid json", code="BAD_REQUEST")- return+ async def start_http(self, *, host: str | None = None, port: int | None = None) -> bool:+ return await self.http.start(host=host, port=port)- if not isinstance(data, dict):- await self.send_response(ws, "", ok=False, error="invalid request", code="BAD_REQUEST")- return+ async def stop_http(self) -> None:+ await self.http.stop()- req_type = data.get("type")- req_id = data.get("id")- method = data.get("method")- params = data.get("params")-- if req_type != "req" or not isinstance(req_id, str) or not isinstance(method, str):- await self.send_response(- ws,- req_id if isinstance(req_id, str) else "",- ok=False,- error="invalid request",- code="BAD_REQUEST",- )+ async def start(self) -> None:+ """Start WebSocket and Gateway Web HTTP; block until WS server closes."""+ if self._running:return- if not isinstance(params, dict):- params = {}-- # ── V2: session_id 解析 ──- # 请求自带 session_id(如 chat.send)→ 用它更新 ws 路由注册。- # 请求未带 session_id(如 memory.compute 心跳、updater.check、config.get- # 等 ws 层 keepalive / 拉取请求)→ 这类请求与 session 无关,- # 仅合成一个临时 id 供后续 Message 构造使用,但【不】参与 register_ws,- # 保留 ws 上一次的真实 RoutingKey,避免把 ws 从其所属 team session 摘除。- _explicit_session_id = params.get("session_id")- has_explicit_session = (- isinstance(_explicit_session_id, str) and bool(_explicit_session_id)- )- session_id = _explicit_session_id if has_explicit_session else self._make_session_id()-- # 追踪 ws → 真实 session_id,用于断连清理/日志。- # 与 register_ws 一致:仅显式 session 入集;临时 id 只供 Message 构造,避免膨胀。- if has_explicit_session:- ws_id = id(ws)- sessions = self._ws_sessions.get(ws_id)- if sessions is None:- sessions = set()- self._ws_sessions[ws_id] = sessions- sessions.add(session_id)-- params = await self._process_files(params)-- # ── V2: 用实际的 session_id / mode / agent_id 更新 ws 注册 ──- _flat_query = {k: (v[0] if v else "") for k, v in query.items()}- _mode = params.get("mode", "agent")- _agent_id = params.get("agent_id", "default")- _app_id = _flat_query.get("app_id", "default")- req_user_id = self._connection_user_id(ws)- if has_explicit_session:- _rk = RoutingKey(- user_id=self._routing_key_user_id(req_user_id, getattr(ws, "remote_address", None)),- channel_id=self.channel_id,- app_id=_app_id,- agent_ref=AgentRef(mode=_mode, id=_agent_id),- session_id=session_id,- )- await self.register_ws(ws, _rk)- # else: ws 层心跳 / 拉取请求,不更新路由注册,沿用 ws 已有的 RoutingKey。-- # Preserve client top-level is_stream (e.g. command.goal set/resume).- # chat.send / history.get still become stream in _normalize_gateway_message- # even when the client omits this field.- user_message = Message(- id=req_id,- type="req",- channel_id=self.channel_id,- session_id=session_id,- params=params,- timestamp=time.time(),- ok=True,- req_method=self._parse_req_method(method),- mode=self._parse_mode(params.get("mode")),- is_stream=bool(data.get("is_stream", False)),- app_id=_app_id,- agent_ref={"mode": _mode, "id": _agent_id},- user_id=req_user_id,- metadata={- "query": query,- "method": method,- # V2: 注入 ws_id 供 MessageHandler 构造 WebDeliveryTarget(ws_id=真值)。- "ws_id": getattr(ws, "_jiuwen_ws_id", ""),- "user_id": req_user_id,- },+ self._running = True+ self.rpc.maybe_start_history_capture()+ await self.ws.start_ws_server()+ await self.http.start()+ logger_info = (+ f"WebChannel 已启动: ws://{self.config.host}:{self.config.ws_port}{self.config.path}")+ if self.http.port:+ logger_info += f" http://{self.config.host}:{self.http.port}"+ import logging+ logging.getLogger(__name__).info(logger_info)+ await self.ws.wait_closed()- # 发布到 route 或回调- handler = self._method_handlers.get(method)- handler_already_called = False- if method in _HANDLER_BEFORE_CALLBACK_METHODS and handler is not None:- handler_already_called = await self._invoke_method_handler(- _MethodHandlerInvocation(- ws, method, req_id, params, session_id, handler,- ),- )- if not handler_already_called:- return-- handled_by_callback = False- if self._on_message_cb is not None:- result = self._on_message_cb(user_message)- if inspect.isawaitable(result):- result = await result- handled_by_callback = bool(result)- else:- await self.bus.publish_user_messages(user_message)-- if handled_by_callback:- return- if handler_already_called:- return-- # 路由到已注册的方法处理器- if handler is not None:- await self._invoke_method_handler(- _MethodHandlerInvocation(- ws, method, req_id, params, session_id, handler,- ),- )- else:- await self.send_response(- ws, req_id, ok=False,- error=f"unknown method: {method}", code="METHOD_NOT_FOUND",- )-- async def _broadcast_to(self, frame: dict[str, Any], clients: set[Any]) -> None:- """向指定 clients 集合广播帧(走 per-ws writer,非阻塞入队).-- 入队 dict,由 writer 统一序列化一次,避免此处预 dumps。- """- if not clients:- return- for client in clients:- self._enqueue_send(client, frame)-- # ── BaseWsChannel 抽象方法 ──-- def _serialize_frame(- self,- msg: Any,- routing_target: RoutingTarget | None = None,- *,- member_names: list[str] | None = None,- ) -> dict[str, Any]:- """将 Message 转为 Web 前端帧 dict(由 writer 统一序列化)."""- event_name = "chat.final"- if getattr(msg, "event_type", None) is not None:- event_name = msg.event_type.value- elif isinstance(getattr(msg, "payload", None), dict):- et = msg.payload.get("event_type")- if isinstance(et, str) and et.strip():- event_name = et.strip()-- payload: dict[str, Any] = {}- if isinstance(msg.payload, dict):- payload = {**msg.payload}- if "session_id" not in payload and getattr(msg, "session_id", None):- payload["session_id"] = msg.session_id- elif getattr(msg, "payload", None) is not None:- payload = {"session_id": getattr(msg, "session_id", None), "content": str(msg.payload)}- else:- payload = {"session_id": getattr(msg, "session_id", None), "content": ""}-- agent_ref = getattr(msg, "agent_ref", None)- if agent_ref:- payload["agent_ref"] = agent_ref if isinstance(agent_ref, dict) else {- "mode": getattr(agent_ref, "mode", ""),- "id": getattr(agent_ref, "id", ""),- }-- frame: dict[str, Any] = {- "type": "event",- "event": event_name,- "payload": payload,- }- return frame-- @staticmethod- def _parse_req_method(method: str) -> ReqMethod | None:- for item in ReqMethod:- if item.value == method:- return item- return None+ async def stop(self) -> None:+ self._running = False+ await self.http.stop()+ self.rpc.shutdown()+ await self.ws.stop_ws_server()- @staticmethod- def _parse_mode(raw_mode: Any) -> Mode:- return Mode.from_raw(raw_mode, default=Mode.AGENT)+ async def connect(self) -> None:+ await self.start()- @staticmethod- def _make_session_id() -> str:- # 与前端 generateSessionId 保持一致:毫秒时间戳(16进制) + 6位随机16进制- ts = format(int(time.time() * 1000), "x")- suffix = secrets.token_hex(3)- return f"sess_{ts}_{suffix}"+ async def disconnect(self) -> None:+ await self.stop()diff --git a/jiuwenswarm/gateway/channel_manager/web/web_delivery_registry.py b/jiuwenswarm/gateway/channel_manager/web/web_delivery_registry.pynew file mode 100644index 0000000000..ffb43d40fd--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_delivery_registry.py@@ -0,0 +1,122 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""HTTP request-scoped outbound registry (not WebSocket connection table)."""++from __future__ import annotations++import inspect+import logging+import uuid+from typing import Any++logger = logging.getLogger(__name__)+++class WebDeliveryRegistry:+ """Tracks ``HttpJsonOutbound`` / ``HttpSseOutbound`` for routing Agent replies."""++ def __init__(self) -> None:+ self._request_outbounds: dict[str, Any] = {}+ self._session_request_outbounds: dict[str, set[str]] = {}++ @property+ def request_outbounds(self) -> dict[str, Any]:+ return self._request_outbounds++ @property+ def session_request_outbounds(self) -> dict[str, set[str]]:+ return self._session_request_outbounds++ def register(self, outbound: Any) -> str:+ """Register a request-scoped HTTP Outbound (no ``register_ws``)."""+ oid = str(+ getattr(outbound, "outbound_id", None)+ or getattr(outbound, "_jiuwen_ws_id", None)+ or uuid.uuid4().hex+ ).strip()+ setattr(outbound, "outbound_id", oid)+ setattr(outbound, "_jiuwen_ws_id", oid)+ self._request_outbounds[oid] = outbound+ sid = str(getattr(outbound, "session_id", "") or "").strip()+ if sid:+ bucket = self._session_request_outbounds.setdefault(sid, set())+ bucket.add(oid)+ return oid++ async def unregister(self, outbound: Any) -> None:+ """Remove request Outbound from routing tables and close it."""+ oid = str(+ getattr(outbound, "outbound_id", None)+ or getattr(outbound, "_jiuwen_ws_id", None)+ or "",+ ).strip()+ if oid:+ self._request_outbounds.pop(oid, None)+ sid = str(getattr(outbound, "session_id", "") or "").strip()+ if sid and oid:+ bucket = self._session_request_outbounds.get(sid)+ if bucket is not None:+ bucket.discard(oid)+ if not bucket:+ self._session_request_outbounds.pop(sid, None)+ close = getattr(outbound, "close", None)+ if callable(close):+ try:+ result = close()+ if inspect.isawaitable(result):+ await result+ except Exception: # noqa: BLE001+ logger.debug("[WebDelivery] outbound close failed", exc_info=True)++ async def clear(self) -> None:+ """Close and drop all HTTP request Outbounds (channel stop / shutdown)."""+ outs = list(self._request_outbounds.values())+ self._request_outbounds.clear()+ self._session_request_outbounds.clear()+ for outbound in outs:+ close = getattr(outbound, "close", None)+ if not callable(close):+ continue+ try:+ result = close()+ if inspect.isawaitable(result):+ await result+ except Exception: # noqa: BLE001+ logger.debug("[WebDelivery] outbound clear close failed", exc_info=True)++ def lookup(self, outbound_id: str) -> Any | None:+ """Return a live HTTP outbound by id, or None."""+ oid = str(outbound_id or "").strip()+ if not oid:+ return None+ out = self._request_outbounds.get(oid)+ if out is None:+ return None+ if getattr(out, "closed", False):+ self._prune_outbound(oid, out)+ return None+ return out++ def _prune_outbound(self, oid: str, outbound: Any) -> None:+ self._request_outbounds.pop(oid, None)+ sid = str(getattr(outbound, "session_id", "") or "").strip()+ if not sid:+ return+ bucket = self._session_request_outbounds.get(sid)+ if bucket is None:+ return+ bucket.discard(oid)+ if not bucket:+ self._session_request_outbounds.pop(sid, None)++ def peers_for_session(self, session_id: str) -> set[Any]:+ """HTTP outbounds bound to ``session_id`` (WS clients added by transport)."""+ peers: set[Any] = set()+ sid = str(session_id or "").strip()+ if not sid:+ return peers+ for oid in list(self._session_request_outbounds.get(sid, ())):+ out = self._request_outbounds.get(oid)+ if out is not None and not getattr(out, "closed", False):+ peers.add(out)+ return peersdiff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.pynew file mode 100644index 0000000000..eba7c1ffcb--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py@@ -0,0 +1,784 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Gateway Web HTTP + SSE — FastAPI routes on /api/v1 (core + mapped table)."""++from __future__ import annotations++import base64+import json+import logging+import uuid+from typing import Any, AsyncIterator++from fastapi import Body, FastAPI, File, Query, Request, Response, UploadFile+from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse+from pydantic import BaseModel, ConfigDict, Field++from jiuwenswarm.gateway.channel_manager.web.web_http_dispatch import dispatch_http_request+from jiuwenswarm.gateway.channel_manager.web.web_http_routes import (+ MAPPED_ROUTES,+ WebHttpMappedRoute,+ catalog_entries,+)+from jiuwenswarm.gateway.channel_manager.web.web_http_file_compat import (+ catalog_file_compat_entries,+ register_file_compat_routes,+)+from jiuwenswarm.gateway.channel_manager.web.web_http_server import (+ resolve_web_http_history_timeout,+ resolve_web_http_sse_idle_timeout,+ resolve_web_http_sse_keepalive,+ resolve_web_http_sse_timeout,+ resolve_web_http_unary_timeout,+)+from jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat import (+ catalog_sessions_compat_entries,+ register_sessions_compat_routes,+)++_HEADER_TO_PARAM = {+ "x-user-id": "user_id",+ "x-group-id": "group_id",+ "x-bot-id": "bot_id",+ "x-session-id": "session_id",+}++logger = logging.getLogger(__name__)+++def _request_client_host(request: Request) -> str | None:+ client = request.client+ if client is None:+ return None+ host = str(getattr(client, "host", "") or "").strip()+ return host or None++_STREAM_RPC_METHODS = frozenset({"chat.send", "history.get"})++_OPENAPI_TAGS = [+ {"name": "health", "description": "探活与 Agent 连接状态"},+ {"name": "sessions", "description": "会话 CRUD / 历史(RPC session.* / history.get)"},+ {"name": "chat", "description": "发消息 SSE / 中断 / 回答(RPC chat.*)"},+ {"name": "Web HTTP catalog", "description": "HTTP → Web RPC method 对照表(可追溯)"},+ {"name": "config", "description": "RPC config.get(企业只读)"},+ {"name": "models", "description": "RPC models.list(企业聊天下拉只读)"},+ {"name": "locale", "description": "RPC locale.get_conf / set_conf"},+ {"name": "cron", "description": "RPC cron.job.*(企业 CronPanel)"},+ {"name": "permissions", "description": "RPC permissions.*(浏览器设置;非 Claw Manager)"},+ {"name": "skills", "description": "RPC skills.*(个人目录 + 企业租户)"},+ {"name": "harness", "description": "RPC harness.*(本机包;进度事件仍走 SSE/WS)"},+ {+ "name": "enterprise history",+ "description": "兼容 Web Pod:GET /api/sessions* → ChatHistoryStore(非 /api/v1 session.list)",+ },+ {+ "name": "file / share HTTP",+ "description": "原 app_web /file-api/*、/share-api/*(静态 Web 已剥离)",+ },+]+++class _ExtraAllow(BaseModel):+ """OpenAPI: extra keys allowed, but do not render dummy additionalProp1."""++ model_config = ConfigDict(extra="allow")+++def _session_create_schema(schema: dict[str, Any]) -> None:+ schema["example"] = {}+ schema["additionalProperties"] = True+ for prop in schema.get("properties", {}).values():+ if isinstance(prop, dict):+ prop.pop("examples", None)+ prop["default"] = None+++class SessionCreateBody(_ExtraAllow):+ """All fields optional. Swagger Try it out should send ``{}``."""++ model_config = ConfigDict(+ extra="allow",+ json_schema_extra=_session_create_schema,+ )+ mode: str | None = Field(+ default=None,+ description="可选。agent / code.normal / …;省略则用通道默认",+ )+ project_id: str | None = Field(default=None, description="可选。省略则绑定默认项目")+ project_dir: str | None = Field(default=None, description="可选")+ work_mode: str | None = Field(default=None, description="可选。work / code")+ create_token: str | None = Field(+ default=None,+ description="可选。幂等令牌;省略时 Gateway 自动生成",+ )+++class SessionPatchBody(_ExtraAllow):+ title: str | None = None+ pinned: bool | None = None+++class ChatSendBody(_ExtraAllow):+ model_config = ConfigDict(+ extra="allow",+ json_schema_extra={+ "example": {+ "session_id": "web_xxx",+ "query": "ping",+ "mode": "agent",+ "enable_streaming": True,+ }+ },+ )+ session_id: str = Field(..., description="已有会话 id(先 POST /sessions)")+ query: str = Field(..., description="用户消息,对齐 RPC chat.send")+ mode: str | None = "agent"+ enable_streaming: bool = True+++# Backward-compatible OpenAPI alias (deprecated path name).+ChatCompletionsBody = ChatSendBody+++class ChatActionBody(_ExtraAllow):+ pass+++def _body_dict(body: BaseModel | dict[str, Any] | None) -> dict[str, Any]:+ if body is None:+ return {}+ if isinstance(body, dict):+ return dict(body)+ return body.model_dump(exclude_none=True)+++def _history_params(session_id: str, page_idx: int | None) -> dict[str, Any]:+ return {"session_id": session_id, "page_idx": int(page_idx) if page_idx is not None else 1}+++def _web_http_metadata(method: str) -> dict[str, Any]:+ return {"rpc_method": method, "transport": "web-http"}+++def _response_headers(request_id: str, method: str = "") -> dict[str, str]:+ headers = {"X-Request-Id": request_id}+ if method:+ headers["X-Web-RPC-Method"] = method+ return headers+++def _envelope_from_res(+ frame: dict[str, Any],+ request_id: str,+ *,+ rpc_method: str = "",+) -> tuple[dict[str, Any], int]:+ ok = bool(frame.get("ok", False))+ body: dict[str, Any] = {"request_id": request_id, "ok": ok}+ if ok:+ body["data"] = frame.get("payload") if frame.get("payload") is not None else {}+ body["metadata"] = _web_http_metadata(rpc_method) if rpc_method else {}+ return body, 200+ err_code = str(frame.get("code") or "INTERNAL_ERROR")+ body["error"] = {+ "code": err_code,+ "message": str(frame.get("error") or "request failed"),+ "details": frame.get("payload") if isinstance(frame.get("payload"), dict) else {},+ }+ if rpc_method:+ body["metadata"] = _web_http_metadata(rpc_method)+ status = {+ "BAD_REQUEST": 400,+ "UNAUTHORIZED": 401,+ "FORBIDDEN": 403,+ "NOT_FOUND": 404,+ "METHOD_NOT_FOUND": 404,+ "CONFLICT": 409,+ "TIMEOUT": 504,+ "SERVICE_UNAVAILABLE": 503,+ }.get(err_code, 500)+ return body, status+++def _sse_pack(request_id: str, event: str, data: Any) -> str:+ payload = data if isinstance(data, str) else json.dumps(data, ensure_ascii=False)+ return f"id: {request_id}\nevent: {event}\ndata: {payload}\n\n"+++def create_web_http_app(channel: Any) -> FastAPI:+ """Build FastAPI app bound to an existing ``WebChannel`` instance."""+ app = FastAPI(+ title="JiuwenSwarm Gateway Web HTTP",+ version="0.2.0",+ description=(+ "Gateway 对外 HTTP+SSE(映射 WebSocket RPC method)。"+ "核心:health / sessions / chat;设置:config / models / locale / cron;"+ "工作区:permissions / skills / harness。"+ "企业旁路历史:GET /api/sessions*(ChatHistoryStore)。"+ "文件/分享:/file-api/*、/share-api/*。"+ "对照表:GET /api/v1/catalog。在本页点 **Try it out** 即可发请求。"+ ),+ docs_url="/doc",+ redoc_url="/redoc",+ openapi_url="/openapi.json",+ openapi_tags=_OPENAPI_TAGS,+ swagger_ui_parameters={"tryItOutEnabled": True, "persistAuthorization": True},+ )+ app.state.web_channel = channel++ @app.get("/", include_in_schema=False)+ @app.get("/doc/", include_in_schema=False)+ @app.get("/docs", include_in_schema=False)+ async def _doc_redirect() -> RedirectResponse:+ return RedirectResponse(url="/doc", status_code=307)++ @app.get("/api/v1/health", tags=["health"], summary="探活")+ async def health(request: Request) -> JSONResponse:+ rid = request.headers.get("x-request-id") or uuid.uuid4().hex+ return JSONResponse(+ {"request_id": rid, "ok": True, "data": {"status": "ready"}, "metadata": {}},+ headers={"X-Request-Id": rid},+ )++ @app.get("/api/v1/connection/status", tags=["health"], summary="Agent 是否就绪")+ async def connection_status(request: Request) -> Response:+ return await _unary(request, channel, "connection.status", {})++ @app.get("/api/v1/sessions", tags=["sessions"], summary="列会话(本地 session.list)")+ async def session_list(+ request: Request,+ limit: int | None = Query(None, ge=1, le=200),+ offset: int | None = Query(None, ge=0),+ ) -> Response:+ params: dict[str, Any] = {}+ if limit is not None:+ params["limit"] = limit+ if offset is not None:+ params["offset"] = offset+ return await _unary(request, channel, "session.list", params)++ @app.post(+ "/api/v1/sessions",+ tags=["sessions"],+ summary="建会话(body 可空,所有字段均可省略)",+ status_code=201,+ )+ async def session_create(+ request: Request,+ body: SessionCreateBody | None = Body(+ default=None,+ description="全部可选。直接 Execute 空对象即可;create_token 省略时由 Gateway 生成。",+ openapi_examples={+ "empty": {+ "summary": "空 body(推荐)",+ "value": {},+ },+ },+ ),+ ) -> Response:+ return await _unary(+ request, channel, "session.create", _body_dict(body), created=True,+ )++ @app.get(+ "/api/v1/sessions/{session_id}",+ tags=["sessions"],+ summary="会话元数据",+ )+ async def session_get(session_id: str, request: Request) -> Response:+ return await _unary(+ request, channel, "session.get_metadata", {"session_id": session_id},+ )++ @app.patch("/api/v1/sessions/{session_id}", tags=["sessions"], summary="重命名 / 置顶")+ async def session_patch(+ session_id: str, request: Request, body: SessionPatchBody | None = None,+ ) -> Response:+ payload = _body_dict(body)+ payload["session_id"] = session_id+ if "pinned" in payload or "pin" in payload:+ return await _unary(request, channel, "session.pin", payload)+ return await _unary(request, channel, "session.rename", payload)++ @app.delete("/api/v1/sessions/{session_id}", tags=["sessions"], summary="删除会话")+ async def session_delete(session_id: str, request: Request) -> Response:+ return await _unary(+ request, channel, "session.delete", {"session_id": session_id},+ )++ @app.get(+ "/api/v1/sessions/{session_id}/history",+ tags=["sessions"],+ summary="拉历史",+ )+ async def history_get(+ session_id: str,+ request: Request,+ page_idx: int | None = Query(None, ge=1),+ ) -> Response:+ params = _history_params(session_id, page_idx)+ accept = (request.headers.get("accept") or "").lower()+ if "text/event-stream" in accept:+ return await _stream(request, channel, "history.get", params)+ return await _history_json(request, channel, params)++ @app.post(+ "/api/v1/chat/completions",+ tags=["chat"],+ summary="发消息(默认 SSE;Web RPC method=chat.send)",+ )+ @app.post(+ "/api/v1/chat/send",+ tags=["chat"],+ summary="发消息(兼容路径;请改用 /chat/completions)",+ include_in_schema=False,+ )+ async def chat_send(request: Request, body: ChatSendBody) -> Response:+ payload = _body_dict(body)+ accept = (request.headers.get("accept") or "").lower()+ want_stream = "text/event-stream" in accept or bool(+ payload.get("enable_streaming", True),+ )+ if want_stream:+ return await _stream(request, channel, "chat.send", payload)+ return await _unary(request, channel, "chat.send", payload, is_stream=False)++ @app.post("/api/v1/chat/resume", tags=["chat"], summary="恢复中断的对话")+ async def chat_resume(request: Request, body: ChatActionBody | None = None) -> Response:+ return await _unary(+ request, channel, "chat.resume", _body_dict(body), is_stream=True,+ )++ @app.post(+ "/api/v1/chat/{session_id}/actions/interrupt",+ tags=["chat"],+ summary="中断当前生成(Web RPC method=chat.interrupt)",+ )+ async def chat_interrupt(+ session_id: str, request: Request, body: ChatActionBody | None = None,+ ) -> Response:+ payload = _body_dict(body)+ payload["session_id"] = session_id+ return await _unary(request, channel, "chat.interrupt", payload, is_stream=True)++ @app.post(+ "/api/v1/chat/{session_id}/actions/user_answer",+ tags=["chat"],+ summary="回答 Agent 追问(Web RPC method=chat.user_answer)",+ )+ @app.post(+ "/api/v1/chat/{session_id}/actions/answer",+ tags=["chat"],+ summary="回答 Agent 追问(兼容旧路径;请改用 …/user_answer)",+ include_in_schema=False,+ )+ async def chat_user_answer(+ session_id: str, request: Request, body: ChatActionBody | None = None,+ ) -> Response:+ payload = _body_dict(body)+ payload["session_id"] = session_id+ return await _unary(request, channel, "chat.user_answer", payload, is_stream=True)++ @app.get(+ "/api/v1/catalog",+ tags=["Web HTTP catalog"],+ summary="HTTP → Web RPC method 对照(可追溯)",+ )+ async def web_http_catalog(request: Request) -> JSONResponse:+ rid = request.headers.get("x-request-id") or uuid.uuid4().hex+ return JSONResponse(+ {+ "request_id": rid,+ "ok": True,+ "data": {+ "prefix": "/api/v1",+ "routes": catalog_entries()+ + catalog_sessions_compat_entries()+ + catalog_file_compat_entries(),+ },+ "metadata": _web_http_metadata("catalog"),+ },+ headers=_response_headers(rid, "catalog"),+ )++ @app.post(+ "/api/v1/harness/packages/actions/import-file",+ tags=["harness"],+ summary="导入 zip(multipart 字段 file)",+ )+ async def harness_import_file(+ request: Request,+ file: UploadFile = File(..., description="harness 包 zip"),+ ) -> Response:+ raw = await file.read()+ max_size = 50 * 1024 * 1024+ if len(raw) > max_size:+ rid = request.headers.get("x-request-id") or uuid.uuid4().hex+ return JSONResponse(+ {+ "request_id": rid,+ "ok": False,+ "error": {+ "code": "BAD_REQUEST",+ "message": "File exceeds 50MB limit",+ "details": {},+ },+ "metadata": _web_http_metadata("harness.import"),+ },+ status_code=400,+ headers=_response_headers(rid, "harness.import"),+ )+ payload = {"file_content": base64.b64encode(raw).decode("ascii")}+ return await _unary(+ request, channel, "harness.import", payload, bind_session_param=False,+ )++ _register_mapped_routes(app, channel, MAPPED_ROUTES)+ register_sessions_compat_routes(app)+ register_file_compat_routes(app)+ return app+++async def _history_json(+ request: Request,+ channel: Any,+ params: dict[str, Any],+) -> JSONResponse:+ """Collect history.message SSE frames into a REST envelope."""+ outbound = None+ req_id = request.headers.get("x-request-id") or uuid.uuid4().hex+ try:+ outbound, rid, _sid = await dispatch_http_request(+ channel,+ method="history.get",+ params=params,+ headers=request.headers,+ request_id=req_id,+ is_stream=True,+ use_sse=True,+ client_host=_request_client_host(request),+ )+ messages: list[Any] = []+ total_pages: Any = None+ page_idx: Any = params.get("page_idx", 1)+ error_payload: dict[str, Any] | None = None+ async for frame in outbound.iter_sse_frames(+ rid,+ timeout=resolve_web_http_history_timeout(),+ idle_timeout=resolve_web_http_sse_idle_timeout(),+ keepalive=resolve_web_http_sse_keepalive(),+ ):+ ftype = frame.get("type")+ if ftype == "res":+ if not frame.get("ok", True):+ body, status = _envelope_from_res(+ frame, rid, rpc_method="history.get",+ )+ return JSONResponse(+ body,+ status_code=status,+ headers=_response_headers(rid, "history.get"),+ )+ continue+ if ftype != "event":+ continue+ ev = str(frame.get("event") or "")+ payload = frame.get("payload") if isinstance(frame.get("payload"), dict) else {}+ if ev == "chat.error":+ error_payload = payload+ break+ if ev == "history.message":+ if payload.get("status") == "done":+ total_pages = payload.get("total_pages", total_pages)+ page_idx = payload.get("page_idx", page_idx)+ break+ item = payload.get("message")+ if item is not None:+ messages.append(item)+ total_pages = payload.get("total_pages", total_pages)+ page_idx = payload.get("page_idx", page_idx)+ if error_payload is not None:+ return JSONResponse(+ {+ "request_id": rid,+ "ok": False,+ "error": {+ "code": "NOT_FOUND",+ "message": str(error_payload.get("error") or "history.get failed"),+ "details": error_payload,+ },+ },+ status_code=404,+ headers=_response_headers(rid, "history.get"),+ )+ return JSONResponse(+ {+ "request_id": rid,+ "ok": True,+ "data": {+ "session_id": params.get("session_id"),+ "messages": messages,+ "total_pages": total_pages,+ "page_idx": page_idx,+ },+ "metadata": _web_http_metadata("history.get"),+ },+ headers=_response_headers(rid, "history.get"),+ )+ except Exception as exc: # noqa: BLE001+ logger.exception("[WebHTTP] history json failed: %s", exc)+ return JSONResponse(+ {+ "request_id": req_id,+ "ok": False,+ "error": {"code": "INTERNAL_ERROR", "message": str(exc), "details": {}},+ },+ status_code=500,+ headers={"X-Request-Id": req_id},+ )+ finally:+ if outbound is not None:+ try:+ await channel.unregister_request_outbound(outbound)+ except Exception: # noqa: BLE001+ logger.debug("[WebHTTP] unregister_request_outbound failed", exc_info=True)+++async def _unary(+ request: Request,+ channel: Any,+ method: str,+ params: dict[str, Any],+ *,+ created: bool = False,+ is_stream: bool = False,+ bind_session_param: bool = True,+) -> JSONResponse:+ outbound = None+ req_id = request.headers.get("x-request-id") or uuid.uuid4().hex+ try:+ outbound, req_id, _sid = await dispatch_http_request(+ channel,+ method=method,+ params=params,+ headers=request.headers,+ request_id=req_id,+ is_stream=is_stream or method in _STREAM_RPC_METHODS,+ use_sse=False,+ bind_session_param=bind_session_param,+ client_host=_request_client_host(request),+ )+ # For forwarded stream methods without SSE Accept, wait for first res (accepted).+ frame = await outbound.wait_response(+ req_id, timeout=resolve_web_http_unary_timeout(),+ )+ body, status = _envelope_from_res(frame, req_id, rpc_method=method)+ if created and body.get("ok"):+ status = 201+ return JSONResponse(+ body, status_code=status, headers=_response_headers(req_id, method),+ )+ except Exception as exc: # noqa: BLE001+ logger.exception("[WebHTTP] unary %s failed: %s", method, exc)+ return JSONResponse(+ {+ "request_id": req_id,+ "ok": False,+ "error": {+ "code": "INTERNAL_ERROR",+ "message": str(exc),+ "details": {},+ },+ "metadata": _web_http_metadata(method),+ },+ status_code=500,+ headers=_response_headers(req_id, method),+ )+ finally:+ if outbound is not None:+ try:+ await channel.unregister_request_outbound(outbound)+ except Exception: # noqa: BLE001+ logger.debug("[WebHTTP] unregister_request_outbound failed", exc_info=True)+++async def _stream(+ request: Request,+ channel: Any,+ method: str,+ params: dict[str, Any],+) -> StreamingResponse:+ req_id = request.headers.get("x-request-id") or uuid.uuid4().hex++ async def gen() -> AsyncIterator[str]:+ outbound = None+ try:+ outbound, rid, _sid = await dispatch_http_request(+ channel,+ method=method,+ params=params,+ headers=request.headers,+ request_id=req_id,+ is_stream=True,+ use_sse=True,+ client_host=_request_client_host(request),+ )+ async for frame in outbound.iter_sse_frames(+ rid,+ timeout=resolve_web_http_sse_timeout(),+ idle_timeout=resolve_web_http_sse_idle_timeout(),+ keepalive=resolve_web_http_sse_keepalive(),+ ):+ if await request.is_disconnected():+ logger.info(+ "[WebHTTP] SSE client disconnected method=%s request_id=%s",+ method,+ rid,+ )+ break+ ftype = frame.get("type")+ if ftype == "keepalive":+ yield ": keepalive\n\n"+ continue+ if ftype == "res":+ # Surface accepted / error as SSE event for clients that want it.+ ev = "web.response" if frame.get("ok", True) else "chat.error"+ data = frame.get("payload") if frame.get("ok", True) else {+ "error": frame.get("error"),+ "code": frame.get("code"),+ **(frame.get("payload") or {}),+ }+ yield _sse_pack(rid, ev, data)+ if not frame.get("ok", True):+ return+ continue+ if ftype == "event":+ yield _sse_pack(+ rid,+ str(frame.get("event") or "message"),+ frame.get("payload") if frame.get("payload") is not None else {},+ )+ except Exception as exc: # noqa: BLE001+ logger.exception("[WebHTTP] stream %s failed: %s", method, exc)+ yield _sse_pack(req_id, "chat.error", {"error": str(exc)})+ finally:+ if outbound is not None:+ try:+ await channel.unregister_request_outbound(outbound)+ except Exception: # noqa: BLE001+ logger.debug("[WebHTTP] unregister_request_outbound failed", exc_info=True)++ return StreamingResponse(+ gen(),+ media_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ "X-Request-Id": req_id,+ "X-Accel-Buffering": "no",+ "X-Web-RPC-Method": method,+ },+ )+++def _coerce_query_value(raw: str) -> Any:+ text = str(raw).strip()+ lowered = text.lower()+ if lowered in {"true", "1", "yes"}:+ return True+ if lowered in {"false", "0", "no"}:+ return False+ try:+ if text.isdigit() or (text.startswith("-") and text[1:].isdigit()):+ return int(text)+ except ValueError:+ pass+ return text+++def _merge_header_params(request: Request, params: dict[str, Any]) -> dict[str, Any]:+ out = dict(params)+ for header_name, param_name in _HEADER_TO_PARAM.items():+ if out.get(param_name):+ continue+ value = request.headers.get(header_name)+ if value:+ out[param_name] = value+ return out+++async def _params_from_mapped_route(+ request: Request,+ spec: WebHttpMappedRoute,+ body: dict[str, Any] | None = None,+) -> dict[str, Any]:+ params: dict[str, Any] = dict(spec.extra_params)+ for src, dst in spec.path_to_param.items():+ if src in request.path_params:+ params[dst] = request.path_params[src]+ for key in spec.query_keys:+ if key in request.query_params:+ params[key] = _coerce_query_value(request.query_params[key])+ raw_body = body+ if spec.accept_body and raw_body is None and request.method in {"POST", "PUT", "PATCH", "DELETE"}:+ ctype = (request.headers.get("content-type") or "").lower()+ if "application/json" in ctype:+ try:+ parsed = await request.json()+ except Exception: # noqa: BLE001+ parsed = None+ if isinstance(parsed, dict):+ raw_body = parsed+ if isinstance(raw_body, dict):+ merged = dict(raw_body)+ merged.update(params)+ params = merged+ return _merge_header_params(request, params)+++def _register_mapped_routes(app: FastAPI, channel: Any, routes: tuple[WebHttpMappedRoute, ...]) -> None:+ """Mount table-driven Web HTTP routes. Static paths must appear before `{param}` rows."""++ for spec in routes:+ def _make(route: WebHttpMappedRoute):+ if route.accept_body:+ async def _handler(+ request: Request,+ body: dict[str, Any] | None = Body(default=None),+ ) -> Response:+ params = await _params_from_mapped_route(request, route, body)+ return await _unary(+ request,+ channel,+ route.rpc_method,+ params,+ created=route.created,+ bind_session_param=route.bind_session_param,+ )+ else:+ async def _handler(request: Request) -> Response:+ params = await _params_from_mapped_route(request, route)+ return await _unary(+ request,+ channel,+ route.rpc_method,+ params,+ created=route.created,+ bind_session_param=route.bind_session_param,+ )++ _handler.__name__ = (+ f"webhttp_{route.rpc_method.replace('.', '_')}_{route.http_method.lower()}"+ )+ _handler.__doc__ = route.summary+ return _handler++ app.add_api_route(+ f"/api/v1{spec.path}",+ _make(spec),+ methods=[spec.http_method],+ tags=[spec.tag],+ summary=spec.summary,+ name=f"webhttp_{spec.rpc_method}_{spec.http_method}_{spec.path}",+ response_model=None,+ )diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.py b/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.pynew file mode 100644index 0000000000..b0508e8782--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_dispatch.py@@ -0,0 +1,188 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Dispatch Web HTTP calls into WebChannel RPC method pipeline."""++from __future__ import annotations++import logging+import os+import time+import uuid+from typing import Any++from jiuwenswarm.common.request_ext import attach_to_metadata as _ext_attach+from jiuwenswarm.common.request_ext import build_ext_from_source as _ext_build+from jiuwenswarm.common.schema.message import Message+from jiuwenswarm.gateway.channel_manager.web.invoke import dispatch_web_request as invoke_web_request+from jiuwenswarm.gateway.channel_manager.web.outbound import (+ HttpJsonOutbound,+ HttpSseOutbound,+ bind_http_session,+)+from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import WebWsTransport++logger = logging.getLogger(__name__)+++def _header_map(headers: Any) -> dict[str, str]:+ out: dict[str, str] = {}+ if headers is None:+ return out+ try:+ for k, v in headers.items():+ out[str(k)] = str(v)+ except Exception: # noqa: BLE001+ pass+ return out+++def _get_header(headers: dict[str, str], name: str) -> str:+ want = name.lower()+ for k, v in headers.items():+ if k.lower() == want:+ return str(v).strip()+ return ""+++def _trust_client_tenant_headers(client_host: str | None) -> bool:+ explicit = os.getenv("GATEWAY_WEB_HTTP_TRUST_CLIENT_HEADERS", "").strip().lower()+ if explicit in {"1", "true", "yes"}:+ return True+ if explicit in {"0", "false", "no"}:+ return False+ host = str(client_host or "").strip().lower()+ return host in {"127.0.0.1", "::1", "localhost"}+++def _build_http_ext(+ hdrs: dict[str, str],+ query: dict[str, list[str]],+) -> dict[str, Any] | None:+ source: dict[str, Any] = dict(hdrs)+ for key, values in query.items():+ if not values:+ continue+ source[key] = values[0]+ return _ext_build(source)+++async def dispatch_http_request(+ channel: Any,+ *,+ method: str,+ params: dict[str, Any] | None,+ headers: Any = None,+ request_id: str | None = None,+ is_stream: bool = False,+ use_sse: bool = False,+ bind_session_param: bool = True,+ client_host: str | None = None,+) -> tuple[Any, str, str]:+ """HTTP adapter: bind request Outbound, then run shared ``invoke.dispatch_web_request``.++ Returns ``(outbound, request_id, session_id)``. Caller must+ ``unregister_request_outbound`` when finished consuming frames.+ Does **not** call ``register_ws``.++ ``use_sse=True`` selects ``HttpSseOutbound`` (SSE / history collectors);+ otherwise ``HttpJsonOutbound`` (unary ``wait_response``). ``is_stream`` only+ sets Message.is_stream for downstream handlers.+ """+ hdrs = _header_map(headers)+ params = dict(params or {})+ req_id = (request_id or _get_header(hdrs, "X-Request-Id") or uuid.uuid4().hex).strip()+ session_id, params = bind_http_session(+ method,+ params,+ header_session_id=_get_header(hdrs, "X-Session-Id"),+ bind_param=bind_session_param,+ )+ trust_tenant_headers = _trust_client_tenant_headers(client_host)+ user_id = _get_header(hdrs, "X-User-Id") if trust_tenant_headers else None+ channel_id_hdr = _get_header(hdrs, "X-Channel-Id") or "web"+ app_id = _get_header(hdrs, "X-App-Id") or "default"++ outbound: HttpJsonOutbound | HttpSseOutbound+ if use_sse:+ outbound = HttpSseOutbound(headers=hdrs, session_id=session_id)+ else:+ outbound = HttpJsonOutbound(headers=hdrs, session_id=session_id)++ from jiuwenswarm.gateway.channel_manager.web.web_connect import (+ _WEB_CONNECTION_USER_ID_ATTR,+ )++ setattr(outbound, _WEB_CONNECTION_USER_ID_ATTR, user_id)+ channel.register_request_outbound(outbound)++ # Enterprise ChatHistoryStore: HTTP path has no browser WS frame; synthesize the+ # same inbound shape WebChannel._handle_raw_message records as "browser".+ if method in ("chat.send", "chat.resume", "chat.user_answer"):+ try:+ import json as _json++ browser_frame = {+ "type": "req",+ "id": req_id,+ "method": method,+ "params": params,+ }+ channel.rpc.record_history_frame(+ "browser", _json.dumps(browser_frame, ensure_ascii=False),+ )+ except Exception: # noqa: BLE001+ logger.debug("[WebHTTP] history browser frame skipped", exc_info=True)++ query: dict[str, list[str]] = {}+ if trust_tenant_headers:+ for hk, hv in (+ ("user_id", user_id or ""),+ ("group_id", _get_header(hdrs, "X-Group-Id")),+ ("bot_id", _get_header(hdrs, "X-Bot-Id")),+ ):+ if hv:+ query[hk] = [hv]++ ext = _build_http_ext(hdrs, query if trust_tenant_headers else {})+ if ext:+ setattr(outbound, "_web_request_ext", ext)++ mode = str(params.get("mode") or "agent")+ agent_id = str(params.get("agent_id") or "default")++ user_message = Message(+ id=req_id,+ type="req",+ channel_id=getattr(channel, "channel_id", None) or channel_id_hdr or "web",+ session_id=session_id,+ params=params,+ timestamp=time.time(),+ ok=True,+ req_method=WebWsTransport.parse_req_method(method),+ mode=WebWsTransport.parse_mode(params.get("mode")),+ is_stream=bool(is_stream),+ app_id=app_id,+ agent_ref={"mode": mode, "id": agent_id},+ user_id=user_id,+ metadata=_ext_attach(+ {+ "query": query,+ "method": method,+ "ws_id": getattr(outbound, "_jiuwen_ws_id", ""),+ "user_id": user_id,+ "transport": "web-http",+ },+ ext=ext,+ ),+ )++ await invoke_web_request(+ channel,+ method=method,+ params=params,+ request_id=req_id,+ outbound=outbound,+ session_id=session_id,+ user_message=user_message,+ )+ return outbound, req_id, session_iddiff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.py b/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.pynew file mode 100644index 0000000000..5acb35ae56--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.py@@ -0,0 +1,408 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Mount legacy ``/file-api/*`` and ``/share-api/*`` on Gateway Web HTTP."""++from __future__ import annotations++import logging+import os+from pathlib import Path+from typing import Any, Iterator++from fastapi import FastAPI, File, Form, Query, Request, UploadFile+from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse++from jiuwenswarm.gateway.channel_manager.web.file_http import (+ FileHttpRoots,+ build_share_snapshot,+ content_disposition,+ default_file_http_roots,+ generate_agent_data,+ guess_mime,+ is_download_path_allowed,+ list_files,+ list_markdown,+ parse_single_byte_range,+ process_obs_upload_body,+ read_file_text,+ resolve_raw_file_path,+ save_pushed_file,+ write_markdown_content,+)++logger = logging.getLogger(__name__)++_OPENAPI_TAG = "file / share HTTP"+_DEFAULT_MAX_PUSH_BYTES = 64 * 1024 * 1024+++def _max_push_upload_bytes() -> int:+ raw = os.getenv("GATEWAY_WEB_HTTP_MAX_UPLOAD_BYTES", "").strip()+ if not raw:+ return _DEFAULT_MAX_PUSH_BYTES+ try:+ value = int(raw)+ except ValueError:+ return _DEFAULT_MAX_PUSH_BYTES+ return value if value > 0 else _DEFAULT_MAX_PUSH_BYTES+++def _is_loopback_client(request: Request) -> bool:+ client = request.client+ if client is None:+ return False+ host = str(getattr(client, "host", "") or "").strip().lower()+ return host in {"127.0.0.1", "::1", "localhost"}+++def _roots(app: FastAPI) -> FileHttpRoots:+ cached = getattr(app.state, "file_http_roots", None)+ if isinstance(cached, FileHttpRoots):+ return cached+ roots = default_file_http_roots()+ app.state.file_http_roots = roots+ return roots+++def _json(status: int, payload: dict[str, Any]) -> JSONResponse:+ return JSONResponse(payload, status_code=status)+++def catalog_file_compat_entries() -> list[dict[str, Any]]:+ paths = [+ ("GET", "/file-api/list-files", "列目录"),+ ("GET", "/file-api/list-markdown", "列 markdown"),+ ("GET", "/file-api/file-content", "读文本"),+ ("POST", "/file-api/file-content", "写 markdown"),+ ("GET", "/file-api/raw-file", "原始字节"),+ ("GET", "/file-api/download", "token 下载"),+ ("GET", "/file-api/ws-debug-config", "WS 调试读"),+ ("POST", "/file-api/ws-debug-config", "WS 调试写"),+ ("POST", "/file-api/rebuild-agent-data", "重建 agent-data"),+ ("POST", "/file-api/upload-obs", "企业 MinIO 上传"),+ ("POST", "/file-api/push", "企业本地落盘+token"),+ ("GET", "/share-api/snapshot", "分享 snapshot"),+ ]+ return [+ {+ "http_method": method,+ "path": path,+ "rpc_method": None,+ "phase": "compat",+ "note": note,+ }+ for method, path, note in paths+ ]+++def register_file_compat_routes(app: FastAPI) -> None:+ """Register ``/file-api/*`` and ``/share-api/snapshot`` on the Web HTTP app."""++ # In-process debug flag (was class var on app_web handler).+ if not hasattr(app.state, "ws_disable_compress"):+ app.state.ws_disable_compress = False++ @app.get(+ "/file-api/list-markdown",+ tags=[_OPENAPI_TAG],+ summary="列出目录下 markdown",+ )+ async def file_list_markdown(+ request: Request,+ dir_path: str = Query("", alias="dir"),+ ) -> JSONResponse:+ status, body = list_markdown(_roots(request.app), dir_path)+ return _json(status, body)++ @app.get(+ "/file-api/list-files",+ tags=[_OPENAPI_TAG],+ summary="列出目录文件",+ )+ async def file_list_files(+ request: Request,+ dir_path: str = Query("", alias="dir"),+ ) -> JSONResponse:+ status, body = list_files(_roots(request.app), dir_path)+ return _json(status, body)++ @app.get(+ "/file-api/file-content",+ tags=[_OPENAPI_TAG],+ summary="读取文本文件",+ )+ async def file_content_get(+ request: Request,+ path: str = Query(""),+ encoding: str = Query("utf-8"),+ ) -> Response:+ status, err, body, used = read_file_text(_roots(request.app), path, encoding)+ if err is not None:+ return _json(status, err)+ headers = {"Cache-Control": "no-store"}+ if used:+ headers["X-Original-Encoding"] = used+ return Response(+ content=body or b"",+ status_code=200,+ media_type="text/plain; charset=utf-8",+ headers=headers,+ )++ @app.post(+ "/file-api/file-content",+ tags=[_OPENAPI_TAG],+ summary="写入 markdown",+ )+ async def file_content_post(request: Request) -> JSONResponse:+ try:+ payload = await request.json()+ except Exception:+ return _json(400, {"error": "invalid_json"})+ if not isinstance(payload, dict):+ return _json(400, {"error": "invalid_json"})+ status, body = write_markdown_content(+ _roots(request.app),+ payload.get("path"),+ payload.get("content"),+ )+ return _json(status, body)++ @app.get(+ "/file-api/raw-file",+ tags=[_OPENAPI_TAG],+ summary="原始文件字节",+ )+ async def file_raw_get(+ request: Request,+ path: str = Query(""),+ ) -> Response:+ return _file_raw_response(request, path, head=False)++ @app.head("/file-api/raw-file", include_in_schema=False)+ async def file_raw_head(+ request: Request,+ path: str = Query(""),+ ) -> Response:+ return _file_raw_response(request, path, head=True)++ def _file_raw_response(request: Request, path: str, *, head: bool) -> Response:+ status, err, full_path = resolve_raw_file_path(_roots(request.app), path)+ if err is not None or full_path is None:+ return _json(status, err or {"error": "file_not_found"})+ mime = guess_mime(full_path)+ if head:+ return Response(+ status_code=200,+ media_type=mime,+ headers={+ "Content-Length": str(full_path.stat().st_size),+ "Cache-Control": "no-store",+ },+ )+ return FileResponse(+ path=str(full_path),+ media_type=mime,+ headers={"Cache-Control": "no-store"},+ )++ @app.get(+ "/file-api/download",+ tags=[_OPENAPI_TAG],+ summary="token 下载(支持 Range)",+ )+ async def file_download_get(+ request: Request,+ token: str = Query(""),+ inline: str = Query(""),+ ) -> Response:+ return _file_download_response(request, token, inline, head=False)++ @app.head("/file-api/download", include_in_schema=False)+ async def file_download_head(+ request: Request,+ token: str = Query(""),+ inline: str = Query(""),+ ) -> Response:+ return _file_download_response(request, token, inline, head=True)++ def _file_download_response(+ request: Request,+ token: str,+ inline: str,+ *,+ head: bool,+ ) -> Response:+ if not token:+ return _json(400, {"error": "missing_token"})+ try:+ from jiuwenswarm.agents.harness.common.tools.web_file_download import (+ validate_file_download_token,+ )+ except ImportError:+ return _json(500, {"error": "download_module_unavailable"})++ payload = validate_file_download_token(token)+ if payload is None:+ return _json(403, {"error": "invalid_or_expired_token"})++ file_path = str(payload.get("path") or "")+ if not file_path or not os.path.isfile(file_path):+ return _json(404, {"error": "file_not_found"})+ if not is_download_path_allowed(Path(file_path), _roots(request.app)):+ return _json(403, {"error": "forbidden_path"})++ file_size = os.path.getsize(file_path)+ file_name = os.path.basename(file_path)+ mime_type = guess_mime(file_name)+ inline_flag = inline.lower() in {"1", "true"}+ range_header = request.headers.get("range") or request.headers.get("Range")+ byte_range = None+ if range_header:+ byte_range = parse_single_byte_range(range_header, file_size)+ if byte_range is None:+ return Response(+ status_code=416,+ headers={"Content-Range": f"bytes */{file_size}"},+ )++ start, end = byte_range or (0, max(0, file_size - 1))+ content_length = 0 if file_size == 0 else end - start + 1+ status_code = 206 if byte_range is not None else 200+ headers = {+ "Content-Type": mime_type,+ "Content-Length": str(content_length),+ "Accept-Ranges": "bytes",+ "Content-Disposition": content_disposition(file_name, inline=inline_flag),+ "Cache-Control": "no-store",+ }+ if byte_range is not None:+ headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"++ if head:+ return Response(status_code=status_code, headers=headers)++ def _iter() -> Iterator[bytes]:+ with open(file_path, "rb") as handle:+ handle.seek(start)+ remaining = content_length+ while remaining > 0:+ chunk = handle.read(min(65536, remaining))+ if not chunk:+ break+ remaining -= len(chunk)+ yield chunk++ return StreamingResponse(_iter(), status_code=status_code, headers=headers)++ @app.get(+ "/file-api/ws-debug-config",+ tags=[_OPENAPI_TAG],+ summary="WS 调试压缩开关(读)",+ )+ async def ws_debug_get(request: Request) -> JSONResponse:+ return _json(+ 200,+ {"wsDisableCompress": bool(getattr(request.app.state, "ws_disable_compress", False))},+ )++ @app.post(+ "/file-api/ws-debug-config",+ tags=[_OPENAPI_TAG],+ summary="WS 调试压缩开关(写)",+ )+ async def ws_debug_post(request: Request) -> JSONResponse:+ if not _is_loopback_client(request):+ return _json(403, {"error": "forbidden"})+ try:+ payload = await request.json()+ except Exception:+ return _json(400, {"error": "invalid_json"})+ if not isinstance(payload, dict):+ return _json(400, {"error": "invalid_json"})+ flag = payload.get("wsDisableCompress")+ if not isinstance(flag, bool):+ return _json(400, {"error": "invalid_ws_disable_compress"})+ request.app.state.ws_disable_compress = flag+ logger.info("[file_http] ws disable compress updated: %s", flag)+ return _json(200, {"ok": True, "wsDisableCompress": flag})++ @app.post(+ "/file-api/rebuild-agent-data",+ tags=[_OPENAPI_TAG],+ summary="重建 agent-data.json",+ )+ async def rebuild_agent_data(request: Request) -> JSONResponse:+ try:+ generate_agent_data(_roots(request.app).project_root)+ except Exception as exc: # noqa: BLE001+ return _json(500, {"error": "rebuild_failed", "detail": str(exc)})+ return _json(200, {"ok": True})++ @app.post(+ "/file-api/upload-obs",+ tags=[_OPENAPI_TAG],+ summary="企业 MinIO 上传",+ )+ async def upload_obs(request: Request) -> JSONResponse:+ if not os.getenv("AGENT_RUNTIME", "").strip():+ return _json(404, {"error": "not_available"})+ raw = await request.body()+ status, payload = process_obs_upload_body(raw)+ return _json(status, payload)++ @app.post(+ "/file-api/push",+ tags=[_OPENAPI_TAG],+ summary="企业文件落盘并签 download token(Gateway 本地)",+ )+ async def file_push(+ request: Request,+ file: UploadFile = File(...),+ session_id: str = Form("default"),+ filename: str = Form(""),+ ) -> JSONResponse:+ if not os.getenv("AGENT_RUNTIME", "").strip():+ return _json(404, {"error": "not_available"})+ try:+ raw = await file.read()+ if len(raw) > _max_push_upload_bytes():+ return _json(413, {"error": "file_too_large"})+ name = (filename or file.filename or "unnamed").strip() or "unnamed"+ result = save_pushed_file(+ file_bytes=raw,+ filename=name,+ session_id=session_id or "default",+ )+ return _json(200, result)+ except ValueError:+ return _json(400, {"error": "invalid_filename"})+ except Exception as exc:+ logger.error("[file_http] push failed: %s", exc, exc_info=True)+ return _json(500, {"error": "push_failed", "detail": str(exc)})++ @app.get(+ "/share-api/snapshot",+ tags=[_OPENAPI_TAG],+ summary="分享导出 snapshot",+ )+ async def share_snapshot(+ request: Request,+ session_id: str = Query(""),+ user: str | None = Query(None),+ ) -> JSONResponse:+ sid = (session_id or "").strip()+ if not sid:+ return _json(400, {"error": "missing_session_id"})+ user_q = (user or "").strip() or None+ if user_q is None:+ hdr = request.headers.get("x-user-id")+ if hdr and str(hdr).strip():+ user_q = str(hdr).strip()+ try:+ snapshot, filename = build_share_snapshot(session_id=sid, user=user_q)+ except FileNotFoundError:+ return _json(404, {"error": "history_not_found"})+ except ValueError as exc:+ return _json(400, {"error": str(exc)})+ return _json(200, {"filename": filename, "snapshot": snapshot})diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.pynew file mode 100644index 0000000000..a0d4292d8a--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py@@ -0,0 +1,620 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Gateway Web HTTP mapped-route table (settings + workspace modules).++Each row is the contract: HTTP verb+path → WebChannel ``register_method`` name.+Handlers stay transport-agnostic; this module has no FastAPI / Gateway imports+so it can be unit-tested and used as the OpenAPI/catalog source of truth.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Mapping, Sequence+++@dataclass(frozen=True)+class WebHttpMappedRoute:+ """One HTTP surface over an existing WebChannel method."""++ http_method: str+ path: str+ rpc_method: str+ tag: str+ summary: str+ path_to_param: Mapping[str, str] = field(default_factory=dict)+ query_keys: tuple[str, ...] = ()+ accept_body: bool = False+ bind_session_param: bool = False+ created: bool = False+ extra_params: Mapping[str, Any] = field(default_factory=dict)++ def __post_init__(self) -> None:+ if not self.path.startswith("/"):+ raise ValueError(f"path must start with /: {self.path}")+ method = self.http_method.upper()+ object.__setattr__(self, "http_method", method)+ if method not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:+ raise ValueError(f"unsupported HTTP method: {method}")+ if not str(self.rpc_method).strip():+ raise ValueError("rpc_method is required")+++# Tenant ids accepted on query (and merged from X-Group-Id / X-Bot-Id / X-User-Id).+_TENANT_QUERY = ("group_id", "bot_id", "user_id", "service_id", "agent_id")+_SKILL_SESSION_QUERY = ("session_id",)+# Agent skills.evolution.* requires params.name (A1 / 企业浏览器契约).+_SKILL_NAME_QUERY = _SKILL_SESSION_QUERY + ("name",)+# Agent skills.skillnet.install_status requires params.install_id.+_SKILLNET_INSTALL_STATUS_QUERY = _SKILL_SESSION_QUERY + ("install_id",)+_CRON_QUERY = _TENANT_QUERY + ("project_id", "session_id", "count")++# ---------------------------------------------------------------------------+# settings — config / models / locale (enterprise read-mostly; writes via Manager)+# ---------------------------------------------------------------------------+_CONFIG_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/config", "config.get",+ "config", "读配置(企业只读;写权威在 Claw Manager)",+ ),+)++_MODELS_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/models", "models.list",+ "models", "模型列表(企业聊天下拉只读)",+ ),+)++_LOCALE_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/locale", "locale.get_conf",+ "locale", "读 preferred_language",+ ),+ WebHttpMappedRoute(+ "PUT", "/locale", "locale.set_conf",+ "locale", "写 preferred_language(body.preferred_language=zh|en)",+ accept_body=True,+ ),+)++_CRON_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/cron/jobs", "cron.job.list",+ "cron", "列定时任务",+ query_keys=_CRON_QUERY,+ ),+ WebHttpMappedRoute(+ "GET", "/cron/jobs/{id}", "cron.job.get",+ "cron", "获取单个任务",+ path_to_param={"id": "id"},+ query_keys=_CRON_QUERY,+ ),+ WebHttpMappedRoute(+ "PATCH", "/cron/jobs/{id}", "cron.job.update",+ "cron", "更新任务(body.patch 对象,与 RPC params 一致)",+ path_to_param={"id": "id"},+ query_keys=_TENANT_QUERY,+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "DELETE", "/cron/jobs/{id}", "cron.job.delete",+ "cron", "删除任务",+ path_to_param={"id": "id"},+ query_keys=_TENANT_QUERY,+ ),+ WebHttpMappedRoute(+ "POST", "/cron/jobs/{id}/actions/toggle", "cron.job.toggle",+ "cron", "启停任务(body.enabled)",+ path_to_param={"id": "id"},+ query_keys=_TENANT_QUERY,+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST", "/cron/jobs/{id}/actions/preview", "cron.job.preview",+ "cron", "预览下次运行(可选 body/query count)",+ path_to_param={"id": "id"},+ query_keys=_CRON_QUERY,+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST", "/cron/jobs/{id}/actions/run-now", "cron.job.run_now",+ "cron", "立即执行一次",+ path_to_param={"id": "id"},+ query_keys=_TENANT_QUERY,+ accept_body=True,+ ),+)++SETTINGS_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ *_CONFIG_ROUTES,+ *_MODELS_ROUTES,+ *_LOCALE_ROUTES,+ *_CRON_ROUTES,+)++# ---------------------------------------------------------------------------+# workspace — permissions.* (browser settings / avatar; not Claw Manager REST)+# ---------------------------------------------------------------------------+_PERMISSIONS_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/permissions/owner-scopes", "permissions.owner_scopes.get",+ "permissions", "数字分身 owner_scopes",+ ),+ WebHttpMappedRoute(+ "PUT", "/permissions/owner-scopes", "permissions.owner_scopes.set",+ "permissions", "写入 owner_scopes",+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "GET", "/permissions/tools", "permissions.tools.get",+ "permissions", "工具级 allow/ask/deny",+ ),+ WebHttpMappedRoute(+ "PUT", "/permissions/tools", "permissions.tools.set",+ "permissions", "整表替换 permissions.tools",+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST", "/permissions/tools/actions/update", "permissions.tools.update",+ "permissions", "更新单条工具级别(body.tool + level;适合含特殊字符的工具名)",+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "PATCH", "/permissions/tools/{tool}", "permissions.tools.update",+ "permissions", "更新单条工具级别",+ path_to_param={"tool": "tool"},+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "DELETE", "/permissions/tools/{tool}", "permissions.tools.delete",+ "permissions", "删除单条工具级别",+ path_to_param={"tool": "tool"},+ ),+ WebHttpMappedRoute(+ "GET", "/permissions/rules", "permissions.rules.get",+ "permissions", "列出参数级规则",+ ),+ WebHttpMappedRoute(+ "POST", "/permissions/rules", "permissions.rules.create",+ "permissions", "创建规则(body.rule)",+ accept_body=True,+ created=True,+ ),+ WebHttpMappedRoute(+ "PATCH", "/permissions/rules/{id}", "permissions.rules.update",+ "permissions", "更新规则(body.patch)",+ path_to_param={"id": "id"},+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "DELETE", "/permissions/rules/{id}", "permissions.rules.delete",+ "permissions", "删除规则",+ path_to_param={"id": "id"},+ ),+ WebHttpMappedRoute(+ "GET", "/permissions/approval-overrides", "permissions.approval_overrides.get",+ "permissions", "列出「总是允许」覆盖项",+ ),+ WebHttpMappedRoute(+ "DELETE", "/permissions/approval-overrides/{id}",+ "permissions.approval_overrides.delete",+ "permissions", "删除一条覆盖项",+ path_to_param={"id": "id"},+ ),+)++# ---------------------------------------------------------------------------+# workspace — skills.* (static prefixes before /skills/{name})+# ---------------------------------------------------------------------------+_SKILLS_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/skills", "skills.list",+ "skills", "技能列表(个人/本机目录)",+ query_keys=("with_installed", "refresh_marketplaces") + _SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/installed", "skills.installed",+ "skills", "已安装技能",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/enterprise", "skills.enterprise.list",+ "skills", "企业租户已装技能(Gateway 本地表)",+ query_keys=_TENANT_QUERY,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/enterprise/actions/install", "skills.enterprise.install",+ "skills", "企业租户安装",+ query_keys=_TENANT_QUERY,+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/enterprise/actions/uninstall", "skills.enterprise.uninstall",+ "skills", "企业租户卸载",+ query_keys=_TENANT_QUERY,+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/marketplace", "skills.marketplace.list",+ "skills", "技能市场列表",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/marketplace", "skills.marketplace.add",+ "skills", "添加市场源",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/marketplace/actions/remove", "skills.marketplace.remove",+ "skills", "移除市场源",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/marketplace/actions/toggle", "skills.marketplace.toggle",+ "skills", "启停市场源",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/clawhub/token", "skills.clawhub.get_token",+ "skills", "ClawHub token",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "PUT", "/skills/clawhub/token", "skills.clawhub.set_token",+ "skills", "保存 ClawHub token",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/clawhub/search", "skills.clawhub.search",+ "skills", "搜索 ClawHub(query.q)",+ query_keys=("q", "limit") + _SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/clawhub/actions/search", "skills.clawhub.search",+ "skills", "搜索 ClawHub",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/clawhub/actions/download", "skills.clawhub.download",+ "skills", "从 ClawHub 安装",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/teamskillshub", "skills.teamskillshub.info",+ "skills", "TeamSkills Hub 信息",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/init", "skills.teamskillshub.init",+ "skills", "TeamSkills Hub 初始化",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/validate", "skills.teamskillshub.validate",+ "skills", "校验待发布技能",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/pack", "skills.teamskillshub.pack",+ "skills", "打包技能",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/search", "skills.teamskillshub.search",+ "skills", "搜索 TeamSkills Hub",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/install", "skills.teamskillshub.install",+ "skills", "从 TeamSkills Hub 安装",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/publish", "skills.teamskillshub.publish",+ "skills", "发布到 TeamSkills Hub",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/teamskillshub/actions/delete", "skills.teamskillshub.delete",+ "skills", "删除 TeamSkills Hub 版本",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/retrieval/status", "skills.retrieval.status",+ "skills", "技能检索索引状态",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/retrieval/tree", "skills.retrieval.tree",+ "skills", "技能检索树",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/retrieval/actions/index-build", "skills.retrieval.index_build",+ "skills", "构建检索索引",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/retrieval/actions/index-cancel", "skills.retrieval.index_cancel",+ "skills", "取消索引构建",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/retrieval/actions/search", "skills.retrieval.search",+ "skills", "检索技能",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/evolution/status", "skills.evolution.status",+ "skills", "技能进化状态(query: session_id, name)",+ query_keys=_SKILL_NAME_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/evolution", "skills.evolution.get",+ "skills", "当前进化配置(query: session_id, name)",+ query_keys=_SKILL_NAME_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "PUT", "/skills/evolution", "skills.evolution.save",+ "skills", "保存进化配置",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/evolution/archives", "skills.evolution.archives",+ "skills", "进化归档(query: session_id, name)",+ query_keys=_SKILL_NAME_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/evolution/actions/rollback", "skills.evolution.rollback",+ "skills", "进化回滚",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/evolution/actions/rebuild", "skills.evolution.rebuild",+ "skills", "重建进化产物",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/skillnet/actions/search", "skills.skillnet.search",+ "skills", "SkillNet 搜索",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/skillnet/actions/install", "skills.skillnet.install",+ "skills", "SkillNet 安装",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/skillnet/install-status", "skills.skillnet.install_status",+ "skills", "SkillNet 安装状态(query: session_id, install_id)",+ query_keys=_SKILLNET_INSTALL_STATUS_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/skillnet/actions/evaluate", "skills.skillnet.evaluate",+ "skills", "SkillNet 评估",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/online-search/actions/search", "skills.online_search.search",+ "skills", "在线搜索技能",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/actions/install", "skills.install",+ "skills", "安装技能(body.spec)",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/actions/uninstall", "skills.uninstall",+ "skills", "卸载技能(body.name)",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/actions/toggle", "skills.toggle",+ "skills", "启用/停用技能",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/skills/actions/import-local", "skills.import_local",+ "skills", "从本地路径导入",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/skills/{name}", "skills.get",+ "skills", "技能详情",+ path_to_param={"name": "name"},+ query_keys=("origin",) + _SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+)++# ---------------------------------------------------------------------------+# workspace — harness.* (packages on local workspace; Manager does not push these)+# ---------------------------------------------------------------------------+_HARNESS_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET", "/harness/packages", "harness.packages",+ "harness", "列出 harness 包",+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/harness/packages/actions/scan", "harness.packages.scan",+ "harness", "扫描并刷新包列表",+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/harness/packages/actions/import", "harness.import",+ "harness", "导入 zip(JSON file_content=base64;multipart 见专用入口)",+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST", "/harness/packages/{package_id}/actions/activate", "harness.activate",+ "harness", "激活包",+ path_to_param={"package_id": "package_id"},+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "POST", "/harness/packages/{package_id}/actions/deactivate", "harness.deactivate",+ "harness", "停用包",+ path_to_param={"package_id": "package_id"},+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/harness/packages/{package_id}/export", "harness.export",+ "harness", "导出包(返回 download_url / token,文件走既有 HTTP 下载)",+ path_to_param={"package_id": "package_id"},+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "DELETE", "/harness/packages/{package_id}", "harness.delete",+ "harness", "删除包",+ path_to_param={"package_id": "package_id"},+ query_keys=_SKILL_SESSION_QUERY,+ bind_session_param=True,+ ),+)++WORKSPACE_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ *_PERMISSIONS_ROUTES,+ *_SKILLS_ROUTES,+ *_HARNESS_ROUTES,+)++# All table-driven routes. Core chat/session routes stay hand-written in web_http_app.py.+MAPPED_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ *SETTINGS_ROUTES,+ *WORKSPACE_ROUTES,+)++# Core routes implemented in web_http_app.py (hand-written because of SSE / history collect).+CORE_ROUTE_CATALOG: tuple[tuple[str, str, str, str], ...] = (+ ("GET", "/health", "", "探活(非 RPC method)"),+ ("GET", "/connection/status", "connection.status", "Agent 连接状态"),+ ("GET", "/sessions", "session.list", "列会话"),+ ("POST", "/sessions", "session.create", "建会话"),+ ("GET", "/sessions/{session_id}", "session.get_metadata", "会话元数据"),+ ("PATCH", "/sessions/{session_id}", "session.rename|session.pin", "重命名 / 置顶"),+ ("DELETE", "/sessions/{session_id}", "session.delete", "删除会话"),+ ("GET", "/sessions/{session_id}/history", "history.get", "JSON;Accept:text/event-stream 时 SSE"),+ ("POST", "/chat/completions", "chat.send", "发消息 SSE(主路径)"),+ ("POST", "/chat/resume", "chat.resume", "恢复中断对话"),+ ("POST", "/chat/{session_id}/actions/interrupt", "chat.interrupt", "中断生成"),+ ("POST", "/chat/{session_id}/actions/user_answer", "chat.user_answer", "回答 Agent 追问"),+)+++def validate_mapped_routes(routes: Sequence[WebHttpMappedRoute] | None = None) -> None:+ """Fail fast on duplicate HTTP surfaces (path param names ignored)."""+ seen: set[tuple[str, str]] = set()+ for route in routes if routes is not None else MAPPED_ROUTES:+ key = (route.http_method, _normalize_path_key(route.path))+ if key in seen:+ raise ValueError(f"duplicate Web HTTP route {route.http_method} {route.path}")+ seen.add(key)+++def _normalize_path_key(path: str) -> str:+ parts: list[str] = []+ for part in path.split("/"):+ if part.startswith("{") and part.endswith("}"):+ parts.append("{}")+ else:+ parts.append(part)+ return "/".join(parts)+++def _catalog_row_from_route(route: WebHttpMappedRoute, *, group: str) -> dict[str, Any]:+ return {+ "http_method": route.http_method,+ "path": f"/api/v1{route.path}",+ "rpc_method": route.rpc_method,+ "group": group,+ "tag": route.tag,+ "summary": route.summary,+ "bind_session_param": route.bind_session_param,+ }+++def catalog_entries(+ *,+ include_core: bool = True,+ include_settings: bool = True,+ include_workspace: bool = True,+) -> list[dict[str, Any]]:+ """Machine-readable map for GET /api/v1/catalog and docs generation."""+ rows: list[dict[str, Any]] = []+ if include_core:+ for http_method, path, rpc_method, note in CORE_ROUTE_CATALOG:+ rows.append({+ "http_method": http_method,+ "path": f"/api/v1{path}",+ "rpc_method": rpc_method or None,+ "group": "core",+ "note": note,+ })+ if include_settings:+ for route in SETTINGS_ROUTES:+ rows.append(_catalog_row_from_route(route, group="settings"))+ if include_workspace:+ for route in WORKSPACE_ROUTES:+ rows.append(_catalog_row_from_route(route, group="workspace"))+ rows.append({+ "http_method": "POST",+ "path": "/api/v1/harness/packages/actions/import-file",+ "rpc_method": "harness.import",+ "group": "workspace",+ "tag": "harness",+ "summary": "multipart 字段 file → harness.import",+ "bind_session_param": False,+ })+ return rows+++validate_mapped_routes()diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_server.py b/jiuwenswarm/gateway/channel_manager/web/web_http_server.pynew file mode 100644index 0000000000..f0475fae49--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_server.py@@ -0,0 +1,170 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Start Gateway Web HTTP server (uvicorn) owned by WebChannel."""++from __future__ import annotations++import asyncio+import logging+import os+from typing import Any++logger = logging.getLogger(__name__)+++def _parse_env_port(name: str, fallback: int) -> int:+ raw = os.getenv(name, "").strip()+ if not raw:+ return fallback+ try:+ return int(raw)+ except ValueError:+ logger.warning("%s=%r is not a valid port; using %s", name, raw, fallback)+ return fallback+++def resolve_web_http_port(+ ws_port: int = 19000,+ *,+ http_port: int | None = None,+) -> int:+ """Resolve Gateway Web HTTP listen port.++ ``GATEWAY_WEB_HTTP_PORT`` overrides the computed port. When the chosen port+ collides with ``ws_port`` or ``GATEWAY_PORT``, returns the next free port.+ """+ ws_port = int(ws_port)+ port = int(http_port if http_port is not None else ws_port + 2)+ port = _parse_env_port("GATEWAY_WEB_HTTP_PORT", port)+ gateway_port = _parse_env_port("GATEWAY_PORT", ws_port + 1)+ if port in (ws_port, gateway_port):+ port = max(ws_port, gateway_port) + 1+ return port+++def _env_float(name: str, default: float, *, allow_zero: bool = False) -> float:+ raw = os.getenv(name, "").strip()+ if not raw:+ return default+ try:+ value = float(raw)+ except ValueError:+ return default+ if allow_zero:+ return value if value >= 0 else default+ return value if value > 0 else default+++def resolve_web_http_sse_timeout() -> float:+ """Total SSE stream lifetime seconds (default 600)."""+ return _env_float("GATEWAY_WEB_HTTP_SSE_TIMEOUT", 600.0)+++def resolve_web_http_sse_idle_timeout() -> float:+ """Idle seconds without frames before ending SSE (default 0 = disabled)."""+ return _env_float("GATEWAY_WEB_HTTP_SSE_IDLE_TIMEOUT", 0.0, allow_zero=True)+++def resolve_web_http_sse_keepalive() -> float:+ """Seconds between SSE keepalive comments while waiting (default 30)."""+ return _env_float("GATEWAY_WEB_HTTP_SSE_KEEPALIVE", 30.0)+++def resolve_web_http_unary_timeout() -> float:+ """Unary ``wait_response`` timeout seconds (default 120)."""+ return _env_float("GATEWAY_WEB_HTTP_UNARY_TIMEOUT", 120.0)+++def resolve_web_http_history_timeout() -> float:+ """History JSON collector timeout seconds (default 60)."""+ return _env_float("GATEWAY_WEB_HTTP_HISTORY_TIMEOUT", 60.0)+++async def _wait_http_listen(+ host: str,+ port: int,+ task: asyncio.Task[Any],+ *,+ timeout: float = 5.0,+) -> None:+ """Wait until the HTTP port accepts TCP connections or the serve task fails."""+ loop = asyncio.get_running_loop()+ deadline = loop.time() + timeout+ connect_host = host if host not in ("0.0.0.0", "::", "") else "127.0.0.1"+ while loop.time() < deadline:+ if task.done():+ exc = task.exception()+ if exc:+ raise exc+ raise RuntimeError("web http server exited during startup")+ try:+ _reader, writer = await asyncio.wait_for(+ asyncio.open_connection(connect_host, port),+ timeout=0.25,+ )+ except (OSError, asyncio.TimeoutError):+ # ConnectionRefusedError is an OSError subclass; do not list both.+ await asyncio.sleep(0.05)+ continue+ writer.close()+ try:+ await writer.wait_closed()+ except Exception: # noqa: BLE001+ pass+ return+ raise TimeoutError(+ f"web http not accepting connections on {host}:{port} within {timeout}s",+ )+++async def start_web_http_server(+ channel: Any,+ *,+ host: str,+ port: int,+) -> tuple[Any, asyncio.Task[Any]]:+ """Bind FastAPI Web HTTP app with uvicorn; return ``(server, serve_task)``."""+ import uvicorn++ from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app++ if port == getattr(getattr(channel, "config", None), "ws_port", None):+ logger.warning(+ "[WebHTTP] HTTP port %s equals WebChannel ws_port — "+ "WS and HTTP cannot share the same bind without multiplexing; "+ "start may fail. Use a distinct http_port (default 19002).",+ port,+ )++ app = create_web_http_app(channel)+ cfg = uvicorn.Config(+ app=app,+ host=host,+ port=port,+ log_level="info",+ access_log=False,+ lifespan="on",+ )+ server = uvicorn.Server(cfg)+ task = asyncio.create_task(server.serve(), name="gateway-web-http")+ await _wait_http_listen(host, port, task)+ logger.info(+ "[WebHTTP] listening http://%s:%s/api/v1 "+ "(also /file-api /share-api /api/sessions*; health=/api/v1/health)",+ host,+ port,+ )+ return server, task+++async def stop_web_http_server(server: Any, task: asyncio.Task[Any] | None) -> None:+ if server is not None:+ server.should_exit = True+ if task is not None:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ except Exception: # noqa: BLE001+ logger.debug("[WebHTTP] serve task stop error", exc_info=True)diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_sessions_compat.py b/jiuwenswarm/gateway/channel_manager/web/web_http_sessions_compat.pynew file mode 100644index 0000000000..418bbd4f29--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_sessions_compat.py@@ -0,0 +1,108 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Enterprise bypass history HTTP: ``GET /api/sessions*`` (compat, not versioned ``/api/v1``).++Reads the same ``ChatHistoryStore`` written by Gateway ``WebChannel`` Listen+(and Web HTTP chat frames). JSON shape matches ``app_web._handle_history_api_get``.+"""++from __future__ import annotations++import asyncio+import logging+import os+from typing import Any++from fastapi import FastAPI, Query, Request+from fastapi.responses import JSONResponse++logger = logging.getLogger(__name__)+++def register_sessions_compat_routes(app: FastAPI) -> None:+ """Mount ``GET /api/sessions`` and ``GET /api/sessions/{session_id}``."""++ @app.get(+ "/api/sessions",+ tags=["enterprise history"],+ summary="企业旁路会话列表(ChatHistoryStore;兼容 Web Pod)",+ include_in_schema=True,+ )+ async def sessions_list(+ request: Request,+ limit: int = Query(20, ge=1, le=100),+ offset: int = Query(0, ge=0),+ user: str | None = Query(None),+ ) -> JSONResponse:+ from jiuwenswarm.channels.web.history_store import list_sessions_sync++ user_q = (user or "").strip() or None+ if user_q is None:+ hdr = request.headers.get("x-user-id")+ if hdr and str(hdr).strip():+ user_q = str(hdr).strip()+ sessions = await asyncio.to_thread(+ list_sessions_sync,+ None,+ limit=limit,+ offset=offset,+ user=user_q,+ )+ return JSONResponse({"sessions": sessions})++ @app.get(+ "/api/sessions/{session_id}",+ tags=["enterprise history"],+ summary="企业旁路会话详情(瘦对白 messages)",+ include_in_schema=True,+ )+ async def sessions_detail(+ request: Request,+ session_id: str,+ user: str | None = Query(None),+ ) -> JSONResponse:+ from jiuwenswarm.channels.web.history_store import get_session_detail_sync++ sid = str(session_id or "").strip()+ if not sid:+ return JSONResponse({"error": "missing_session_id"}, status_code=400)+ user_q = (user or "").strip() or None+ if user_q is None:+ hdr = request.headers.get("x-user-id")+ if hdr and str(hdr).strip():+ user_q = str(hdr).strip()+ detail = await asyncio.to_thread(+ get_session_detail_sync,+ sid,+ None,+ user=user_q,+ )+ if detail is None:+ return JSONResponse({"error": "not_found"}, status_code=404)+ return JSONResponse(detail)++ logger.info(+ "[WebHTTP] registered enterprise history compat routes "+ "GET /api/sessions , GET /api/sessions/{session_id} "+ "(AGENT_RUNTIME=%s)",+ bool(os.getenv("AGENT_RUNTIME", "").strip()),+ )+++def catalog_sessions_compat_entries() -> list[dict[str, Any]]:+ return [+ {+ "http_method": "GET",+ "path": "/api/sessions",+ "rpc_method": None,+ "phase": "compat",+ "note": "企业旁路历史列表 → ChatHistoryStore(非 RPC session.list)",+ },+ {+ "http_method": "GET",+ "path": "/api/sessions/{session_id}",+ "rpc_method": None,+ "phase": "compat",+ "note": "企业旁路历史详情 → ChatHistoryStore",+ },+ ]diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_http_transport.pynew file mode 100644index 0000000000..97089df097--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_transport.py@@ -0,0 +1,94 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Gateway Web HTTP listener lifecycle (uvicorn + FastAPI)."""++from __future__ import annotations++import asyncio+import logging+from typing import Any++logger = logging.getLogger(__name__)+++class WebHttpTransport:+ """Owns uvicorn server state; does not inherit from WebSocket channel."""++ def __init__(self, channel: Any) -> None:+ self._channel = channel+ self._http_server: Any = None+ self._http_task: asyncio.Task[Any] | None = None+ self._http_port: int | None = None++ @property+ def port(self) -> int | None:+ """Listen port when running; otherwise None."""+ return self._http_port++ async def start(self, *, host: str | None = None, port: int | None = None) -> bool:+ """Start Gateway Web HTTP (REST + SSE). Returns False on failure (non-fatal)."""+ from jiuwenswarm.gateway.channel_manager.web.web_http_server import (+ resolve_web_http_port,+ start_web_http_server,+ )++ if self._http_task is not None and not self._http_task.done():+ logger.warning("Web HTTP 已在运行 port=%s", self._http_port)+ return True++ config = self._channel.config+ bind_host = host if host is not None else config.host+ bind_port = int(port) if port is not None else config.http_port+ try:+ server, task = await start_web_http_server(+ self._channel,+ host=bind_host,+ port=bind_port,+ )+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "Web HTTP 启动失败(非致命)host=%s port=%s: %s",+ bind_host,+ bind_port,+ exc,+ )+ self._http_server = None+ self._http_task = None+ self._http_port = None+ return False++ self._http_server = server+ self._http_task = task+ self._http_port = bind_port++ def _on_http_task_done(done_task: asyncio.Task[Any]) -> None:+ if done_task.cancelled():+ return+ exc = done_task.exception()+ if exc is not None:+ logger.error("[WebHTTP] server task exited: %s", exc, exc_info=exc)+ else:+ logger.warning("[WebHTTP] server task exited unexpectedly")+ if self._http_task is done_task:+ self._http_server = None+ self._http_task = None+ self._http_port = None++ task.add_done_callback(_on_http_task_done)+ return True++ async def stop(self) -> None:+ """Stop Gateway Web HTTP and clear in-flight request outbounds."""+ from jiuwenswarm.gateway.channel_manager.web.web_http_server import stop_web_http_server++ server, task = self._http_server, self._http_task+ self._http_server = None+ self._http_task = None+ self._http_port = None+ await self._channel.delivery.clear()+ if server is None and task is None:+ return+ try:+ await stop_web_http_server(server, task)+ except Exception: # noqa: BLE001+ logger.debug("Web HTTP stop failed", exc_info=True)diff --git a/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.py b/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.pynew file mode 100644index 0000000000..b362c1ea63--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_rpc_host.py@@ -0,0 +1,314 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Transport-agnostic Web RPC host: method registry, history capture, handler invoke."""++from __future__ import annotations++import inspect+import ipaddress+import json+import logging+import os+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Awaitable, Callable+from urllib.parse import urlparse++import aiohttp++from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.gateway.channel_manager.web.file_http import (+ is_path_under_directory,+ safe_filename,+)+from jiuwenswarm.common.ws_diagnostics import (+ describe_ws_exception,+ describe_ws_peer,+ format_ws_diagnostics,+)++logger = logging.getLogger(__name__)++MethodHandler = Callable[..., Awaitable[None]]+ConnectHook = Callable[..., Any]++HANDLER_BEFORE_CALLBACK_METHODS = frozenset({ReqMethod.CHAT_SEND.value})+_MAX_DOWNLOAD_BYTES = 32 * 1024 * 1024+++def _is_url_safe_for_fetch(url: str) -> bool:+ parsed = urlparse(str(url or "").strip())+ if parsed.scheme not in {"http", "https"}:+ return False+ host = (parsed.hostname or "").strip().lower()+ if not host:+ return False+ if host in {"localhost", "metadata.google.internal"} or host.endswith((".local", ".internal")):+ return False+ try:+ ip = ipaddress.ip_address(host)+ except ValueError:+ return True+ return not (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_reserved+ or ip.is_multicast+ )+++@dataclass(frozen=True)+class MethodHandlerInvocation:+ ws: Any+ method: str+ req_id: str+ params: dict[str, Any]+ session_id: str+ handler: MethodHandler+++class WebRpcHost:+ """Shared business host for WS and HTTP transports."""++ def __init__(self, channel: Any) -> None:+ self._channel = channel+ self._method_handlers: dict[str, MethodHandler] = {}+ self._on_message_cb: Callable[[Any], Any] | None = None+ self._connect_hooks: list[ConnectHook] = []+ self._disconnect_hooks: list[ConnectHook] = []+ self._history_runner: Any = None++ @property+ def method_handlers(self) -> dict[str, MethodHandler]:+ return self._method_handlers++ @property+ def on_message_cb(self) -> Callable[[Any], Any] | None:+ return self._on_message_cb++ @on_message_cb.setter+ def on_message_cb(self, value: Callable[[Any], Any] | None) -> None:+ self._on_message_cb = value++ def register_method(self, method: str, handler: MethodHandler) -> None:+ self._method_handlers[method] = handler++ def on_connect(self, callback: ConnectHook) -> None:+ self._connect_hooks.append(callback)++ def on_disconnect(self, callback: ConnectHook) -> None:+ self._disconnect_hooks.append(callback)++ def on_message(self, callback: Callable[[Any], None]) -> None:+ self._on_message_cb = callback++ def wrap_message_callback(+ self,+ wrapper: Callable[[Callable[[Any], Any] | None, Any], Any],+ ) -> None:+ original = self._on_message_cb++ def wrapped(msg: Any) -> Any:+ return wrapper(original, msg)++ self._on_message_cb = wrapped++ @property+ def connect_hooks(self) -> list[ConnectHook]:+ return self._connect_hooks++ @property+ def disconnect_hooks(self) -> list[ConnectHook]:+ return self._disconnect_hooks++ def maybe_start_history_capture(self) -> None:+ """Enterprise: capture frames on Listen for ``GET /api/sessions*``."""+ if self._history_runner is not None:+ return+ if not os.getenv("AGENT_RUNTIME", "").strip():+ return+ try:+ from jiuwenswarm.channels.web.history_store import (+ ChatHistoryStore,+ HistoryFrameRunner,+ set_default_store,+ )++ store = ChatHistoryStore.from_env()+ set_default_store(store)+ if not store.available:+ logger.warning(+ "WebChannel 会话历史不可用(MySQL 缺 WEB_DB_HOST 或库类型不支持)",+ )+ return+ runner = HistoryFrameRunner(store)+ runner.start()+ self._history_runner = runner+ if store.backend == "mysql" and store.mysql_settings is not None:+ s = store.mysql_settings+ logger.info(+ "WebChannel enterprise history capture: mysql %s:%s/%s",+ s.host, s.port, s.database,+ )+ else:+ logger.info(+ "WebChannel enterprise history capture: %s db=%s",+ store.backend, store.db_path,+ )+ except Exception:+ logger.warning("WebChannel 启动会话历史采集失败", exc_info=True)++ def shutdown(self) -> None:+ runner = self._history_runner+ if runner is None:+ return+ try:+ runner.stop()+ except Exception: # noqa: BLE001+ logger.debug("WebChannel history runner stop failed", exc_info=True)+ self._history_runner = None++ def record_history_frame(self, direction: str, data: Any) -> None:+ runner = self._history_runner+ if runner is None or data is None:+ return+ try:+ if isinstance(data, bytes):+ raw = data.decode("utf-8", errors="replace")+ elif isinstance(data, dict):+ raw = json.dumps(data, ensure_ascii=False)+ else:+ raw = str(data)+ runner.submit(direction, raw)+ except Exception:+ logger.debug("WebChannel history submit failed dir=%s", direction, exc_info=True)++ async def invoke_method_handler(self, invocation: MethodHandlerInvocation) -> bool:+ ws_transport = self._channel.ws+ kwargs: dict[str, Any] = {}+ if "user_id" in inspect.signature(invocation.handler).parameters:+ kwargs["user_id"] = ws_transport.connection_user_id(invocation.ws)+ try:+ await invocation.handler(+ invocation.ws,+ invocation.req_id,+ invocation.params,+ invocation.session_id,+ **kwargs,+ )+ return True+ except Exception as e:+ ws_closed = bool(getattr(invocation.ws, "closed", False))+ if ws_closed:+ logger.warning(+ "WebChannel method handler aborted on closed websocket: %s",+ format_ws_diagnostics(+ {+ "method": invocation.method,+ "id": invocation.req_id,+ "session_id": invocation.session_id,+ },+ describe_ws_peer(invocation.ws),+ describe_ws_exception(e),+ ),+ )+ return False++ logger.error(+ "WebChannel method handler error: %s",+ format_ws_diagnostics(+ {+ "method": invocation.method,+ "id": invocation.req_id,+ "session_id": invocation.session_id,+ },+ describe_ws_peer(invocation.ws),+ describe_ws_exception(e),+ ),+ )+ try:+ await self._channel.send_response(+ invocation.ws, invocation.req_id, ok=False,+ error=f"handler error: {e}", code="INTERNAL_ERROR",+ )+ except Exception as send_err:+ logger.warning(+ "WebChannel failed to send handler error response ({}): {}",+ invocation.method, send_err,+ )+ return False++ async def download_file(self, url: str) -> bytes | None:+ if not _is_url_safe_for_fetch(url):+ logger.warning("WebChannel blocked unsafe file URL: %s", url)+ return None+ timeout = aiohttp.ClientTimeout(total=60)+ try:+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(url, allow_redirects=True, max_redirects=3) as response:+ if response.status != 200:+ logger.warning(+ "WebChannel 文件下载失败: %s, 状态码: %s", url, response.status,+ )+ return None+ content = await response.read()+ if len(content) > _MAX_DOWNLOAD_BYTES:+ logger.warning(+ "WebChannel 文件下载过大: %s, bytes=%s", url, len(content),+ )+ return None+ return content+ except Exception as e:+ logger.warning("WebChannel 文件下载异常: %s, 错误: %s", url, e)+ return None++ async def process_files(self, params: dict[str, Any]) -> dict[str, Any]:+ files = params.get("files")+ if not files or not isinstance(files, list):+ return params++ strip_path_for_url = bool(os.getenv("AGENT_RUNTIME", "").strip())+ downloaded_files = []+ workspace = Path(get_agent_workspace_dir()).resolve()++ for file_info in files:+ if not isinstance(file_info, dict):+ downloaded_files.append(file_info)+ continue++ file_url = file_info.get("url") or file_info.get("uri") or ""+ file_name = safe_filename(+ str(file_info.get("name") or file_info.get("filename") or "unknown_file"),+ default="unknown_file",+ )++ if file_url and strip_path_for_url:+ updated = dict(file_info)+ updated["url"] = file_url+ updated.pop("path", None)+ downloaded_files.append(updated)+ continue++ if file_url:+ file_content = await self.download_file(file_url)+ if file_content:+ try:+ workspace.mkdir(parents=True, exist_ok=True)+ file_path = (workspace / file_name).resolve()+ if not is_path_under_directory(workspace, file_path):+ logger.warning(+ "WebChannel blocked unsafe attachment path: %s", file_name,+ )+ downloaded_files.append(file_info)+ continue+ file_path.write_bytes(file_content)+ file_info["path"] = str(file_path)+ except Exception as e:+ logger.warning("WebChannel 文件保存失败: %s", e)++ downloaded_files.append(file_info)++ params["files"] = downloaded_files+ return paramsdiff --git a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.pynew file mode 100644index 0000000000..6b9bd96f96--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py@@ -0,0 +1,1293 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""WebSocket transport for browser WebChannel (extends BaseWsChannel)."""++from __future__ import annotations++import asyncio+import inspect+import json+import logging+import os+import secrets+import time+import uuid+from dataclasses import dataclass+from typing import Any, Awaitable, Callable+from urllib.parse import parse_qs, urlparse++import aiohttp+from websockets.exceptions import ConnectionClosed as WebSocketConnectionClosed++from jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.gateway.channel_manager.base import ChannelMetadata, RobotMessageRouter+from jiuwenswarm.gateway.routing.base_ws_channel import BaseWsChannel+from jiuwenswarm.gateway.routing.keys import AgentRef, RoutingKey+from jiuwenswarm.gateway.routing.session_sharing import RoutingTarget+from jiuwenswarm.common.security.ws_origin import (+ extract_handshake_request,+ forbidden_origin_response,+ get_header_value,+ is_origin_check_enabled,+ is_allowed_browser_origin,+)+from jiuwenswarm.common.request_ext import (+ attach_to_metadata as _ext_attach,+ build_ext_from_source as _ext_build,+ set_current as _ext_set,+)+from jiuwenswarm.common.schema.message import EventType, Message, Mode, ReqMethod+from jiuwenswarm.common.ws_diagnostics import (+ describe_ws_exception,+ describe_ws_peer,+ format_ws_diagnostics,+)++logger = logging.getLogger(__name__)++_WEB_CONNECTION_USER_ID_ATTR = "_web_connection_user_id"++_HANDLER_BEFORE_CALLBACK_METHODS = frozenset({ReqMethod.CHAT_SEND.value})++_STREAM_COALESCE_EVENT_TYPES = frozenset({"chat.delta", "chat.reasoning"})+_STREAM_COALESCE_MAX_FRAMES = 32++_WEB_FULL_PAYLOAD_EVENT_TYPES = frozenset(+ {+ "connection.ack",+ "todo.updated",+ "task.start",+ "task.update",+ "task.complete",+ "chat.tool_call",+ "chat.tool_update",+ "chat.tool_result",+ "chat.processing_status",+ "chat.interrupt_result",+ "chat.evolution_status",+ "chat.error",+ "heartbeat.relay",+ "context.usage",+ "context.compression_state",+ "chat.ask_user_question",+ "chat.subtask_update",+ "chat.symphony_status",+ "chat.notice",+ "history.message",+ "chat.session_result",+ "chat.usage_metadata",+ "chat.usage_summary",+ "chat.file",+ "chat.retract",+ "security.alert",+ "goal.snapshot",+ "goal.updated",+ "runtime.accepted",+ "execution.error",+ "proactive_recommendation",+ }+)++# ── 类型别名 ──────────────────────────────────────────────+# 方法处理器签名: (ws, req_id, params, session_id) -> None+MethodHandler = Callable[..., Awaitable[None]]+# 连接钩子签名: (ws) -> None | Awaitable[None]+ConnectHook = Callable[..., Any]+++@dataclass(init=False)+class WebChannelConfig:+ """WebChannel bind settings (WS + HTTP are separate listeners)."""++ enabled: bool+ host: str+ ws_port: int+ http_port: int+ path: str+ allow_from: list[str]++ def __init__(+ self,+ *,+ enabled: bool = False,+ host: str = "127.0.0.1",+ ws_port: int | None = None,+ http_port: int | None = None,+ path: str = "/ws",+ allow_from: list[str] | None = None,+ port: int | None = None,+ ) -> None:+ if port is not None:+ ws_port = port+ if ws_port is None:+ ws_port = 19000+ self.enabled = enabled+ self.host = host+ self.ws_port = int(ws_port)+ 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.__post_init__()++ def __post_init__(self) -> None:+ from jiuwenswarm.gateway.channel_manager.web.web_http_server import (+ resolve_web_http_port,+ )++ self.http_port = resolve_web_http_port(self.ws_port, http_port=self.http_port)++ @property+ def port(self) -> int:+ """Legacy alias for ``ws_port`` (``WEB_PORT`` / ``--port``)."""+ return self.ws_port+++class WebWsTransport(BaseWsChannel):+ """WebSocket listener and frame protocol; business RPC lives on ``WebRpcHost``."""++ name = "web"+ channel_id = "web"++ def __init__(+ self,+ config: WebChannelConfig,+ router: RobotMessageRouter,+ owner: Any,+ ) -> None:+ super().__init__(config, router)+ self._owner = owner+ self.config: WebChannelConfig = config+ self._server: Any = None+ # ws -> set[session_id]: 追踪每个连接上活跃的 session+ self._ws_sessions: dict[int, set[str]] = {}+ # session_id -> is_processing+ self._session_busy: dict[str, bool] = {}++ @staticmethod+ def _coalescible_stream_frame(+ frame: Any,+ ) -> tuple[dict[str, Any], str] | None:+ """Return (decoded frame, content) for a merge-safe stream frame.++ 帧已是 dict(入队时不预序列化),故无需 json.loads;返回 decoded 与+ content 供 _coalesce 直接在 dict 层合并,省去 str↔dict 往返。+ """+ if not isinstance(frame, dict) or frame.get("type") != "event":+ return None+ if frame.get("event") not in _STREAM_COALESCE_EVENT_TYPES:+ return None+ payload = frame.get("payload")+ if not isinstance(payload, dict):+ return None+ content = payload.get("content")+ if not isinstance(content, str):+ return None+ return frame, content++ @staticmethod+ def _same_stream_identity(+ a: dict[str, Any],+ b: dict[str, Any],+ ) -> bool:+ """两帧除 payload.content 外是否同流(可合并)。++ 逐键比对 payload 非 content 字段 + 外层 event 等键,避免构造 comparable+ dict 副本与整 dict 哈希比对的开销。+ """+ a_payload = a["payload"]+ b_payload = b["payload"]+ if a.get("event") != b.get("event"):+ return False+ if a.get("type") != b.get("type"):+ return False+ for key in set(a_payload) | set(b_payload):+ if key == "content":+ continue+ if a_payload.get(key) != b_payload.get(key):+ return False+ return True++ def _coalesce(+ self,+ first_frame: Any,+ queue: asyncio.Queue,+ ) -> list[Any]:+ """Merge only contiguous stream frames with identical non-content data."""+ parsed = self._coalescible_stream_frame(first_frame)+ if parsed is None:+ return [first_frame]++ decoded, merged_content = parsed+ merged_count = 1+ trailing: list[Any] = []++ while merged_count < _STREAM_COALESCE_MAX_FRAMES:+ try:+ candidate = queue.get_nowait()+ except asyncio.QueueEmpty:+ break+ if candidate is None:+ trailing.append(None)+ break+ candidate_parsed = self._coalescible_stream_frame(candidate)+ if (+ candidate_parsed is None+ or not self._same_stream_identity(decoded, candidate_parsed[0])+ ):+ trailing.append(candidate)+ break+ merged_content += candidate_parsed[1]+ merged_count += 1++ if merged_count == 1:+ return [first_frame, *trailing]++ merged_payload = {**decoded["payload"], "content": merged_content}+ return [{**decoded, "payload": merged_payload}, *trailing]++ # ── 公共属性 ──────────────────────────────────────────++ @property+ def clients(self) -> set[Any]:+ """当前活跃的 WebSocket 客户端集合(从 _clients_by_key 推导,只读副本)."""+ result: set[Any] = set()+ for ws_list in self._clients_by_key.values():+ result.update(ws_list)+ return result++ def lookup_ws_by_id(self, peer_id: str) -> Any | None:+ pid = str(peer_id or "").strip()+ if not pid:+ return None+ ws = self._ws_by_id.get(pid)+ if ws is not None and not getattr(ws, "closed", False):+ return ws+ return None++ def peers_for_session_ws(self, session_id: str) -> set[Any]:+ peers: set[Any] = set()+ sid = str(session_id or "").strip()+ if not sid:+ return peers+ for rk, ws_list in self._clients_by_key.items():+ if rk.session_id == sid:+ for w in ws_list:+ if not getattr(w, "closed", False):+ peers.add(w)+ return peers++ @property+ def ws_sessions(self) -> dict[int, set[str]]:+ return self._ws_sessions++ @property+ def send_queues(self) -> dict[str, "asyncio.Queue[str | bytes | None]"]:+ return self._send_queues++ def coalesce(+ self,+ first_frame: Any,+ queue: asyncio.Queue,+ ) -> list[Any]:+ return self._coalesce(first_frame, queue)++ async def writer_loop(self, ws: Any, ws_id: str) -> None:+ await self._writer_loop(ws, ws_id)++ async def handle_raw_message(+ self,+ ws: Any,+ raw: str,+ query: dict[str, list[str]],+ ) -> None:+ await self._handle_raw_message(ws, raw, query)++ # ── 帧发送 API(公开给处理器使用)─────────────────────++ async def send_response(+ self,+ ws: Any,+ req_id: str,+ *,+ ok: bool,+ payload: dict[str, Any] | None = None,+ error: str | None = None,+ code: str | None = None,+ ) -> None:+ """向指定客户端发送 ``res`` 帧."""+ frame: dict[str, Any] = {+ "type": "res",+ "id": req_id,+ "ok": ok,+ "payload": payload or {},+ }+ if not ok:+ frame["error"] = error or "request failed"+ if code:+ frame["code"] = code+ try:+ self._enqueue_send(ws, frame)+ except Exception as e:+ if bool(getattr(ws, "closed", False)):+ logger.debug(+ "WebChannel send_response skipped on closed websocket: %s",+ format_ws_diagnostics(+ {"id": req_id},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )+ return+ raise++ async def send_event(+ self,+ ws: Any,+ event: str,+ payload: dict[str, Any],+ *,+ seq: int | None = None,+ stream_id: str | None = None,+ ) -> None:+ """向指定客户端发送 ``event`` 帧."""+ frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}+ if seq is not None:+ frame["seq"] = seq+ if stream_id is not None:+ frame["stream_id"] = stream_id+ try:+ self._enqueue_send(ws, frame)+ except Exception as e:+ if bool(getattr(ws, "closed", False)):+ logger.debug(+ "WebChannel send_event skipped on closed websocket: %s",+ format_ws_diagnostics(+ {"event": event, "seq": seq, "stream_id": stream_id},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )+ return+ raise++ def _lookup_peer(self, peer_id: str) -> Any | None:+ return self._owner.lookup_peer(peer_id)++ def _peers_for_session(self, session_id: str) -> set[Any]:+ return self._owner.peers_for_session(session_id)++ def _record_history_frame(self, direction: str, data: Any) -> None:+ self._owner.rpc.record_history_frame(direction, data)++ def _enqueue_send(self, ws: Any, data: Any) -> None:+ self._record_history_frame("uplink", data)+ if getattr(ws, "is_http_outbound", False):+ from jiuwenswarm.gateway.channel_manager.web.outbound import _normalize_frame++ frame = _normalize_frame(data)+ if frame is None:+ return+ accept = getattr(ws, "accept_frame", None)+ if callable(accept):+ accept(frame)+ return+ super()._enqueue_send(ws, data)++ @staticmethod+ def _extract_query_user_id(flat_query: dict[str, str]) -> str | None:+ uid = str(flat_query.get("user_id", "") or "").strip()+ return uid or None++ @staticmethod+ def _extract_ws_header_user_id(ws: Any) -> str | None:+ headers = (+ getattr(getattr(ws, "request", None), "headers", None)+ or getattr(ws, "request_headers", None)+ )+ raw = get_header_value(headers, "X-User-Id")+ if raw is None:+ return None+ text = str(raw).strip()+ return text or None++ @classmethod+ def _resolve_connection_user_id(cls, flat_query: dict[str, str], ws: Any) -> str | None:+ connection_user_id = cls._extract_query_user_id(flat_query) or cls._extract_ws_header_user_id(ws)+ setattr(ws, _WEB_CONNECTION_USER_ID_ATTR, connection_user_id)+ return connection_user_id++ @staticmethod+ def connection_user_id(ws: Any) -> str | None:+ """返回 Web 连接建立时缓存的 user_id(query 或 X-User-Id Header)。"""+ uid = getattr(ws, _WEB_CONNECTION_USER_ID_ATTR, None)+ if uid is None:+ return None+ text = str(uid).strip()+ return text or None++ @staticmethod+ def _routing_key_user_id(connection_user_id: str | None, remote: Any) -> str:+ if connection_user_id:+ return connection_user_id+ return str(remote or "unknown")++ @classmethod+ def _resolve_ws_identity(+ cls,+ ws: Any,+ flat_query: dict[str, str],+ remote: Any,+ *,+ route_type: str = "ws",+ ) -> tuple[str | None, str]:+ """解析 ws 连接身份,供 /ws 和 /ws/git 共用(设计文档 §5.3.7)。++ Args:+ route_type: ``"ws"`` 主路由或 ``"git"`` /ws/git 路由,仅用于日志区分。++ Returns:+ ``(connection_user_id, routing_key_user_id)``+ """+ connection_user_id = cls._resolve_connection_user_id(flat_query, ws)+ routing_key_user_id = cls._routing_key_user_id(connection_user_id, remote)+ return connection_user_id, routing_key_user_id++ async def broadcast_event(+ self,+ event: str,+ payload: dict[str, Any],+ *,+ seq: int | None = None,+ stream_id: str | None = None,+ exclude_ws: Any = None,+ ) -> None:+ """向所有已连接客户端广播 ``event`` 帧.++ exclude_ws: 排除单个发起方 ws(如 config.changed 的保存发起方),+ 避免发起方收到自身触发的广播而误弹「丢弃草稿」确认框。发起方靠+ 保存响应的本地乐观合并自行刷新,无需这条广播。+ """+ frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}+ if seq is not None:+ frame["seq"] = seq+ if stream_id is not None:+ frame["stream_id"] = stream_id+ clients = self.clients+ if exclude_ws is not None:+ clients = {c for c in clients if c is not exclude_ws}+ await self._broadcast_to(frame, clients)++ # ── WebSocket 生命周期 ──────────────────────────────────++ async def start(self) -> None:+ await self.start_ws_server()++ async def stop(self) -> None:+ await self.stop_ws_server()++ async def start_ws_server(self) -> None:+ if self._running:+ logger.warning("WebWsTransport 已在运行")+ return+ if not self.config.enabled:+ logger.warning("WebWsTransport 未启用(enabled=False)")+ return++ try:+ from websockets.legacy.server import serve as ws_serve+ except Exception: # pragma: no cover+ import websockets++ ws_serve = websockets.serve++ from jiuwenswarm.common.ws_limits import WEB_WS_MAX_MESSAGE_BYTES++ self._server = await ws_serve(+ self._connection_handler,+ self.config.host,+ self.config.ws_port,+ process_request=self._process_request,+ ping_interval=20,+ ping_timeout=60,+ max_size=WEB_WS_MAX_MESSAGE_BYTES,+ )+ self._running = True+ logger.info(+ f"WebChannel WS 已启动: ws://{self.config.host}:{self.config.ws_port}{self.config.path}"+ )++ async def wait_closed(self) -> None:+ if self._server is not None:+ await self._server.wait_closed()++ async def stop_ws_server(self) -> None:+ """Stop WebSocket server and clean up connections."""+ self._running = False+ all_clients = list(self.clients)+ close_tasks = [client.close(code=1001, reason="server shutdown") for client in all_clients]+ if close_tasks:+ await asyncio.gather(*close_tasks, return_exceptions=True)+ self._clients_by_key.clear()++ if self._server is not None:+ self._server.close()+ await self._server.wait_closed()+ self._server = None+ # 兜底清理未走正常断连路径的 writer 协程(正常断连已由 unregister_ws 清理)+ await self._shutdown_all_writers()+ logger.info("WebChannel WS 已停止")++ async def _process_request(self, *args: Any) -> Any:+ """在握手阶段执行 Origin 校验,兼容 legacy/new websockets APIs。"""+ path, request_headers = extract_handshake_request(args)+ origin = get_header_value(request_headers, "Origin")+ enable_origin_check = is_origin_check_enabled()+ if not enable_origin_check:+ logger.info(+ "WebChannel 握手检查 path=%s origin=%s enable_origin_check=%s allowed=%s",+ path,+ origin,+ enable_origin_check,+ True,+ )+ return None++ allowed = is_allowed_browser_origin(origin)+ logger.info(+ "WebChannel 握手检查 path=%s origin=%s enable_origin_check=%s allowed=%s",+ path,+ origin,+ enable_origin_check,+ allowed,+ )+ if allowed:+ return None++ logger.warning(+ "WebChannel 握手拒绝 path=%s origin=%s reason=origin_not_allowed",+ path,+ origin,+ )+ return forbidden_origin_response(args)++ @staticmethod+ def _should_preserve_full_payload(event_name: str) -> bool:+ return (+ event_name in _WEB_FULL_PAYLOAD_EVENT_TYPES+ or event_name.startswith("team.")+ or event_name.startswith("harness.")+ )++ @classmethod+ def _build_event_payload(cls, msg: Message, event_name: str) -> dict[str, Any]:+ """Build the Web event payload without dropping structured control fields."""+ if isinstance(msg.payload, dict):+ if cls._should_preserve_full_payload(event_name):+ payload = {**msg.payload}+ if "session_id" not in payload and msg.session_id:+ payload["session_id"] = msg.session_id+ if event_name.startswith("chat.") and "request_id" not in payload and msg.id:+ payload["request_id"] = msg.id+ return payload++ content = str(msg.payload.get("content", "") or "")+ if not content and not getattr(msg, "ok", True) and msg.payload.get("error"):+ content = str(msg.payload.get("error", ""))+ payload = {+ "session_id": msg.session_id,+ "content": content,+ }+ for _key in ("role", "member_name", "member_action", "source_channel", "user_id", "display_name"):+ _val = msg.payload.get(_key)+ if _val is not None:+ payload[_key] = _val+ if event_name == "chat.final":+ cron_extra = msg.payload.get("cron")+ if isinstance(cron_extra, dict):+ payload["cron"] = cron_extra+ source = msg.payload.get("source")+ if source:+ payload["source"] = source+ ptype = msg.payload.get("proactive_type")+ if ptype:+ payload["proactive_type"] = ptype+ if source == "proactive_recommendation":+ logger.info(+ "[WebChannel] proactive push frame: source=%s proactive_type=%s "+ "content_len=%d payload_keys=%s",+ source, ptype, len(str(payload.get("content", ""))), list(payload.keys()),+ )+ return payload++ content = str((msg.params or {}).get("content", "") or "")+ return {+ "session_id": msg.session_id,+ "content": content,+ }++ async def send(+ self,+ msg: Message,+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """向客户端发送消息。++ V2: 当 routing_target 非空时,按其 routing_keys 精确路由(_clients_by_key)。+ 否则回退到全量广播(向后兼容)。+ """+ _pl = getattr(msg, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ _has_fanout = bool((getattr(msg, "metadata", None) or {}).get("fan_out_targets"))+ logger.debug(+ "[WebChannel] send() called: id=%s event_type=%s payload_et=%s has_fanout=%s"+ " has_routing_target=%s client_count=%s",+ getattr(msg, "id", ""), getattr(msg, "event_type", None), _et,+ _has_fanout, routing_target is not None, len(self.clients),+ )+ # ── 心跳 relay:临时 session_id(heartbeat_{ts}_{suffix})不匹配任何前端连接,+ # 按常规 session_id 路由会被当作"无连接"丢弃。心跳状态是全局的(非会话级),+ # 前端 setHeartbeatStatus 也是全局 store,因此直接广播给所有 web 客户端。+ # 与 wechat 等 IM 渠道在 send() 中对 HEARTBEAT_RELAY 的专属分支对齐。+ if msg.event_type == EventType.HEARTBEAT_RELAY:+ frame = self._serialize_frame(msg, None) # 返回 dict,由 writer 统一序列化+ clients = self.clients+ for w in clients:+ self._enqueue_send(w, frame)+ logger.debug(+ "[WebChannel] heartbeat.relay broadcast to %d client(s) id=%s",+ len(clients), getattr(msg, "id", ""),+ )+ return++ # ── 定时任务推 web:原设计绑定 job.session_id,但关闭 tab/换设备后旧会话再无连接,+ # 按 session_id 路由会被丢弃。cron 推送(占位 + 结果)带 payload.cron 标记,普通对话+ # chat.final 不带,以此为识别条件广播给所有 web 客户端。前端 _push_to_targets 已对 web+ # 置空 session_id,shouldHandleSessionEvent 放行,消息进当前活跃会话流(含 placeholder 替换)。+ if (+ msg.event_type == EventType.CHAT_FINAL+ and isinstance(msg.payload, dict)+ and isinstance(msg.payload.get("cron"), dict)+ ):+ frame = self._serialize_frame(msg, None) # 返回 dict,由 writer 统一序列化+ clients = self.clients+ for w in clients:+ self._enqueue_send(w, frame)+ logger.debug(+ "[WebChannel] cron push broadcast to %d client(s) id=%s run_id=%s",+ len(clients), getattr(msg, "id", ""),+ (msg.payload.get("cron") or {}).get("run_id", ""),+ )+ return++ # ── 主动推荐系统通知推 web:与 cron 推送同理——后端主动推、无前端 session_id 绑定,+ # 按 session_id 路由会被当"无 session"丢弃(旧路径 580 行 if not msg.session_id 兜底丢弃)。+ # proactive notification("今日已达上限"等系统提醒)带 payload.source ==+ # "proactive_notification" 标记,据此广播给所有 web 客户端。前端 shouldHandleSessionEvent+ # 对无 session_id 的 payload 放行,作为普通 assistant 消息渲染。+ if (+ msg.event_type == EventType.CHAT_FINAL+ and isinstance(msg.payload, dict)+ and msg.payload.get("source") == "proactive_notification"+ ):+ frame = self._serialize_frame(msg, None) # 返回 dict,由 writer 统一序列化+ clients = self.clients+ for w in clients:+ self._enqueue_send(w, frame)+ logger.debug(+ "[WebChannel] proactive_notification broadcast to %d client(s) id=%s",+ len(clients), getattr(msg, "id", ""),+ )+ return++ if msg.type == "res":+ if isinstance(msg.payload, dict):+ res_payload = {**msg.payload}+ elif msg.payload is None:+ res_payload = {}+ else:+ res_payload = {"content": str(msg.payload)}++ frame: dict[str, Any] = {+ "type": "res",+ "id": msg.id,+ "ok": bool(msg.ok),+ "payload": res_payload,+ }+ if not msg.ok:+ # Prefer explicit error; fall back to message (e.g. command.goal+ # unary failures put the human-readable text in payload.message).+ error_text = res_payload.get("error") or res_payload.get("message")+ if isinstance(error_text, str) and error_text:+ frame["error"] = error_text+ code_text = res_payload.get("code")+ if isinstance(code_text, str) and code_text:+ frame["code"] = code_text++ ws_set: set[Any] = set()+ metadata = msg.metadata if isinstance(msg.metadata, dict) else {}+ request_ws_id = str(metadata.get("ws_id") or "").strip()+ if request_ws_id:+ ws = self._lookup_peer(request_ws_id)+ if ws is not None:+ ws_set.add(ws)++ if not ws_set and routing_target is not None:+ delivery = routing_target.delivery+ if delivery is not None:+ ws_id = getattr(delivery, "ws_id", "")+ if ws_id:+ ws = self._lookup_peer(str(ws_id))+ if ws is not None:+ ws_set.add(ws)+ if not ws_set:+ for rk in routing_target.routing_keys:+ ws_list = self._clients_by_key.get(rk) or []+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)++ if not ws_set and msg.session_id:+ ws_set |= self.peers_for_session_ws(msg.session_id)++ if not ws_set:+ logger.debug(+ "[WebChannel] response route miss: ws_id=%s session_id=%s id=%s",+ request_ws_id,+ msg.session_id,+ getattr(msg, "id", ""),+ )+ return+ await self._broadcast_to(frame, ws_set)+ return++ # ── V2 精确路由 ──+ if routing_target is not None:+ routing_keys = routing_target.routing_keys+ member_names = list(routing_target.member_names)++ # ── 优先:按 delivery.ws_id 物理寻址 ──+ ws_set: set[Any] = set()+ delivery = routing_target.delivery+ if delivery is not None:+ ws_id = getattr(delivery, "ws_id", "")+ if ws_id:+ ws = self._lookup_peer(str(ws_id))+ if ws is not None:+ ws_set.add(ws)++ # ── 兜底:按 routing_keys 5 维逻辑查 _clients_by_key ──+ if not ws_set and routing_keys:+ for rk in routing_keys:+ ws_list = self._clients_by_key.get(rk) or []+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)+ if ws_set:+ frame_data = self._serialize_frame(msg, routing_target, member_names=member_names)+ for w in ws_set:+ self._enqueue_send(w, frame_data)+ return+ # V2 精确路由未命中 —— 回退到 session_id 路由+ logger.debug(+ "[WebChannel] V2 routing miss: looked up %d routing_keys + ws_id=%s,"+ " ws_set empty — falling back to session_id=%s",+ len(routing_keys), getattr(delivery, "ws_id", "") if delivery else "",+ getattr(msg, "session_id", ""),+ )++ # ── 旧路径:优先按请求 metadata.ws_id 物理寻址,再按 session_id 精确路由 ──+ # 普通 stream event(chat.delta/final/usage_summary 等)由 ChannelManager+ # 调 channel.send(msg),不会携带 RoutingTarget;但原始 Web 请求注入的+ # metadata.ws_id 会经 _chunk_to_message 保留下来。先用它收窄到发起请求的+ # 物理连接,避免同一个 session 桶里的陈旧 ws 一起收到迟到事件。+ ws_set: set[Any] = set()+ metadata = msg.metadata if isinstance(msg.metadata, dict) else {}+ request_ws_id = str(metadata.get("ws_id") or "").strip()+ if request_ws_id:+ ws = self._lookup_peer(request_ws_id)+ if ws is not None:+ ws_set.add(ws)++ if not ws_set and not msg.session_id:+ logger.warning(+ "[WebChannel] msg has no session_id, cannot route -- "+ "dropping msg id=%s to avoid cross-session broadcast",+ getattr(msg, "id", ""),+ )+ return+ if not ws_set:+ ws_set |= self.peers_for_session_ws(msg.session_id)+ if not ws_set:+ logger.debug(+ "[WebChannel] session_id=%s has no connected ws, dropping msg id=%s ws_id=%s",+ msg.session_id, getattr(msg, "id", ""), request_ws_id,+ )+ return+ all_clients = ws_set++ # 确定事件名称+ event_name = "chat.final"+ if msg.event_type is not None:+ event_name = msg.event_type.value+ elif isinstance(msg.payload, dict):+ payload_event_type = msg.payload.get("event_type")+ if isinstance(payload_event_type, str) and payload_event_type.strip():+ event_name = payload_event_type.strip()++ payload = self._build_event_payload(msg, event_name)++ # ── V2: 诊断日志 ──+ if routing_target is not None:+ logger.info(+ "[WebChannel] frame: id=%s event=%s intent=%s",+ getattr(msg, "id", ""), event_name, routing_target.intent,+ )+ if getattr(msg, "agent_ref", None):+ payload["agent_ref"] = msg.agent_ref if isinstance(msg.agent_ref, dict) else {+ "mode": getattr(msg.agent_ref, "mode", ""),+ "id": getattr(msg.agent_ref, "id", ""),+ }++ frame_data: dict[str, Any] = {+ "type": "event",+ "event": event_name,+ "payload": payload,+ }+ await self._broadcast_to(frame_data, all_clients)++ # 维护 session busy 状态(供 /ws/git 写操作查询)+ if event_name == "chat.processing_status" and isinstance(payload, dict):+ sid = payload.get("session_id") or msg.session_id+ if sid:+ self._session_busy[sid] = bool(payload.get("is_processing", False))++ # interrupt_result 根据 intent 决定 is_processing 状态+ if event_name == "chat.interrupt_result":+ intent = payload.get("intent", "cancel") if isinstance(payload, dict) else "cancel"+ is_processing = intent in ("pause", "supplement", "resume")+ # 同步更新 busy 映射+ if msg.session_id:+ self._session_busy[msg.session_id] = is_processing+ await self._broadcast_to({+ "type": "event",+ "event": "chat.processing_status",+ "payload": {"session_id": msg.session_id, "is_processing": is_processing},+ }, all_clients)++ def is_session_busy(self, session_id: str) -> bool:+ """查询 session 是否正在执行(agent 处理中)。++ 基于 ``chat.processing_status`` 事件维护的映射。+ 未跟踪的 session 默认返回 False(不忙碌)。++ 供 /ws/git 写操作(如 ``project.git.discard_turn_changes``)在执行前+ 校验会话非忙碌,避免与正在进行的 agent 文件写入冲突。+ """+ return self._session_busy.get(session_id, False)++ def get_metadata(self) -> ChannelMetadata:+ """获取 Channel 元数据."""+ return ChannelMetadata(+ channel_id=self.channel_id,+ source="websocket",+ extra={"host": self.config.host, "port": self.config.ws_port, "path": self.config.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)+ request_path = parsed.path or raw_path+ query = parse_qs(parsed.query)+ remote = getattr(ws, "remote_address", None)+ _flat_query = {k: (v[0] if v else "") for k, v in query.items()}++ # ── Path 分发(设计文档 §5.3.7) ──+ # /ws/git → GitDiffWebSocketHandler+ # /ws → 现有主 RPC+ # 其他 → 1008 close+ if request_path == "/ws/git":+ await self._handle_git_ws_connection(ws, _flat_query, remote)+ return++ if request_path != self.config.path:+ await ws.close(code=1008, reason=f"unsupported path: {request_path}")+ return++ connection_user_id, _user_id = self._resolve_ws_identity(+ ws, _flat_query, remote, route_type="ws",+ )+ try:+ _conn_ext = _ext_build(query)+ except Exception:+ _conn_ext = None+ setattr(ws, "_web_request_ext", _conn_ext)+ _ext_set(_conn_ext)+ uid_marker = "" if connection_user_id else " uid_empty=yes"+ logger.info(+ "WebChannel 新连接: remote=%s query=%s user_id=%r%s",+ remote,+ query,+ connection_user_id,+ uid_marker,+ )++ # ── V2: 从 query 提取身份字段,构造默认 RoutingKey ──+ # session_id 和 agent_id 可能在首条消息中更新+ _app_id = _flat_query.get("app_id", "default")+ _mode = _flat_query.get("mode", "agent")+ _agent_id = _flat_query.get("agent_id", "default")+ _initial_sid = _flat_query.get("session_id", self._make_session_id())+ _initial_rk = RoutingKey(+ user_id=_user_id,+ channel_id=self.channel_id,+ app_id=_app_id,+ agent_ref=AgentRef(mode=_mode, id=_agent_id),+ session_id=_initial_sid,+ )+ await self.register_ws(ws, _initial_rk)+ # 将握手阶段占位 session_id 挂到 ws 上,供 _on_connect 等连接级钩子复用,+ # 确保 connection.ack 与 ws 在 _clients_by_key 中的注册 key 一致,+ # 否则 send() 按 session_id 反查会落空导致 ACK 丢弃。+ # 注:此 sid 仅为传输层占位,首条 chat.send 携带真实 session_id 时会 re-register 覆盖。+ setattr(ws, "_jiuwen_initial_sid", _initial_sid)++ # 触发连接钩子(如发送 connection.ack)+ for hook in self._owner.rpc.connect_hooks:+ try:+ result = hook(ws)+ if inspect.isawaitable(result):+ await result+ except Exception as e: # pragma: no cover+ logger.warning(+ "WebChannel on_connect hook error: %s",+ format_ws_diagnostics(+ {"remote": remote, "path": request_path},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )++ try:+ async for raw in ws:+ await self._handle_raw_message(ws, raw, query)+ except WebSocketConnectionClosed as e: # pragma: no cover - 连接生命周期容错+ logger.info(+ "WebChannel 连接关闭: %s",+ format_ws_diagnostics(+ {"remote": remote, "path": request_path},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )+ except Exception as e: # pragma: no cover - 连接生命周期容错+ logger.warning(+ "WebChannel 连接异常: %s",+ format_ws_diagnostics(+ {"remote": remote, "path": request_path},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )+ finally:+ await self.unregister_ws(ws)++ logger.info(+ "WebChannel 连接清理完成: %s",+ format_ws_diagnostics(+ {"remote": remote, "path": request_path, "clients": len(self._clients_by_key)},+ describe_ws_peer(ws),+ ),+ )+ # 取出该 ws 关联的 session_ids,清理映射+ ws_id = id(ws)+ disconnected_sessions = self._ws_sessions.pop(ws_id, set())+ logger.info(+ "WebChannel 连接关闭: remote=%s sessions=%s",+ remote,+ disconnected_sessions or "none",+ )+ # 注意:此处不清理 _session_busy。ws 断开不等价于 agent 已停止——+ # 用户关 tab / 刷新 / 网络断开期间,后端 run 仍可能在写文件。若按+ # ws ownership 清掉 busy,新的 discard_turn_changes 会通过 busy 校验,+ # 与仍在运行的 agent 文件写入并发,造成数据损坏。stale busy 的治理+ # 应基于 TTL / 心跳 / agentserver run 状态源,而非 ws 连接状态。+ # 触发断连钩子,传入 session_ids(签名: (ws, session_ids))+ for hook in self._owner.rpc.disconnect_hooks:+ try:+ result = hook(ws, disconnected_sessions)+ if inspect.isawaitable(result):+ await result+ except Exception as e: # pragma: no cover+ logger.warning("WebChannel on_disconnect hook error: %s", e)++ async def _handle_git_ws_connection(+ self,+ ws: Any,+ flat_query: dict[str, str],+ remote: Any,+ ) -> None:+ """处理 /ws/git 路由的连接(设计文档 §5.3.7)。++ 构建 ``AgentRef(mode="git", id="diff")`` 哨兵 RoutingKey,+ 注册后委托 ``GitDiffWebSocketHandler.handle_connection`` 处理消息循环。+ 断连 ``finally`` 先后调 ``unregister_ws(ws)`` 和+ ``git_watcher_registry.cleanup_ws(ws)``,避免 watcher 仍继续轮询推送。+ """+ registry = getattr(self._owner, "git_watcher_registry", None)+ if registry is None:+ await ws.close(code=1011, reason="git watcher registry not available")+ return++ from jiuwenswarm.gateway.channel_manager.web.git_ws_handler import (+ GitDiffWebSocketHandler,+ )+ handler = GitDiffWebSocketHandler(self, registry)++ connection_user_id, _user_id = self._resolve_ws_identity(+ ws, flat_query, remote, route_type="git",+ )+ _app_id = flat_query.get("app_id", "default")+ # session_id 为传输层占位,不是聊天会话(设计文档 §5.3.7)+ _session_id = flat_query.get("session_id") or f"gitws_{uuid.uuid4().hex[:12]}"+ _rk = RoutingKey(+ user_id=_user_id,+ channel_id=self.channel_id,+ app_id=_app_id,+ agent_ref=AgentRef(mode="git", id="diff"),+ session_id=_session_id,+ )+ await self.register_ws(ws, _rk)++ logger.info(+ "[WebChannel] /ws/git 新连接: remote=%s user_id=%r session_id=%s",+ remote,+ connection_user_id,+ _session_id,+ )++ try:+ await handler.handle_connection(ws, flat_query)+ except WebSocketConnectionClosed as e:+ logger.info(+ "[WebChannel] /ws/git 连接关闭: %s",+ format_ws_diagnostics(+ {"remote": remote, "path": "/ws/git"},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )+ except Exception as e:+ logger.warning(+ "[WebChannel] /ws/git 连接异常: %s",+ format_ws_diagnostics(+ {"remote": remote, "path": "/ws/git"},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )+ finally:+ await self.unregister_ws(ws)+ try:+ registry.cleanup_ws(ws)+ except Exception as exc: # noqa: BLE001+ logger.debug(+ "[WebChannel] /ws/git cleanup_ws failed: %s", exc,+ )+ logger.info(+ "[WebChannel] /ws/git 连接清理完成: remote=%s",+ remote,+ )++ async def _handle_raw_message(self, ws: Any, raw: str, query: dict[str, list[str]]) -> None:+ self._record_history_frame("browser", raw)+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ await self.send_response(ws, "", ok=False, error="invalid json", code="BAD_REQUEST")+ return++ if not isinstance(data, dict):+ await self.send_response(ws, "", ok=False, error="invalid request", code="BAD_REQUEST")+ return++ req_type = data.get("type")+ req_id = data.get("id")+ method = data.get("method")+ params = data.get("params")++ if req_type != "req" or not isinstance(req_id, str) or not isinstance(method, str):+ await self.send_response(+ ws,+ req_id if isinstance(req_id, str) else "",+ ok=False,+ error="invalid request",+ code="BAD_REQUEST",+ )+ return+ if not isinstance(params, dict):+ params = {}++ # ── V2: session_id 解析 ──+ # 请求自带 session_id(如 chat.send)→ 用它更新 ws 路由注册。+ # 请求未带 session_id(如 memory.compute 心跳、updater.check、config.get+ # 等 ws 层 keepalive / 拉取请求)→ 这类请求与 session 无关,+ # 仅合成一个临时 id 供后续 Message 构造使用,但【不】参与 register_ws,+ # 保留 ws 上一次的真实 RoutingKey,避免把 ws 从其所属 team session 摘除。+ _explicit_session_id = params.get("session_id")+ has_explicit_session = (+ isinstance(_explicit_session_id, str) and bool(_explicit_session_id)+ )+ session_id = _explicit_session_id if has_explicit_session else self._make_session_id()++ # 追踪 ws → 真实 session_id,用于断连清理/日志。+ # 与 register_ws 一致:仅显式 session 入集;临时 id 只供 Message 构造,避免膨胀。+ if has_explicit_session:+ ws_id = id(ws)+ sessions = self._ws_sessions.get(ws_id)+ if sessions is None:+ sessions = set()+ self._ws_sessions[ws_id] = sessions+ sessions.add(session_id)++ params = await self._owner.rpc.process_files(params)++ # ── V2: 用实际的 session_id / mode / agent_id 更新 ws 注册 ──+ _flat_query = {k: (v[0] if v else "") for k, v in query.items()}+ _mode = params.get("mode", "agent")+ _agent_id = params.get("agent_id", "default")+ _app_id = _flat_query.get("app_id", "default")+ req_user_id = self.connection_user_id(ws)+ if has_explicit_session:+ _rk = RoutingKey(+ user_id=self._routing_key_user_id(req_user_id, getattr(ws, "remote_address", None)),+ channel_id=self.channel_id,+ app_id=_app_id,+ agent_ref=AgentRef(mode=_mode, id=_agent_id),+ session_id=session_id,+ )+ await self.register_ws(ws, _rk)+ # else: ws 层心跳 / 拉取请求,不更新路由注册,沿用 ws 已有的 RoutingKey。++ # Preserve client top-level is_stream (e.g. command.goal set/resume).+ # chat.send / history.get still become stream in _normalize_gateway_message+ # even when the client omits this field.+ user_message = Message(+ id=req_id,+ type="req",+ channel_id=self.channel_id,+ session_id=session_id,+ params=params,+ timestamp=time.time(),+ ok=True,+ req_method=self._parse_req_method(method),+ mode=self._parse_mode(params.get("mode")),+ is_stream=bool(data.get("is_stream", False)),+ app_id=_app_id,+ agent_ref={"mode": _mode, "id": _agent_id},+ user_id=req_user_id,+ metadata=_ext_attach(+ {+ "query": query,+ "method": method,+ # V2: 注入 ws_id 供 MessageHandler 构造 WebDeliveryTarget(ws_id=真值)。+ "ws_id": getattr(ws, "_jiuwen_ws_id", ""),+ "user_id": req_user_id,+ },+ ext=getattr(ws, "_web_request_ext", None),+ ),+ )++ from jiuwenswarm.gateway.channel_manager.web.invoke import dispatch_web_request++ await dispatch_web_request(+ self._owner,+ method=method,+ params=params,+ request_id=req_id,+ outbound=ws,+ session_id=session_id,+ user_message=user_message,+ )++ async def _broadcast_to(self, frame: dict[str, Any], clients: set[Any]) -> None:+ """向指定 clients 集合广播帧(走 per-ws writer,非阻塞入队).++ 入队 dict,由 writer 统一序列化一次,避免此处预 dumps。+ """+ if not clients:+ return+ for client in clients:+ self._enqueue_send(client, frame)++ # ── BaseWsChannel 抽象方法 ──++ def _serialize_frame(+ self,+ msg: Any,+ routing_target: RoutingTarget | None = None,+ *,+ member_names: list[str] | None = None,+ ) -> dict[str, Any]:+ """将 Message 转为 Web 前端帧 dict(由 writer 统一序列化)."""+ event_name = "chat.final"+ if getattr(msg, "event_type", None) is not None:+ event_name = msg.event_type.value+ elif isinstance(getattr(msg, "payload", None), dict):+ et = msg.payload.get("event_type")+ if isinstance(et, str) and et.strip():+ event_name = et.strip()++ payload: dict[str, Any] = {}+ if isinstance(msg.payload, dict):+ payload = {**msg.payload}+ if "session_id" not in payload and getattr(msg, "session_id", None):+ payload["session_id"] = msg.session_id+ elif getattr(msg, "payload", None) is not None:+ payload = {"session_id": getattr(msg, "session_id", None), "content": str(msg.payload)}+ else:+ payload = {"session_id": getattr(msg, "session_id", None), "content": ""}++ agent_ref = getattr(msg, "agent_ref", None)+ if agent_ref:+ payload["agent_ref"] = agent_ref if isinstance(agent_ref, dict) else {+ "mode": getattr(agent_ref, "mode", ""),+ "id": getattr(agent_ref, "id", ""),+ }++ frame: dict[str, Any] = {+ "type": "event",+ "event": event_name,+ "payload": payload,+ }+ return frame++ @staticmethod+ def _parse_req_method(method: str) -> ReqMethod | None:+ for item in ReqMethod:+ if item.value == method:+ return item+ return None++ @staticmethod+ def _parse_mode(raw_mode: Any) -> Mode:+ return Mode.from_raw(raw_mode, default=Mode.AGENT)++ @staticmethod+ def _make_session_id() -> str:+ # 与前端 generateSessionId 保持一致:毫秒时间戳(16进制) + 6位随机16进制+ ts = format(int(time.time() * 1000), "x")+ suffix = secrets.token_hex(3)+ return f"sess_{ts}_{suffix}"++ parse_req_method = _parse_req_method+ parse_mode = _parse_mode+ make_session_id = _make_session_id+ build_event_payload = _build_event_payload+ coalescible_stream_frame = _coalescible_stream_frame+ extract_query_user_id = _extract_query_user_id+ extract_ws_header_user_id = _extract_ws_header_user_id+ resolve_connection_user_id = _resolve_connection_user_id+ routing_key_user_id = _routing_key_user_iddiff --git a/jiuwenswarm/gateway/message_handler/web_file_push.py b/jiuwenswarm/gateway/message_handler/web_file_push.pyindex 6198b9f7e0..03ceec0998 100644--- a/jiuwenswarm/gateway/message_handler/web_file_push.py+++ b/jiuwenswarm/gateway/message_handler/web_file_push.py@@ -1,6 +1,11 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.-"""Enterprise Web file push helpers (Gateway -> app_web /file-api/push)."""+"""Enterprise file push helpers — land on Gateway disk and sign download tokens.++Historically POSTed to Web Pod ``/file-api/push``. Web is static-only now; files+are written under ``web_received_files`` (or ``JIUWENSWARM_WEB_RECEIVED_FILES``)+on the Gateway host and served via Gateway ``GET /file-api/download``.+"""from __future__ import annotations@@ -10,105 +15,50 @@ from typing import Anylogger = logging.getLogger(__name__)-_DEFAULT_K8S_WEB_SERVICE_URL = "http://jiuwenclaw-web-nodeport:5173"---def resolve_web_server_push_url() -> str:- """Resolve Web Server base URL for enterprise file push."""- if not os.getenv("AGENT_RUNTIME", "").strip():- return ""-- explicit = (- os.getenv("JIUWENCLAW_WEB_SERVER_URL", "").strip()- or os.getenv("ENTERPRISE_WEB_SERVICE_URL", "").strip()- )- if explicit:- return explicit.rstrip("/")-- k8s_host = os.getenv("JIUWENCLAW_WEB_NODEPORT_SERVICE_HOST", "").strip()- k8s_port = os.getenv("JIUWENCLAW_WEB_NODEPORT_SERVICE_PORT", "").strip()- if k8s_host and k8s_port:- return f"http://{k8s_host}:{k8s_port}"-- logger.warning(- "[WebFilePush] 使用默认 K8s Service URL: %s",- _DEFAULT_K8S_WEB_SERVICE_URL,- )- return _DEFAULT_K8S_WEB_SERVICE_URL-async def push_file_to_web_and_get_token(file_path: str,filename: str,session_id: str,) -> dict[str, Any] | None:- """Push a local file to Web Server and return download metadata."""+ """Copy a local file into Gateway received dir and return download metadata."""if not os.getenv("AGENT_RUNTIME", "").strip():return None- web_server_url = resolve_web_server_push_url()- if not web_server_url:- return None-- import aiohttp-- push_endpoint = f"{web_server_url}/file-api/push"-try:- file_size = os.path.getsize(file_path)- with open(file_path, "rb") as f:- file_content = f.read()+ from jiuwenswarm.gateway.channel_manager.web.file_http import save_pushed_file- form_data = aiohttp.FormData()- form_data.add_field(- "file",- file_content,+ with open(file_path, "rb") as handle:+ raw = handle.read()+ result = save_pushed_file(+ file_bytes=raw,filename=filename,- content_type="application/octet-stream",+ session_id=session_id,)- form_data.add_field("session_id", session_id)- form_data.add_field("filename", filename)- form_data.add_field("file_size", str(file_size))-- timeout = aiohttp.ClientTimeout(total=300)- async with aiohttp.ClientSession(timeout=timeout) as http_session:- async with http_session.post(push_endpoint, data=form_data) as response:- if response.status != 200:- error_text = await response.text()- logger.error(- "[WebFilePush] 推送文件到 Web Server 失败: %s, status=%d, error=%s",- filename,- response.status,- error_text,- )- return None-- result = await response.json()- if not result.get("success"):- logger.error(- "[WebFilePush] Web Server 返回错误: %s",- result.get("error"),- )- return None-- logger.info(- "[WebFilePush] 成功推送文件到 Web Server: %s, download_url=%s",- filename,- result.get("download_url"),- )- return {- "name": filename,- "size": file_size,- "mime_type": "application/octet-stream",- "download_url": result.get("download_url"),- "download_token": result.get("download_token"),- "expires_at": result.get("expires_at"),- }+ file_size = os.path.getsize(file_path)+ logger.info(+ "[WebFilePush] Gateway local receive: %s download_url=%s",+ filename,+ result.get("download_url"),+ )+ return {+ "name": filename,+ "size": file_size,+ "mime_type": "application/octet-stream",+ "download_url": result.get("download_url"),+ "download_token": result.get("download_token"),+ "expires_at": result.get("expires_at"),+ }except Exception as exc:logger.error(- "[WebFilePush] 推送文件到 Web Server 异常: %s, error: %s",+ "[WebFilePush] Gateway local receive failed: %s, error: %s",filename,exc,exc_info=True,)return None+++def resolve_web_server_push_url() -> str:+ """Deprecated: push no longer targets Web Pod."""+ return ""diff --git a/jiuwenswarm/server/pipeline.py b/jiuwenswarm/server/pipeline.pyindex 876e3f0a4c..c0874cd58a 100644--- a/jiuwenswarm/server/pipeline.py+++ b/jiuwenswarm/server/pipeline.py@@ -13,6 +13,7 @@ from websockets.exceptions import ConnectionClosed as WebSocketConnectionClosedfrom jiuwenswarm.common.e2a.wire_codec import encode_agent_response_for_wirefrom jiuwenswarm.common.log_preview import preview_text+from jiuwenswarm.common.request_ext import lift_from_metadata, reset_extfrom jiuwenswarm.common.schema.agent import AgentRequest, AgentResponsefrom jiuwenswarm.common.schema.message import ReqMethodfrom jiuwenswarm.common.ws_diagnostics import (@@ -85,6 +86,7 @@ async def dispatch_parsed_request(preview_text(_request_query_text(request)),)+ _ext_token = lift_from_metadata(request.metadata)try:if request.channel_id == "acp" and request.req_method != ReqMethod.INITIALIZE:metadata = dict(request.metadata or {})@@ -173,3 +175,5 @@ async def dispatch_parsed_request(request.request_id,send_err,)+ finally:+ reset_ext(_ext_token)diff --git a/jiuwenswarm/start_services.py b/jiuwenswarm/start_services.pyindex 7ccae4b909..292b15f8d9 100644--- a/jiuwenswarm/start_services.py+++ b/jiuwenswarm/start_services.py@@ -643,9 +643,28 @@ def _wait_for_services_ready(if agent_port:targets.append(("AgentServer WebSocket", agent_port, f"ws://localhost:{agent_port}"))if gateway_port:- targets.append(("Gateway HTTP", gateway_port, f"http://localhost:{gateway_port}"))+ targets.append(+ ("Gateway WebSocket", gateway_port, f"ws://localhost:{gateway_port}/tui"),+ )if web_port:targets.append(("WebChannel WebSocket", web_port, f"ws://localhost:{web_port}/ws"))+ # Keep in sync with web_http_server.resolve_web_http_port (no heavy import).+ web_http_port = web_port + 2+ raw_http = os.environ.get("GATEWAY_WEB_HTTP_PORT", "").strip()+ if raw_http:+ try:+ web_http_port = int(raw_http)+ except ValueError:+ pass+ if web_http_port in (web_port, gateway_port):+ web_http_port = max(web_port, gateway_port or 0) + 1+ targets.append(+ (+ "Web HTTP",+ web_http_port,+ f"http://localhost:{web_http_port}/api/v1",+ ),+ )# HTTP/SSE 入口(可选):与 AgentServer 同进程,开启时才展示。# 配置解析与 AgentServer 共用同一函数,避免两处逻辑漂移。diff --git a/scripts/gateway_http_live_test.py b/scripts/gateway_http_live_test.pynew file mode 100644index 0000000000..da1569b262--- /dev/null+++ b/scripts/gateway_http_live_test.py@@ -0,0 +1,446 @@+#!/usr/bin/env python3+"""Catalog-driven live test for Gateway Web HTTP enterprise browser APIs."""++from __future__ import annotations++import json+import logging+import os+import re+import time+import uuid+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from typing import Any++logger = logging.getLogger(__name__)+BASE = "http://localhost:19002"+GET_TIMEOUT = 45+WRITE_SKIP = True # avoid mutating permissions/skills/harness on live env+++def join_url(path: str) -> str:+ return urllib.parse.urljoin(BASE.rstrip("/") + "/", path.lstrip("/"))+++def join_api_path(*segments: str) -> str:+ """Join HTTP API path segments (urllib.parse, not filesystem paths)."""+ if not segments:+ return "/"+ path = segments[0]+ for segment in segments[1:]:+ path = urllib.parse.urljoin(path.rstrip("/") + "/", segment.lstrip("/"))+ return path+++@dataclass+class ClassifyRequest:+ group: str+ method: str+ path: str+ rpc: str | None+ code: int+ text: str+ ms: int+ allow_biz: bool = True+++@dataclass+class Row:+ group: str+ method: str+ path: str+ rpc: str | None+ status: str+ http_code: int | None = None+ ms: int = 0+ note: str = ""+++rows: list[Row] = []+session_id: str | None = None+cron_job_id: str | None = None+skill_name: str | None = None+++def http(+ method: str,+ path: str,+ *,+ body: dict | None = None,+ headers: dict[str, str] | None = None,+ timeout: int = GET_TIMEOUT,+) -> tuple[int, dict[str, str], str, int]:+ url = join_url(path)+ hdrs = {+ "Accept": "application/json",+ "Content-Type": "application/json",+ "X-Request-Id": uuid.uuid4().hex,+ }+ if session_id:+ hdrs["X-Session-Id"] = session_id+ if headers:+ hdrs.update(headers)+ data = json.dumps(body).encode() if body is not None else None+ req = urllib.request.Request(url, data=data, headers=hdrs, method=method)+ t0 = time.perf_counter()+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ text = resp.read().decode("utf-8", errors="replace")+ ms = int((time.perf_counter() - t0) * 1000)+ return resp.status, dict(resp.headers), text, ms+ except urllib.error.HTTPError as e:+ text = e.read().decode("utf-8", errors="replace")+ ms = int((time.perf_counter() - t0) * 1000)+ return e.code, dict(e.headers), text, ms+++def add(row: Row) -> None:+ rows.append(row)+++def parse_json(text: str) -> dict[str, Any] | None:+ try:+ v = json.loads(text)+ return v if isinstance(v, dict) else None+ except json.JSONDecodeError:+ return None+++def classify(req: ClassifyRequest) -> None:+ payload = parse_json(req.text)+ rpc_hdr = None+ if payload and isinstance(payload.get("metadata"), dict):+ rpc_hdr = payload["metadata"].get("rpc_method")+ if req.code in (200, 201) and payload and payload.get("ok") is True:+ add(Row(req.group, req.method, req.path, req.rpc or rpc_hdr, "PASS", req.code, req.ms))+ return+ if req.allow_biz and req.code in (400, 404, 409) and payload:+ msg = ""+ err = payload.get("error")+ if isinstance(err, dict):+ msg = str(err.get("message") or err.get("code") or "")+ add(+ Row(+ req.group,+ req.method,+ req.path,+ req.rpc or rpc_hdr,+ "BIZ",+ req.code,+ req.ms,+ msg or "business response",+ ),+ )+ return+ if req.code == 403 and req.path.startswith("/file-api"):+ add(+ Row(+ req.group,+ req.method,+ req.path,+ req.rpc,+ "BIZ",+ req.code,+ req.ms,+ "forbidden path/dir (expected for bad dir)",+ ),+ )+ return+ if req.code == 200 and req.path.startswith(("/api/sessions", "/file-api/", "/share-api/")):+ add(+ Row(+ req.group,+ req.method,+ req.path,+ req.rpc,+ "PASS",+ req.code,+ req.ms,+ "legacy compat JSON (no ok envelope)",+ ),+ )+ return+ add(Row(req.group, req.method, req.path, req.rpc or rpc_hdr, "FAIL", req.code, req.ms, req.text[:180]))+++def fill_path(path: str) -> str | None:+ global cron_job_id, skill_name+ if "{session_id}" in path:+ if not session_id:+ return None+ path = path.replace("{session_id}", session_id)+ if "{id}" in path:+ if "/cron/jobs/" in path:+ if not cron_job_id:+ return None+ path = path.replace("{id}", cron_job_id)+ else:+ path = path.replace("{id}", "test-rule-id")+ if "{tool}" in path:+ path = path.replace("{tool}", "bash")+ if "{name}" in path:+ if not skill_name:+ return None+ path = path.replace("{name}", urllib.parse.quote(skill_name, safe=""))+ if "{slug}" in path:+ path = path.replace("{slug}", "demo")+ if "{package_id}" in path:+ path = path.replace("{package_id}", "native")+ return path+++def query_for(path: str, rpc: str | None) -> str:+ q: dict[str, str] = {}+ if "/cron/" in path:+ q["project_id"] = "default"+ if rpc and "clawhub.search" in rpc:+ q.update({"q": "demo", "limit": "1"})+ if rpc and "enterprise.list" in (rpc or ""):+ q.update({"group_id": "g1", "bot_id": "b1", "user_id": "u1"})+ if "evolution" in path or (rpc and "evolution" in rpc):+ if session_id:+ q["session_id"] = session_id+ if "skillnet.install_status" in (rpc or ""):+ q["install_id"] = "test-install-id"+ if "evolution" in (rpc or ""):+ q["name"] = skill_name or "demo-skill"+ if not q:+ return ""+ return "?" + urllib.parse.urlencode(q)+++def bootstrap() -> None:+ global session_id, cron_job_id, skill_name+ code, _, text, ms = http("GET", "/api/v1/health")+ classify(ClassifyRequest("infra", "GET", "/api/v1/health", None, code, text, ms))+ code, _, text, ms = http("GET", "/api/v1/connection/status", timeout=15)+ classify(+ ClassifyRequest(+ "infra", "GET", "/api/v1/connection/status", "connection.status", code, text, ms,+ ),+ )++ code, _, text, ms = http("POST", "/api/v1/sessions", body={})+ payload = parse_json(text)+ if payload and payload.get("ok"):+ sid = payload.get("data", {}).get("session_id")+ if sid:+ session_id = str(sid)+ classify(ClassifyRequest("core", "POST", "/api/v1/sessions", "session.create", code, text, ms))++ code, _, text, ms = http("GET", "/api/v1/sessions")+ classify(ClassifyRequest("core", "GET", "/api/v1/sessions", "session.list", code, text, ms))++ cron_path = join_api_path("/api/v1/cron/jobs") + query_for("/cron/jobs", "cron.job.list")+ code, _, text, ms = http("GET", cron_path)+ payload = parse_json(text)+ if payload and isinstance(payload.get("data"), dict):+ jobs = payload["data"].get("jobs") or []+ if jobs and isinstance(jobs[0], dict):+ cron_job_id = str(jobs[0].get("id") or "")+ classify(ClassifyRequest("settings", "GET", "/api/v1/cron/jobs", "cron.job.list", code, text, ms))++ code, _, text, ms = http("GET", "/api/v1/skills/installed")+ payload = parse_json(text)+ if payload and isinstance(payload.get("data"), dict):+ plugins = payload["data"].get("plugins") or payload["data"].get("skills") or []+ if plugins and isinstance(plugins[0], dict):+ skill_name = str(plugins[0].get("name") or plugins[0].get("skill_name") or "")+ classify(+ ClassifyRequest("workspace", "GET", "/api/v1/skills/installed", "skills.installed", code, text, ms),+ )+++def test_catalog_gets() -> None:+ _, _, text, _ = http("GET", "/api/v1/catalog", timeout=15)+ cat = parse_json(text)+ if not cat or not cat.get("ok"):+ add(Row("infra", "GET", "/api/v1/catalog", None, "FAIL", None, 0, "catalog unavailable"))+ return+ routes = cat.get("data", {}).get("routes", [])+ add(Row("infra", "GET", "/api/v1/catalog", None, "PASS", 200, 0, f"{len(routes)} routes"))++ for r in routes:+ method = str(r.get("http_method") or "").upper()+ if method != "GET":+ continue+ raw_path = str(r.get("path") or "")+ rpc = r.get("rpc_method")+ group = str(r.get("group") or r.get("phase") or "other")+ if raw_path in {"/api/v1/health", "/api/v1/catalog"}:+ continue+ if "/history" in raw_path and "stream" in raw_path:+ add(Row(group, method, raw_path, rpc, "SKIP", None, 0, "SSE history stream — manual"))+ continue+ rel = raw_path.replace("/api/v1", "")+ filled = fill_path(rel)+ if filled is None:+ add(Row(group, method, raw_path, rpc, "SKIP", None, 0, "missing fixture id"))+ continue+ full = join_api_path("/api/v1", filled.lstrip("/")) + query_for(+ filled, str(rpc) if rpc else None,+ )+ try:+ code, _, text, ms = http(method, full)+ classify(+ ClassifyRequest(group, method, full, str(rpc) if rpc else None, code, text, ms),+ )+ except Exception as exc: # noqa: BLE001+ add(Row(group, method, full, str(rpc) if rpc else None, "FAIL", None, 0, str(exc)))+++def test_core_writes() -> None:+ if not session_id:+ return+ sid = session_id+ code, _, text, ms = http(+ "PATCH",+ f"/api/v1/sessions/{sid}",+ body={"title": "enterprise-http-smoke"},+ )+ classify(ClassifyRequest("core", "PATCH", f"/api/v1/sessions/{sid}", "session.rename", code, text, ms))++ # SSE chat+ url = join_url("/api/v1/chat/completions")+ body = json.dumps(+ {"session_id": sid, "query": "reply with exactly: pong", "enable_streaming": True},+ ).encode()+ req = urllib.request.Request(+ url,+ data=body,+ headers={+ "Content-Type": "application/json",+ "Accept": "text/event-stream",+ "X-Request-Id": uuid.uuid4().hex,+ "X-Session-Id": sid,+ },+ method="POST",+ )+ t0 = time.perf_counter()+ try:+ with urllib.request.urlopen(req, timeout=90) as resp:+ chunk = resp.read(8192).decode("utf-8", errors="replace")+ ms = int((time.perf_counter() - t0) * 1000)+ ok = resp.status == 200 and ("event:" in chunk or "data:" in chunk)+ add(+ Row(+ "core",+ "POST",+ "/api/v1/chat/completions",+ "chat.send",+ "PASS" if ok else "WARN",+ resp.status,+ ms,+ chunk[:120],+ ),+ )+ except Exception as exc: # noqa: BLE001+ add(Row("core", "POST", "/api/v1/chat/completions", "chat.send", "FAIL", None, 0, str(exc)))++ code, _, text, ms = http("GET", f"/api/v1/sessions/{sid}/history")+ classify(ClassifyRequest("core", "GET", f"/api/v1/sessions/{sid}/history", "history.get", code, text, ms))++ code, _, text, ms = http(+ "POST",+ f"/api/v1/chat/{sid}/actions/interrupt",+ body={},+ )+ classify(+ ClassifyRequest(+ "core",+ "POST",+ f"/api/v1/chat/{sid}/actions/interrupt",+ "chat.interrupt",+ code,+ text,+ ms,+ allow_biz=True,+ ),+ )+++def test_file_compat() -> None:+ cases = [+ ("GET", "/file-api/ws-debug-config", None),+ ("GET", "/file-api/list-files?dir=", None),+ ("GET", "/file-api/list-markdown?dir=", None),+ ("GET", "/file-api/list-files?dir=..%2F", "path traversal"),+ (+ "GET",+ join_api_path("/share-api/snapshot")+ + "?"+ + urllib.parse.urlencode({"session_id": session_id or "missing"}),+ None,+ ),+ ]+ for method, path, note in cases:+ p = path+ if p.endswith("=") and session_id:+ p = f"{p}{session_id}"+ try:+ code, _, text, ms = http(method, p, timeout=20)+ if note == "path traversal":+ payload = parse_json(text)+ verdict = "PASS" if code == 403 or (payload and payload.get("error")) else "FAIL"+ add(Row("file", method, p, None, verdict, code, ms, note))+ else:+ classify(ClassifyRequest("file", method, p, None, code, text, ms, allow_biz=True))+ except Exception as exc: # noqa: BLE001+ add(Row("file", method, p, None, "FAIL", None, 0, str(exc)))+++def test_enterprise_sessions() -> None:+ code, _, text, ms = http("GET", "/api/sessions?limit=10")+ classify(ClassifyRequest("enterprise", "GET", "/api/sessions", None, code, text, ms))+ if session_id:+ code, _, text, ms = http("GET", f"/api/sessions/{session_id}")+ classify(ClassifyRequest("enterprise", "GET", f"/api/sessions/{session_id}", None, code, text, ms))+++def test_openapi() -> None:+ for p in ("/doc", "/openapi.json"):+ try:+ req = urllib.request.Request(join_url(p), headers={"Accept": "*/*"}, method="GET")+ with urllib.request.urlopen(req, timeout=15) as resp:+ add(Row("infra", "GET", p, None, "PASS", resp.status, 0))+ except Exception as exc: # noqa: BLE001+ add(Row("infra", "GET", p, None, "FAIL", None, 0, str(exc)))+++def main() -> None:+ logging.basicConfig(level=logging.INFO, format="%(message)s")+ test_openapi()+ bootstrap()+ test_catalog_gets()+ test_core_writes()+ test_enterprise_sessions()+ test_file_compat()++ summary: dict[str, int] = {}+ for r in rows:+ summary[r.status] = summary.get(r.status, 0) + 1++ out = {+ "base": BASE,+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),+ "session_id": session_id,+ "cron_job_id": cron_job_id,+ "skill_name": skill_name,+ "summary": summary,+ "results": [r.__dict__ for r in rows],+ }+ out_path = os.path.join("scripts", "gateway_http_live_results.json")+ with open(out_path, "w", encoding="utf-8") as f:+ json.dump(out, f, ensure_ascii=False, indent=2)++ logger.info("%s", json.dumps(summary, ensure_ascii=False))+ for r in rows:+ if r.status in ("FAIL", "WARN"):+ logger.info("[%s] %s %s %s", r.status, r.method, r.path, r.note)+++if __name__ == "__main__":+ main()diff --git a/scripts/gateway_http_smoke_test.py b/scripts/gateway_http_smoke_test.pynew file mode 100644index 0000000000..f0e31a3dab--- /dev/null+++ b/scripts/gateway_http_smoke_test.py@@ -0,0 +1,462 @@+#!/usr/bin/env python3+"""Live smoke test against Gateway Web HTTP (enterprise browser APIs)."""++from __future__ import annotations++import json+import logging+import os+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from typing import Any++logger = logging.getLogger(__name__)++BASE = "http://localhost:19002"+TIMEOUT = 30+++def join_url(path: str) -> str:+ return urllib.parse.urljoin(BASE.rstrip("/") + "/", path.lstrip("/"))+++@dataclass+class Result:+ group: str+ name: str+ method: str+ path: str+ status: str # PASS | FAIL | SKIP | WARN+ http_code: int | None = None+ rpc_method: str | None = None+ note: str = ""+ detail: str = ""+++results: list[Result] = []+session_id: str | None = None+cron_job_id: str | None = None+++def req(+ method: str,+ path: str,+ *,+ body: dict | None = None,+ headers: dict[str, str] | None = None,+ raw_body: bytes | None = None,+) -> tuple[int, dict[str, str], str]:+ url = join_url(path)+ hdrs = {"Accept": "application/json", "Content-Type": "application/json"}+ if headers:+ hdrs.update(headers)+ data = None+ if raw_body is not None:+ data = raw_body+ elif body is not None:+ data = json.dumps(body).encode("utf-8")+ request = urllib.request.Request(url, data=data, headers=hdrs, method=method)+ try:+ with urllib.request.urlopen(request, timeout=TIMEOUT) as resp:+ text = resp.read().decode("utf-8", errors="replace")+ return resp.status, dict(resp.headers), text+ except urllib.error.HTTPError as e:+ text = e.read().decode("utf-8", errors="replace")+ return e.code, dict(e.headers), text+++def record(result: Result) -> None:+ results.append(result)+++def expect_ok_json(+ group: str,+ name: str,+ method: str,+ path: str,+ *,+ rpc: str | None = None,+ body: dict | None = None,+ headers: dict[str, str] | None = None,+ allow_codes: set[int] | None = None,+) -> dict[str, Any] | None:+ allow = allow_codes or {200, 201}+ try:+ code, hdrs, text = req(method, path, body=body, headers=headers)+ rpc_hdr = hdrs.get("X-Web-RPC-Method") or hdrs.get("x-web-rpc-method")+ if code not in allow:+ record(+ Result(+ group, name, method, path, "FAIL", code, rpc or rpc_hdr,+ f"HTTP {code}", text[:500],+ ),+ )+ return None+ try:+ payload = json.loads(text) if text else {}+ except json.JSONDecodeError:+ record(Result(group, name, method, path, "FAIL", code, rpc, "invalid json", text[:500]))+ return None+ if isinstance(payload, dict) and payload.get("ok") is False:+ err = payload.get("error", {})+ msg = err.get("message") if isinstance(err, dict) else str(err)+ # Some endpoints legitimately return business errors in dev+ record(+ Result(+ group, name, method, path, "WARN", code, rpc or rpc_hdr,+ msg or "ok=false", text[:500],+ ),+ )+ return payload+ record(Result(group, name, method, path, "PASS", code, rpc or rpc_hdr))+ return payload if isinstance(payload, dict) else {}+ except Exception as exc: # noqa: BLE001+ record(Result(group, name, method, path, "FAIL", None, rpc, str(exc)))+ return None+++def test_doc_and_catalog() -> None:+ for path, name in [("/doc", "Swagger UI"), ("/openapi.json", "OpenAPI")]:+ try:+ code, _, _ = req("GET", path, headers={"Accept": "text/html"})+ record(Result("infra", name, "GET", path, "PASS" if code == 200 else "FAIL", code))+ except Exception as exc: # noqa: BLE001+ record(Result("infra", name, "GET", path, "FAIL", note=str(exc)))++ code, _, text = req("GET", "/api/v1/catalog")+ try:+ cat = json.loads(text)+ n = len(cat.get("data", {}).get("routes", []))+ record(+ Result(+ "infra",+ "catalog",+ "GET",+ "/api/v1/catalog",+ "PASS" if cat.get("ok") and n > 50 else "WARN",+ code,+ note=f"{n} routes",+ ),+ )+ except Exception as exc: # noqa: BLE001+ record(Result("infra", "catalog", "GET", "/api/v1/catalog", "FAIL", code, note=str(exc)))+++def test_core() -> None:+ global session_id+ expect_ok_json("core", "health", "GET", "/api/v1/health")+ expect_ok_json(+ "core",+ "connection.status",+ "GET",+ "/api/v1/connection/status",+ rpc="connection.status",+ )+ expect_ok_json("core", "session.list", "GET", "/api/v1/sessions", rpc="session.list")+ created = expect_ok_json(+ "core",+ "session.create",+ "POST",+ "/api/v1/sessions",+ rpc="session.create",+ body={},+ allow_codes={200, 201},+ )+ if created and isinstance(created.get("data"), dict):+ session_id = str(created["data"].get("session_id") or "")+ if not session_id:+ record(Result("core", "session.create", "POST", "/api/v1/sessions", "FAIL", note="no session_id"))+ return++ sid = session_id+ expect_ok_json(+ "core",+ "session.get_metadata",+ "GET",+ f"/api/v1/sessions/{sid}",+ rpc="session.get_metadata",+ )+ expect_ok_json(+ "core",+ "session.rename",+ "PATCH",+ f"/api/v1/sessions/{sid}",+ rpc="session.rename",+ body={"title": "http-smoke-test"},+ )++ # SSE chat - read first chunk only (before history: empty session returns 404)+ try:+ url = join_url("/api/v1/chat/completions")+ body = json.dumps(+ {"session_id": sid, "query": "reply with exactly: pong", "enable_streaming": True},+ ).encode()+ request = urllib.request.Request(+ url,+ data=body,+ headers={+ "Content-Type": "application/json",+ "Accept": "text/event-stream",+ },+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=60) as resp:+ chunk = resp.read(4096).decode("utf-8", errors="replace")+ ok = resp.status == 200 and ("event:" in chunk or "data:" in chunk)+ record(+ Result(+ "core",+ "chat.completions (SSE)",+ "POST",+ "/api/v1/chat/completions",+ "PASS" if ok else "WARN",+ resp.status,+ "chat.send",+ detail=chunk[:200],+ ),+ )+ except Exception as exc: # noqa: BLE001+ record(+ Result(+ "core",+ "chat.completions (SSE)",+ "POST",+ "/api/v1/chat/completions",+ "FAIL",+ rpc_method="chat.send",+ note=str(exc),+ ),+ )++ expect_ok_json(+ "core",+ "history.get (json)",+ "GET",+ f"/api/v1/sessions/{sid}/history",+ rpc="history.get",+ allow_codes={200, 404},+ )++ expect_ok_json(+ "core",+ "chat.interrupt",+ "POST",+ f"/api/v1/chat/{sid}/actions/interrupt",+ rpc="chat.interrupt",+ body={},+ allow_codes={200, 400, 409},+ )+++def test_settings() -> None:+ expect_ok_json("settings", "config.get", "GET", "/api/v1/config", rpc="config.get")+ expect_ok_json("settings", "models.list", "GET", "/api/v1/models", rpc="models.list")+ loc = expect_ok_json("settings", "locale.get", "GET", "/api/v1/locale", rpc="locale.get_conf")+ lang = "en"+ if loc and isinstance(loc.get("data"), dict):+ cur = str(loc["data"].get("preferred_language") or "zh")+ lang = "en" if cur == "zh" else "zh"+ expect_ok_json(+ "settings",+ "locale.set",+ "PUT",+ "/api/v1/locale",+ rpc="locale.set_conf",+ body={"preferred_language": lang},+ )+ jobs = expect_ok_json(+ "settings",+ "cron.job.list",+ "GET",+ "/api/v1/cron/jobs?project_id=default",+ rpc="cron.job.list",+ )+ global cron_job_id+ if jobs and isinstance(jobs.get("data"), dict):+ items = jobs["data"].get("jobs") or []+ if items and isinstance(items[0], dict):+ cron_job_id = str(items[0].get("id") or "")+ if cron_job_id:+ jid = cron_job_id+ expect_ok_json(+ "settings",+ "cron.job.get",+ "GET",+ f"/api/v1/cron/jobs/{jid}?project_id=default",+ rpc="cron.job.get",+ )+ expect_ok_json(+ "settings",+ "cron.job.preview",+ "POST",+ f"/api/v1/cron/jobs/{jid}/actions/preview?project_id=default",+ rpc="cron.job.preview",+ body={"count": 1},+ )+++def test_workspace_sample() -> None:+ expect_ok_json(+ "workspace",+ "permissions.tools.get",+ "GET",+ "/api/v1/permissions/tools",+ rpc="permissions.tools.get",+ )+ expect_ok_json(+ "workspace",+ "permissions.owner_scopes.get",+ "GET",+ "/api/v1/permissions/owner-scopes",+ rpc="permissions.owner_scopes.get",+ )+ expect_ok_json(+ "workspace",+ "skills.list",+ "GET",+ "/api/v1/skills",+ rpc="skills.list",+ )+ expect_ok_json(+ "workspace",+ "skills.installed",+ "GET",+ "/api/v1/skills/installed",+ rpc="skills.installed",+ )+ expect_ok_json(+ "workspace",+ "harness.packages",+ "GET",+ "/api/v1/harness/packages",+ rpc="harness.packages",+ )+++def test_enterprise_compat() -> None:+ expect_ok_json(+ "enterprise",+ "GET /api/sessions (history store)",+ "GET",+ "/api/sessions?limit=5",+ allow_codes={200},+ )+ if session_id:+ expect_ok_json(+ "enterprise",+ "GET /api/sessions/{id}",+ "GET",+ f"/api/sessions/{session_id}",+ allow_codes={200, 404},+ )+++def test_file_api() -> None:+ expect_ok_json(+ "file",+ "list-files (workspace)",+ "GET",+ "/file-api/list-files?dir=agent%2Fworkspace",+ allow_codes={200},+ )+ expect_ok_json(+ "file",+ "ws-debug-config",+ "GET",+ "/file-api/ws-debug-config",+ allow_codes={200},+ )+ # path traversal should be blocked+ code, _, text = req("GET", "/file-api/list-files?dir=..%2F")+ try:+ payload = json.loads(text)+ blocked = code == 403 or payload.get("error")+ record(+ Result(+ "file",+ "path traversal blocked",+ "GET",+ "/file-api/list-files?dir=../",+ "PASS" if blocked else "FAIL",+ code,+ detail=text[:200],+ ),+ )+ except Exception: # noqa: BLE001+ record(+ Result(+ "file",+ "path traversal blocked",+ "GET",+ "/file-api/list-files?dir=../",+ "PASS" if code == 403 else "WARN",+ code,+ ),+ )+++def test_mapped_routes_spot_check() -> None:+ """Spot-check a few table-driven routes from catalog."""+ samples = [+ ("GET", "/api/v1/permissions/rules", "permissions.rules.get"),+ ("GET", "/api/v1/skills/retrieval/status", "skills.retrieval.status"),+ ("GET", "/api/v1/skills/evolution/status", "skills.evolution.status"),+ ]+ for method, path, rpc in samples:+ expect_ok_json("workspace", path, method, path, rpc=rpc)+++def main() -> int:+ logging.basicConfig(level=logging.INFO, format="%(message)s")+ logger.info("Gateway Web HTTP smoke test @ %s", BASE)+ logger.info("%s", "=" * 60)+ test_doc_and_catalog()+ test_core()+ test_settings()+ test_workspace_sample()+ test_mapped_routes_spot_check()+ test_enterprise_compat()+ test_file_api()++ counts = {"PASS": 0, "FAIL": 0, "WARN": 0, "SKIP": 0}+ for r in results:+ counts[r.status] = counts.get(r.status, 0) + 1++ logger.info(+ "\nSummary: PASS=%s WARN=%s FAIL=%s",+ counts["PASS"],+ counts["WARN"],+ counts["FAIL"],+ )+ logger.info("%s", "-" * 60)+ for r in results:+ code = r.http_code if r.http_code is not None else "-"+ rpc = f" [{r.rpc_method}]" if r.rpc_method else ""+ extra = f" — {r.note}" if r.note else ""+ logger.info("[%s] %s %s %s%s (%s)%s", r.status, r.group, r.method, r.path, rpc, code, extra)++ # JSON for report generation+ out_path = os.path.join("scripts", "gateway_http_smoke_results.json")+ with open(out_path, "w", encoding="utf-8") as f:+ json.dump(+ {+ "base": BASE,+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),+ "session_id": session_id,+ "summary": counts,+ "results": [r.__dict__ for r in results],+ },+ f,+ ensure_ascii=False,+ indent=2,+ )+ logger.info("\nWrote %s", out_path)+ return 1 if counts["FAIL"] else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.pyindex a64d189b8c..59cc3582aa 100644--- a/tests/unit_tests/test_app_web_handlers.py+++ b/tests/unit_tests/test_app_web_handlers.py@@ -693,6 +693,64 @@ async def test_models_replace_all_applies_scoped_reload_before_responding(monkeyassert channel.responses[-1]["payload"]["applied_without_restart"] is True+async def test_models_save_remove_set_active_are_registered(monkeypatch):+ channel = FakeWebChannel()+ persisted: list[list[dict]] = []++ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.get_config_raw",+ lambda: {"models": {"defaults": [+ {+ "model_client_config": {+ "model_name": "keep-me",+ "api_base": "",+ "api_key": "",+ "client_provider": "OpenAI",+ },+ "model_config_obj": {"temperature": 0.95},+ }+ ]}},+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_default_models_in_config",+ lambda models: persisted.append(list(models)),+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.registry.ExtensionRegistry.get_instance",+ lambda: type(+ "Registry",+ (),+ {"get_crypto_provider": lambda self: None},+ )(),+ )++ async def on_config_saved(updated_keys, *, env_updates, config_payload, reload_options):+ return True++ _register_web_handlers(+ WebHandlersBindParams(channel=channel, on_config_saved=on_config_saved)+ )+ assert "models.save" in channel.methods+ assert "models.remove" in channel.methods+ assert "models.set_active" in channel.methods++ await channel.methods["models.save"](+ object(),+ "req-save",+ {+ "model_name": "new-model",+ "api_base": "https://example.com/v1",+ "api_key": "secret",+ "model_provider": "OpenAI",+ },+ "sess-1",+ )+ assert channel.responses[-1]["ok"] is True+ assert channel.responses[-1]["payload"]["action"] == "created"+ assert persisted[-1][-1]["model_client_config"]["model_name"] == "new-model"++@pytest.mark.asyncioasync def test_config_set_routes_team_payload_to_modes_team_helper(monkeypatch):channel = FakeWebChannel()diff --git a/tests/unit_tests/test_app_web_raw_file.py b/tests/unit_tests/test_app_web_raw_file.pyindex 70abfbac9a..9f6d39a632 100644--- a/tests/unit_tests/test_app_web_raw_file.py+++ b/tests/unit_tests/test_app_web_raw_file.py@@ -1,49 +1,43 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Regression: raw-file served from Gateway Web HTTP (migrated from app_web)."""+from __future__ import annotations-import threading-import sys-import types-from http.client import HTTPConnection-from http.server import ThreadingHTTPServer-from urllib.parse import quote+from pathlib import Path-bootstrap_module = types.ModuleType("jiuwenswarm.agents.harness.team.bootstrap")-bootstrap_module.configure_agent_teams_home = lambda: None-sys.modules.setdefault(bootstrap_module.__name__, bootstrap_module)+from fastapi.testclient import TestClient-from jiuwenswarm.channels.web.app_web import _SpaStaticHandler+from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app+from jiuwenswarm.gateway.channel_manager.web.file_http import FileHttpRoots+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig-def test_raw_file_serves_persisted_session_image(tmp_path):+def test_raw_file_serves_persisted_session_image(tmp_path: Path):agent_root = tmp_path / "agent"image_path = agent_root / "sessions" / "session-1" / "uploads" / "image.png"image_path.parent.mkdir(parents=True)image_bytes = b"\x89PNG\r\n\x1a\nimage-data"image_path.write_bytes(image_bytes)- class Handler(_SpaStaticHandler):- project_root = tmp_path- workspace_root = agent_root- agent_teams_root = tmp_path / "agent-teams"- logs_root = tmp_path / "logs"- auto_harness_root = tmp_path / "auto-harness"- api_target = ""- ws_target = ""-- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)- thread = threading.Thread(target=server.serve_forever)- thread.start()- try:- connection = HTTPConnection("127.0.0.1", server.server_port)- connection.request("GET", f"/file-api/raw-file?path={quote(str(image_path))}")- response = connection.getresponse()- try:- assert response.status == 200- assert response.headers["Content-Type"] == "image/png"- assert response.read() == image_bytes- finally:- connection.close()- finally:- server.shutdown()- thread.join()- server.server_close()+ roots = FileHttpRoots(+ project_root=tmp_path,+ workspace_root=agent_root,+ agent_teams_root=tmp_path / "agent-teams",+ logs_root=tmp_path / "logs",+ auto_harness_root=tmp_path / "auto-harness",+ )+ for d in (roots.agent_teams_root, roots.logs_root, roots.auto_harness_root):+ d.mkdir(parents=True, exist_ok=True)++ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ app = create_web_http_app(channel)+ app.state.file_http_roots = roots+ client = TestClient(app)++ rel = str(image_path.relative_to(tmp_path)).replace("\\", "/")+ response = client.get("/file-api/raw-file", params={"path": rel})+ assert response.status_code == 200+ assert response.headers["content-type"].startswith("image/png")+ assert response.content == image_bytesdiff --git a/tests/unit_tests/test_history.py b/tests/unit_tests/test_history.pyindex 72814368b2..c3480673e4 100644--- a/tests/unit_tests/test_history.py+++ b/tests/unit_tests/test_history.py@@ -6,6 +6,7 @@ import pytestfrom jiuwenswarm.channels.web.history_store import (ChatHistoryStore,+ default_enterprise_history_db_path,get_session_detail_sync,list_sessions_sync,make_history_callback,@@ -99,6 +100,40 @@ async def test_callback_pending_backfill_on_final(tmp_path) -> None:await store.close()+async def test_callback_uplink_request_id_in_payload(tmp_path) -> None:+ store = ChatHistoryStore(tmp_path / "h.db")+ cb = make_history_callback(store)+ await cb(+ "browser",+ json.dumps({"type": "req", "id": "r1", "method": "chat.send", "params": {"query": "hi"}}),+ )+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.delta",+ "payload": {"session_id": "s1", "request_id": "r1", "content": "ok"},+ },+ ),+ )+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.final",+ "payload": {"session_id": "s1", "request_id": "r1", "content": ""},+ },+ ),+ )+ detail = await store.get_session_detail("s1")+ assert detail is not None+ assert detail["messages"][-1]["content"] == "ok"+ await store.close()++@pytest.mark.asyncioasync def test_callback_ignores_delta_events(tmp_path) -> None:store = ChatHistoryStore(tmp_path / "h.db")@@ -165,3 +200,43 @@ async def test_sync_read_after_write(tmp_path) -> None:# db 不存在:返回空 / None,不抛assert list_sessions_sync(tmp_path / "missing.db") == []assert get_session_detail_sync(tmp_path / "missing.db", "x") is None+++def test_default_enterprise_history_db_path_is_web_history_db() -> None:+ path = default_enterprise_history_db_path()+ assert path.endswith("web_history.db")+++def test_resolve_history_db_type_mysql_when_host_set(monkeypatch) -> None:+ from jiuwenswarm.channels.web.history_store import resolve_history_db_type++ monkeypatch.delenv("WEB_DB_TYPE", raising=False)+ monkeypatch.delenv("DB_TYPE", raising=False)+ monkeypatch.setenv("WEB_DB_HOST", "127.0.0.1")+ assert resolve_history_db_type() == "mysql"+++def test_mysql_store_unavailable_without_host(monkeypatch) -> None:+ from jiuwenswarm.channels.web.history_store import ChatHistoryStore++ monkeypatch.delenv("WEB_DB_HOST", raising=False)+ store = ChatHistoryStore.for_db_type("mysql")+ assert store.backend == "mysql"+ assert store.available is False+++async def test_memory_backend_record_and_list() -> None:+ store = ChatHistoryStore.memory()+ await store.record_user(request_id="r1", session_id="s1", query="你好", ts=1000.0, user="u1")+ await store.record_assistant(+ request_id="r1", session_id="s1", content="答", event_type="chat.final", ts=1001.0,+ )+ sessions = store.list_sessions_blocking(limit=20, offset=0, user="u1")+ assert len(sessions) == 1+ detail = store.get_session_detail_blocking("s1", user="u1")+ assert detail is not None+ assert len(detail["messages"]) == 2+ assert store.get_session_detail_blocking("s1", user="other") is None++diff --git a/tests/unit_tests/test_request_ext.py b/tests/unit_tests/test_request_ext.pynew file mode 100644index 0000000000..2008e70782--- /dev/null+++ b/tests/unit_tests/test_request_ext.py@@ -0,0 +1,62 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import os++import pytest++from jiuwenswarm.common.request_ext import (+ METADATA_KEY,+ attach_to_metadata,+ build_ext_from_source,+ get_ext,+ lift_from_metadata,+ reset_ext,+ set_current,+ set_forward_headers,+)++[email protected](autouse=True)+def _reset_forward_headers():+ set_forward_headers(None)+ yield+ set_forward_headers(None)+++def test_build_ext_from_query_lists(monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_REQUEST_EXT_FORWARD_HEADERS", "user_id,group_id,bot_id")+ ext = build_ext_from_source({+ "user_id": ["u1"],+ "group_id": ["g1"],+ "other": ["x"],+ })+ assert ext == {"user_id": "u1", "group_id": "g1"}+++def test_build_ext_legacy_env_name(monkeypatch):+ monkeypatch.delenv("JIUWENSWARM_REQUEST_EXT_FORWARD_HEADERS", raising=False)+ monkeypatch.setenv("JIUWENCLAW_REQUEST_EXT_FORWARD_HEADERS", "bot_id")+ ext = build_ext_from_source({"bot_id": "b1"})+ assert ext == {"bot_id": "b1"}+++def test_attach_and_lift_roundtrip():+ meta = attach_to_metadata({"method": "chat.send"}, ext={"user_id": "u1"})+ assert meta[METADATA_KEY] == {"user_id": "u1"}+ token = lift_from_metadata(meta)+ try:+ assert get_ext() == {"user_id": "u1"}+ finally:+ reset_ext(token)+ assert get_ext() == {}+++def test_set_current_context():+ token = set_current({"group_id": "g"})+ try:+ meta = attach_to_metadata({"method": "x"})+ assert meta[METADATA_KEY] == {"group_id": "g"}+ finally:+ reset_ext(token)diff --git a/tests/unit_tests/test_start_services_ready_hint.py b/tests/unit_tests/test_start_services_ready_hint.pyindex e5f891ec74..2f9fd1a13a 100644--- a/tests/unit_tests/test_start_services_ready_hint.py+++ b/tests/unit_tests/test_start_services_ready_hint.py@@ -153,7 +153,7 @@ def test_wait_for_services_ready_prints_full_port_summary(caplog: pytest.LogCapt}processes = {"app": app, "web-dev": frontend}- with _open_ports(5173, 18092, 19000, 19001):+ with _open_ports(5173, 18092, 19000, 19001, 19002):with caplog.at_level(logging.INFO):_wait_for_services_ready(ports, processes, overall_timeout=2.0)@@ -161,11 +161,13 @@ def test_wait_for_services_ready_prints_full_port_summary(caplog: pytest.LogCaptassert "服务已启动,端口信息如下:" in joinedassert "✓ Web UI" in joinedassert "✓ AgentServer WebSocket" in joined- assert "✓ Gateway HTTP" in joined+ assert "✓ Gateway WebSocket" in joinedassert "✓ WebChannel WebSocket" in joined+ assert "✓ Web HTTP" in joinedassert "http://localhost:5173" in joined- assert "http://localhost:19001" in joined+ assert "ws://localhost:19001/tui" in joinedassert "ws://localhost:19000/ws" in joined+ assert "http://localhost:19002/api/v1" in joinedassert "ws://localhost:18092" in joined@@ -282,7 +284,7 @@ def test_web_ui_banner_prints_before_backends_ready(caplog: pytest.LogCaptureFixdef _sleep(_seconds: float) -> None:# After the first wait tick, backends come up (Web UI already bannered).- open_set.update({18092, 19000, 19001})+ open_set.update({18092, 19000, 19001, 19002})with patch("socket.socket", side_effect=lambda *a, **k: _Sock()):with patch("jiuwenswarm.start_services.time.sleep", side_effect=_sleep):diff --git a/tests/unit_tests/test_web_file_download.py b/tests/unit_tests/test_web_file_download.pyindex 5d2f2117c7..00e2b9b342 100644--- a/tests/unit_tests/test_web_file_download.py+++ b/tests/unit_tests/test_web_file_download.py@@ -1,74 +1,53 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.+from __future__ import annotationsimport base64import hashlibimport hmac-import ioimport jsonimport timefrom pathlib import Pathimport pytest+from fastapi.testclient import TestClientfrom jiuwenswarm.agents.harness.common.tools import web_file_downloadfrom jiuwenswarm.agents.harness.common.tools.web_file_download import (WebFileDownloadManager,)+from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig-class _DownloadHandlerStub:- def __init__(- self,- *,- command: str = "HEAD",- headers: dict[str, str] | None = None,- ) -> None:- self.command = command- self.headers = headers or {}- self.wfile = io.BytesIO()- self.status: int | None = None- self.response_headers: dict[str, str] = {}- self.headers_ended = False-- def send_response(self, status: int) -> None:- self.status = status-- def send_header(self, name: str, value: str) -> None:- self.response_headers[name] = value-- def end_headers(self) -> None:- self.headers_ended = True-- def _write_json(self, status: int, payload: dict) -> None:- raise AssertionError(f"unexpected JSON response: {status} {payload}")-- def log_error(self, message: str, *args: object) -> None:- raise AssertionError(message % args)---def _spa_static_handler():- """Lazy import: app_web pulls cgi (removed in Py3.13) which handler tests need."""- from jiuwenswarm.channels.web.app_web import _SpaStaticHandler-- return _SpaStaticHandler+def _download_client() -> TestClient:+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ return TestClient(create_web_http_app(channel))-def _serve_file(+def _get_download(monkeypatch: pytest.MonkeyPatch,file_path: Path,- query: dict[str, str],*,- command: str = "HEAD",- headers: dict[str, str] | None = None,-) -> _DownloadHandlerStub:+ inline: str | None = None,+ range_header: str | None = None,+ method: str = "GET",+):+ monkeypatch.setenv("JIUWENSWARM_WEB_RECEIVED_FILES", str(file_path.parent))monkeypatch.setattr(web_file_download,"validate_file_download_token",lambda _token: {"path": str(file_path)},)- handler = _DownloadHandlerStub(command=command, headers=headers)- _spa_static_handler()._handle_file_download(handler, query)- return handler+ client = _download_client()+ params: dict[str, str] = {"token": "signed-token"}+ if inline is not None:+ params["inline"] = inline+ headers = {"Range": range_header} if range_header else None+ if method == "HEAD":+ return client.head("/file-api/download", params=params, headers=headers)+ return client.get("/file-api/download", params=params, headers=headers)def _signed_token(secret: str, payload: object) -> str:@@ -120,35 +99,36 @@ def test_download_handler_uses_inline_disposition_for_preview() -> None:file_path = tmp_path / "preview sample.pdf"file_path.write_bytes(b"%PDF-1.7")- handler = _serve_file(+ response = _get_download(monkeypatch,file_path,- {"token": "signed-token", "inline": inline_value},+ inline=inline_value,+ method="HEAD",)- assert handler.status == 200- assert handler.headers_ended is True- assert handler.response_headers["Content-Type"] == "application/pdf"- assert handler.response_headers["Accept-Ranges"] == "bytes"- assert handler.response_headers["Content-Disposition"] == (+ assert response.status_code == 200+ assert response.headers["content-type"] == "application/pdf"+ assert response.headers["accept-ranges"] == "bytes"+ assert response.headers["content-disposition"] == ("inline; filename*=UTF-8''preview%20sample.pdf")@pytest.mark.parametrize(- "query", [{"token": "signed-token"}, {"token": "signed-token", "inline": "0"}]+ "inline",+ [None, "0"],)def test_download_handler_keeps_attachment_disposition_for_download(tmp_path,monkeypatch: pytest.MonkeyPatch,- query: dict[str, str],+ inline: str | None,) -> None:file_path = tmp_path / "report.pdf"file_path.write_bytes(b"%PDF-1.7")- handler = _serve_file(monkeypatch, file_path, query)+ response = _get_download(monkeypatch, file_path, inline=inline, method="HEAD")- assert handler.status == 200- assert handler.response_headers["Content-Disposition"] == (+ assert response.status_code == 200+ assert response.headers["content-disposition"] == ("attachment; filename*=UTF-8''report.pdf")@@ -171,19 +151,18 @@ def test_download_handler_serves_single_byte_range() -> None:file_path = tmp_path / "media.bin"file_path.write_bytes(b"0123456789")- handler = _serve_file(+ response = _get_download(monkeypatch,file_path,- {"token": "signed-token", "inline": "1"},- command="GET",- headers={"Range": range_header},+ inline="1",+ range_header=range_header,)- assert handler.status == 206- assert handler.response_headers["Content-Length"] == str(len(expected_body))- assert handler.response_headers["Accept-Ranges"] == "bytes"- assert handler.response_headers["Content-Range"] == expected_content_range- assert handler.wfile.getvalue() == expected_body+ assert response.status_code == 206+ assert response.headers["content-length"] == str(len(expected_body))+ assert response.headers["accept-ranges"] == "bytes"+ assert response.headers["content-range"] == expected_content_range+ assert response.content == expected_body@pytest.mark.parametrize(@@ -203,14 +182,13 @@ def test_download_handler_rejects_invalid_byte_range() -> None:file_path = tmp_path / "media.bin"file_path.write_bytes(b"0123456789")- handler = _serve_file(+ response = _get_download(monkeypatch,file_path,- {"token": "signed-token", "inline": "1"},- command="GET",- headers={"Range": range_header},+ inline="1",+ range_header=range_header,)- assert handler.status == 416- assert handler.response_headers["Content-Range"] == "bytes */10"- assert handler.wfile.getvalue() == b""+ assert response.status_code == 416+ assert response.headers["content-range"] == "bytes */10"+ assert response.content == b""diff --git a/tests/unit_tests/test_web_http.py b/tests/unit_tests/test_web_http.pynew file mode 100644index 0000000000..bfcf69328e--- /dev/null+++ b/tests/unit_tests/test_web_http.py@@ -0,0 +1,898 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Gateway Web HTTP core-route tests (avoid heavy gateway package import side-effects)."""++from __future__ import annotations++import asyncio+import importlib.util+import json+import sys+from pathlib import Path+from types import ModuleType+from typing import Any+from unittest.mock import AsyncMock++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++ROOT = Path(__file__).resolve().parents[2]+OUTBOUND_PATH = ROOT / "jiuwenswarm" / "gateway" / "channel_manager" / "web" / "outbound.py"+HTTP_PATH = ROOT / "jiuwenswarm" / "gateway" / "channel_manager" / "web" / "web_http_app.py"+SERVER_PATH = ROOT / "jiuwenswarm" / "gateway" / "channel_manager" / "web" / "web_http_server.py"+ROUTES_PATH = ROOT / "jiuwenswarm" / "gateway" / "channel_manager" / "web" / "web_http_routes.py"+++def _load_module(mod_name: str, path: Path) -> ModuleType:+ spec = importlib.util.spec_from_file_location(mod_name, path)+ assert spec and spec.loader+ mod = importlib.util.module_from_spec(spec)+ sys.modules[mod_name] = mod+ spec.loader.exec_module(mod)+ return mod+++outbound_mod = _load_module("jw_outbound_under_test", OUTBOUND_PATH)+++class _FakePeer:+ def __init__(self, frames: list[dict[str, Any]]):+ self._frames = list(frames)+ self.closed = False++ async def wait_response(self, req_id: str, *, timeout: float = 60.0) -> dict[str, Any]:+ for f in self._frames:+ if f.get("type") == "res" and f.get("id") == req_id:+ return f+ return {"type": "res", "id": req_id, "ok": False, "error": "missing", "code": "NOT_FOUND", "payload": {}}++ async def iter_sse_frames(self, req_id: str, *, timeout: float = 600.0, **_kwargs):+ for f in self._frames:+ yield f+++def app_with_mock(monkeypatch: pytest.MonkeyPatch) -> tuple[FastAPI, AsyncMock]:+ # Stub dispatch module before loading web_http_app+ dispatch_mod = ModuleType("jiuwenswarm.gateway.channel_manager.web.web_http_dispatch")+ dispatch_mock = AsyncMock()+ dispatch_mod.dispatch_http_request = dispatch_mock # type: ignore[attr-defined]+ sys.modules["jiuwenswarm.gateway.channel_manager.web.web_http_dispatch"] = dispatch_mod++ # Minimal package parents so relative imports in web_http_app resolve if any+ for pkg in (+ "jiuwenswarm",+ "jiuwenswarm.gateway",+ "jiuwenswarm.gateway.channel_manager",+ "jiuwenswarm.gateway.channel_manager.web",+ ):+ if pkg not in sys.modules:+ m = ModuleType(pkg)+ m.__path__ = [] # type: ignore[attr-defined]+ sys.modules[pkg] = m++ # Real route table (no Gateway imports) so create_web_http_app can register workspace routes.+ _load_module(+ "jiuwenswarm.gateway.channel_manager.web.web_http_routes",+ ROUTES_PATH,+ )++ # web_http_app imports file/sessions compat; stub them (empty package __path__ above).+ sessions_compat = ModuleType("jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat")+ sessions_compat.register_sessions_compat_routes = lambda app: None # type: ignore[attr-defined]+ sessions_compat.catalog_sessions_compat_entries = lambda: [] # type: ignore[attr-defined]+ sys.modules["jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat"] = sessions_compat++ file_compat = ModuleType("jiuwenswarm.gateway.channel_manager.web.web_http_file_compat")+ file_compat.register_file_compat_routes = lambda app: None # type: ignore[attr-defined]+ file_compat.catalog_file_compat_entries = lambda: [] # type: ignore[attr-defined]+ sys.modules["jiuwenswarm.gateway.channel_manager.web.web_http_file_compat"] = file_compat++ web_http_app = _load_module("jw_web_http_app_under_test", HTTP_PATH)+ channel = object()+ app = web_http_app.create_web_http_app(channel)+ return app, dispatch_mock+++def test_bind_http_session_create_does_not_inject_session_id():+ sid, params = outbound_mod.bind_http_session("session.create", {})+ assert "session_id" not in params+ assert sid.startswith("webhttp_")+ assert params.get("create_token")+++def test_bind_http_session_create_keeps_client_create_token():+ _, params = outbound_mod.bind_http_session(+ "session.create", {"create_token": "client-token-1"},+ )+ assert params["create_token"] == "client-token-1"+++def test_bind_http_session_create_strips_client_session_id():+ sid, params = outbound_mod.bind_http_session(+ "session.create", {"session_id": "web_should_not_go_to_agent"},+ )+ assert "session_id" not in params+ assert sid.startswith("webhttp_")+ assert sid != "web_should_not_go_to_agent"+++def test_bind_http_session_bind_param_false_does_not_invent_session_id():+ sid, params = outbound_mod.bind_http_session(+ "permissions.tools.get", {}, bind_param=False,+ )+ assert "session_id" not in params+ assert sid.startswith("webhttp_")+++def test_bind_http_session_bind_param_false_keeps_client_session_id():+ sid, params = outbound_mod.bind_http_session(+ "skills.list",+ {"session_id": "web_sess"},+ bind_param=False,+ )+ assert params["session_id"] == "web_sess"+ assert sid == "web_sess"+++def test_bind_http_session_chat_keeps_session_id():+ sid, params = outbound_mod.bind_http_session("chat.send", {"query": "hi"})+ assert params["session_id"] == sid+ assert sid.startswith("webhttp_")+++def test_http_json_outbound_wait_response():+ async def _run():+ peer = outbound_mod.HttpJsonOutbound()+ await peer.send(json.dumps({"type": "res", "id": "r1", "ok": True, "payload": {"a": 1}}))+ frame = await peer.wait_response("r1", timeout=2)+ assert frame["ok"] is True+ assert frame["payload"]["a"] == 1++ asyncio.run(_run())+++def test_http_sse_outbound_iter_ends_on_final():+ async def _run():+ peer = outbound_mod.HttpSseOutbound()+ await peer.send(json.dumps({"type": "res", "id": "r1", "ok": True, "payload": {"accepted": True}}))+ await peer.send(json.dumps({"type": "event", "event": "chat.delta", "payload": {"content": "x"}}))+ await peer.send(json.dumps({"type": "event", "event": "chat.final", "payload": {"content": "x"}}))+ events = []+ async for f in peer.iter_sse_frames("r1", timeout=2):+ events.append(f)+ assert any(e.get("event") == "chat.delta" for e in events)+ assert events[-1].get("event") == "chat.final"++ asyncio.run(_run())+++def test_http_sse_outbound_iter_ends_on_history_done():+ async def _run():+ peer = outbound_mod.HttpSseOutbound()+ await peer.send(json.dumps({"type": "res", "id": "r1", "ok": True, "payload": {"accepted": True}}))+ await peer.send(json.dumps({+ "type": "event", "event": "history.message",+ "payload": {"message": {"role": "user", "content": "hi"}},+ }))+ await peer.send(json.dumps({+ "type": "event", "event": "history.message",+ "payload": {"status": "done", "page_idx": 1, "total_pages": 1},+ }))+ events = []+ async for f in peer.iter_sse_frames("r1", timeout=2):+ events.append(f)+ assert events[-1].get("payload", {}).get("status") == "done"++ asyncio.run(_run())+++def test_http_dispatch_registers_outbound_not_ws(monkeypatch: pytest.MonkeyPatch):+ """S3: HTTP path must use request Outbound tables, not register_ws."""+ from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+ from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig+ from jiuwenswarm.gateway.channel_manager.web import web_http_dispatch as disp++ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ register_calls: list[Any] = []++ async def _no_register(ws, rk, **kwargs):+ register_calls.append((ws, rk))++ monkeypatch.setattr(channel, "register_ws", _no_register)++ async def _handler(ws, req_id, params, session_id, **kwargs):+ await channel.send_response(ws, req_id, ok=True, payload={"pong": True})++ channel.register_method("connection.status", _handler)++ async def _run():+ out, rid, sid = await disp.dispatch_http_request(+ channel,+ method="connection.status",+ params={},+ headers={"X-Request-Id": "req-s3"},+ use_sse=False,+ )+ try:+ assert register_calls == []+ assert out.outbound_id in channel._request_outbounds+ assert getattr(out, "is_http_outbound", False) is True+ frame = await out.wait_response(rid, timeout=2)+ assert frame["ok"] is True+ assert frame["payload"]["pong"] is True+ finally:+ await channel.unregister_request_outbound(out)+ assert out.outbound_id not in channel._request_outbounds++ asyncio.run(_run())+++def test_http_sse_unregister_on_cancel():+ """S4: client cancel / stop clears request outbound routing tables."""+ from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+ from jiuwenswarm.gateway.channel_manager.web.outbound import HttpSseOutbound+ from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig++ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())++ async def _run():+ out = HttpSseOutbound(session_id="sess-cancel")+ oid = channel.register_request_outbound(out)+ assert oid in channel._request_outbounds+ assert oid in channel._session_request_outbounds.get("sess-cancel", set())++ # Simulate client disconnect mid-stream: unregister like _stream finally.+ await channel.unregister_request_outbound(out)+ assert oid not in channel._request_outbounds+ assert not channel._session_request_outbounds+ assert out.closed is True++ # stop_http / clear_request_outbounds also empties leftovers.+ out2 = HttpSseOutbound(session_id="sess-stop")+ channel.register_request_outbound(out2)+ await channel.clear_request_outbounds()+ assert channel._request_outbounds == {}+ assert channel._session_request_outbounds == {}+ assert out2.closed is True++ asyncio.run(_run())+++def test_sse_idle_timeout_ends_stream():+ async def _run():+ peer = outbound_mod.HttpSseOutbound()+ events = []+ async for f in peer.iter_sse_frames(+ "r1", timeout=5.0, idle_timeout=0.15, keepalive=0.05,+ ):+ events.append(f)+ if f.get("event") == "chat.error":+ break+ assert any(+ e.get("event") == "chat.error"+ and "idle" in str((e.get("payload") or {}).get("error", ""))+ for e in events+ )++ asyncio.run(_run())+++def test_history_json_collects_messages(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"accepted": True}},+ {+ "type": "event",+ "event": "history.message",+ "payload": {"message": {"role": "user", "content": "hi"}, "page_idx": 1, "total_pages": 1},+ },+ {+ "type": "event",+ "event": "history.message",+ "payload": {"status": "done", "page_idx": 1, "total_pages": 1},+ },+ ])+ return peer, rid, "s1"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get("/api/v1/sessions/s1/history")+ assert r.status_code == 200+ data = r.json()["data"]+ assert data["messages"][0]["content"] == "hi"+ assert data["page_idx"] == 1+ assert dispatch.await_args.kwargs["params"]["page_idx"] == 1+++def test_doc_ui_and_openapi(app_with_mock):+ app, _dispatch = app_with_mock+ client = TestClient(app, follow_redirects=False)+ r = client.get("/doc")+ assert r.status_code == 200+ assert "swagger" in r.text.lower()+ r = client.get("/doc/")+ assert r.status_code == 307+ assert r.headers["location"] in ("/doc", "http://testserver/doc")+ spec = client.get("/openapi.json").json()+ assert "/api/v1/health" in spec["paths"]+ assert "/api/v1/chat/completions" in spec["paths"]+ assert "/api/v1/chat/send" not in spec["paths"]+ assert spec["paths"]["/api/v1/sessions"]["post"]["tags"] == ["sessions"]+ post_body = spec["paths"]["/api/v1/sessions"]["post"]["requestBody"]["content"]["application/json"]+ example = post_body.get("example")+ if example is None:+ example = (post_body.get("examples") or {}).get("empty", {}).get("value")+ if example is None:+ example = post_body.get("schema", {}).get("example")+ assert example == {}+ assert not post_body.get("schema", {}).get("required")+++def test_health(app_with_mock):+ app, _dispatch = app_with_mock+ client = TestClient(app)+ r = client.get("/api/v1/health")+ assert r.status_code == 200+ body = r.json()+ assert body["ok"] is True+ assert body["data"]["status"] == "ready"+++def test_connection_status(app_with_mock):+ app, dispatch = app_with_mock+ peer = _FakePeer([+ {"type": "res", "id": "fixed", "ok": True, "payload": {"agent_ready": True, "protocol_version": "1.0"}},+ ])++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "fixed"+ peer._frames[0]["id"] = rid+ return peer, rid, "sess"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get("/api/v1/connection/status", headers={"X-Request-Id": "fixed"})+ assert r.status_code == 200+ assert r.json()["data"]["agent_ready"] is True+ dispatch.assert_awaited()+ assert dispatch.await_args.kwargs["method"] == "connection.status"+++def test_sessions_list_create_delete(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ method = kwargs["method"]+ rid = kwargs.get("request_id") or "r"+ if method == "session.list":+ payload = {"sessions": [{"session_id": "s1"}], "total": 1, "limit": 20, "offset": 0}+ elif method == "session.create":+ payload = {"session_id": (kwargs.get("params") or {}).get("session_id") or "s_new"}+ else:+ payload = {"deleted": True}+ peer = _FakePeer([{"type": "res", "id": rid, "ok": True, "payload": payload}])+ return peer, rid, "s1"++ dispatch.side_effect = _disp+ client = TestClient(app)++ r = client.get("/api/v1/sessions")+ assert r.status_code == 200+ assert r.json()["data"]["total"] == 1++ r = client.post("/api/v1/sessions", json={"session_id": "s_x"})+ assert r.status_code == 201+ assert r.json()["data"]["session_id"] == "s_x"++ r = client.delete("/api/v1/sessions/s_x")+ assert r.status_code == 200+ assert r.json()["ok"] is True+++def test_chat_completions_sse(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"accepted": True}},+ {"type": "event", "event": "chat.delta", "payload": {"content": "hi"}},+ {"type": "event", "event": "chat.final", "payload": {"content": "hi"}},+ ])+ return peer, rid, "sess_1"++ dispatch.side_effect = _disp+ client = TestClient(app)+ with client.stream(+ "POST",+ "/api/v1/chat/completions",+ json={"session_id": "sess_1", "query": "hello"},+ headers={"Accept": "text/event-stream", "X-Request-Id": "r"},+ ) as resp:+ assert resp.status_code == 200+ text = "".join(resp.iter_text())+ assert "event: chat.delta" in text+ assert "event: chat.final" in text+ dispatch.assert_called()+ assert dispatch.await_args.kwargs["method"] == "chat.send"+++def test_chat_send_compat_path(app_with_mock):+ """Compat path /chat/send still works; OpenAPI only exposes /chat/completions."""+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"accepted": True}},+ {"type": "event", "event": "chat.final", "payload": {}},+ ])+ return peer, rid, "sess_1"++ dispatch.side_effect = _disp+ client = TestClient(app)+ with client.stream(+ "POST",+ "/api/v1/chat/send",+ json={"session_id": "sess_1", "query": "hello"},+ headers={"Accept": "text/event-stream", "X-Request-Id": "r"},+ ) as resp:+ assert resp.status_code == 200+ text = "".join(resp.iter_text())+ assert "event: chat.final" in text+ paths = client.get("/openapi.json").json()["paths"]+ assert "/api/v1/chat/send" not in paths+ assert "/api/v1/chat/completions" in paths+ assert dispatch.await_args.kwargs["method"] == "chat.send"+++def test_resolve_web_http_port_defaults_to_19002(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("GATEWAY_WEB_HTTP_PORT", raising=False)+ monkeypatch.delenv("GATEWAY_PORT", raising=False)+ web_http_server = _load_module(+ "jw_web_http_server_under_test",+ SERVER_PATH,+ )+ assert web_http_server.resolve_web_http_port(19000) == 19002+++def test_resolve_web_http_port_env_override(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("GATEWAY_WEB_HTTP_PORT", "19111")+ web_http_server = _load_module(+ "jw_web_http_server_override_under_test",+ SERVER_PATH,+ )+ assert web_http_server.resolve_web_http_port(19000) == 19111+++def test_resolve_web_http_port_skips_gateway_port(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("GATEWAY_WEB_HTTP_PORT", raising=False)+ monkeypatch.setenv("GATEWAY_PORT", "19002")+ web_http_server = _load_module(+ "jw_web_http_server_skip_gw_under_test",+ SERVER_PATH,+ )+ assert web_http_server.resolve_web_http_port(19000) == 19003+++def test_resolve_web_http_port_follows_ws_port_offset(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("GATEWAY_WEB_HTTP_PORT", raising=False)+ monkeypatch.delenv("GATEWAY_PORT", raising=False)+ web_http_server = _load_module(+ "jw_web_http_server_offset_under_test",+ SERVER_PATH,+ )+ assert web_http_server.resolve_web_http_port(19100) == 19102+++def test_resolve_web_http_port_invalid_env_falls_back(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("GATEWAY_WEB_HTTP_PORT", "auto")+ monkeypatch.delenv("GATEWAY_PORT", raising=False)+ web_http_server = _load_module(+ "jw_web_http_server_invalid_env_under_test",+ SERVER_PATH,+ )+ assert web_http_server.resolve_web_http_port(19000) == 19002+++def test_resolve_web_http_timeouts_defaults_and_env(monkeypatch: pytest.MonkeyPatch):+ for key in (+ "GATEWAY_WEB_HTTP_SSE_TIMEOUT",+ "GATEWAY_WEB_HTTP_SSE_IDLE_TIMEOUT",+ "GATEWAY_WEB_HTTP_SSE_KEEPALIVE",+ "GATEWAY_WEB_HTTP_UNARY_TIMEOUT",+ "GATEWAY_WEB_HTTP_HISTORY_TIMEOUT",+ ):+ monkeypatch.delenv(key, raising=False)+ mod = _load_module("jw_web_http_timeouts_default", SERVER_PATH)+ assert mod.resolve_web_http_sse_timeout() == 600.0+ assert mod.resolve_web_http_sse_idle_timeout() == 0.0+ assert mod.resolve_web_http_sse_keepalive() == 30.0+ assert mod.resolve_web_http_unary_timeout() == 120.0+ assert mod.resolve_web_http_history_timeout() == 60.0++ monkeypatch.setenv("GATEWAY_WEB_HTTP_SSE_TIMEOUT", "90")+ monkeypatch.setenv("GATEWAY_WEB_HTTP_SSE_IDLE_TIMEOUT", "45")+ monkeypatch.setenv("GATEWAY_WEB_HTTP_UNARY_TIMEOUT", "15")+ mod2 = _load_module("jw_web_http_timeouts_env", SERVER_PATH)+ assert mod2.resolve_web_http_sse_timeout() == 90.0+ assert mod2.resolve_web_http_sse_idle_timeout() == 45.0+ assert mod2.resolve_web_http_unary_timeout() == 15.0+++def test_chat_interrupt(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([{"type": "res", "id": rid, "ok": True, "payload": {"accepted": True}}])+ return peer, rid, "sess_1"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.post("/api/v1/chat/sess_1/actions/interrupt", json={})+ assert r.status_code == 200+ assert dispatch.await_args.kwargs["method"] == "chat.interrupt"+++web_http_routes = _load_module(+ "jw_web_http_routes_under_test",+ ROUTES_PATH,+)+++def test_mapped_route_table_unique_http_surfaces():+ web_http_routes.validate_mapped_routes()+ keys = {+ (r.http_method, r.path) for r in web_http_routes.MAPPED_ROUTES+ }+ assert len(keys) == len(web_http_routes.MAPPED_ROUTES)+ rpc_methods = {r.rpc_method for r in web_http_routes.MAPPED_ROUTES}+ assert "config.get" in rpc_methods+ assert "models.list" in rpc_methods+ assert "locale.get_conf" in rpc_methods+ assert "locale.set_conf" in rpc_methods+ assert "cron.job.list" in rpc_methods+ assert "cron.job.run_now" in rpc_methods+ assert "permissions.tools.get" in rpc_methods+ assert "skills.enterprise.list" in rpc_methods+ assert "harness.export" in rpc_methods+++def test_web_http_catalog_lists_settings_and_workspace(app_with_mock):+ app, _dispatch = app_with_mock+ client = TestClient(app)+ r = client.get("/api/v1/catalog")+ assert r.status_code == 200+ body = r.json()+ assert body["ok"] is True+ methods = {row["rpc_method"] for row in body["data"]["routes"]}+ assert "config.get" in methods+ assert "models.list" in methods+ assert "locale.set_conf" in methods+ assert "cron.job.preview" in methods+ assert "permissions.owner_scopes.get" in methods+ assert "skills.list" in methods+ assert "harness.packages" in methods+ assert "chat.send" in methods+++def test_permissions_tools_get(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"tools": {"bash": "ask"}}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get("/api/v1/permissions/tools")+ assert r.status_code == 200+ assert r.json()["data"]["tools"]["bash"] == "ask"+ assert r.headers["x-web-rpc-method"] == "permissions.tools.get"+ assert dispatch.await_args.kwargs["method"] == "permissions.tools.get"+ assert dispatch.await_args.kwargs["bind_session_param"] is False+ assert "session_id" not in (dispatch.await_args.kwargs.get("params") or {})+++def test_permissions_tools_patch_path_param(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"tools": {"bash": "deny"}}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.patch("/api/v1/permissions/tools/bash", json={"level": "deny"})+ assert r.status_code == 200+ kwargs = dispatch.await_args.kwargs+ assert kwargs["method"] == "permissions.tools.update"+ assert kwargs["params"]["tool"] == "bash"+ assert kwargs["params"]["level"] == "deny"+++def test_skills_enterprise_list_tenant_headers(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"skills": []}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get(+ "/api/v1/skills/enterprise",+ headers={"X-Group-Id": "g1", "X-Bot-Id": "b1", "X-User-Id": "u1"},+ )+ assert r.status_code == 200+ params = dispatch.await_args.kwargs["params"]+ assert dispatch.await_args.kwargs["method"] == "skills.enterprise.list"+ assert params["group_id"] == "g1"+ assert params["bot_id"] == "b1"+ assert params["user_id"] == "u1"+++def test_harness_packages_get(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {+ "type": "res",+ "id": rid,+ "ok": True,+ "payload": {"packages": [], "active_package_ids": []},+ },+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get("/api/v1/harness/packages", headers={"X-Session-Id": "web_1"})+ assert r.status_code == 200+ assert dispatch.await_args.kwargs["method"] == "harness.packages"+ assert r.json()["metadata"]["rpc_method"] == "harness.packages"+++def test_skills_evolution_get_forwards_name_query(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"exists": False, "entries": []}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get(+ "/api/v1/skills/evolution?name=demo-skill&session_id=web_1",+ headers={"X-Session-Id": "web_1"},+ )+ assert r.status_code == 200+ params = dispatch.await_args.kwargs["params"]+ assert dispatch.await_args.kwargs["method"] == "skills.evolution.get"+ assert params["name"] == "demo-skill"+ assert params["session_id"] == "web_1"+++def test_skills_skillnet_install_status_forwards_install_id(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"success": True, "status": "pending"}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get(+ "/api/v1/skills/skillnet/install-status?install_id=job-abc&session_id=web_1",+ headers={"X-Session-Id": "web_1"},+ )+ assert r.status_code == 200+ params = dispatch.await_args.kwargs["params"]+ assert dispatch.await_args.kwargs["method"] == "skills.skillnet.install_status"+ assert params["install_id"] == "job-abc"+ assert params["session_id"] == "web_1"+++def test_config_get(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"app_version": "1.0"}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get("/api/v1/config")+ assert r.status_code == 200+ assert r.json()["data"]["app_version"] == "1.0"+ assert r.headers["x-web-rpc-method"] == "config.get"+ assert dispatch.await_args.kwargs["method"] == "config.get"+ assert dispatch.await_args.kwargs["bind_session_param"] is False+++def test_models_list(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {+ "type": "res",+ "id": rid,+ "ok": True,+ "payload": {"models": [{"model_name": "m1"}], "active_model": "m1"},+ },+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get("/api/v1/models")+ assert r.status_code == 200+ assert r.json()["data"]["active_model"] == "m1"+ assert dispatch.await_args.kwargs["method"] == "models.list"+++def test_locale_put(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"preferred_language": "en"}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.put("/api/v1/locale", json={"preferred_language": "en"})+ assert r.status_code == 200+ assert dispatch.await_args.kwargs["method"] == "locale.set_conf"+ assert dispatch.await_args.kwargs["params"]["preferred_language"] == "en"+++def test_cron_job_list_and_toggle(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"jobs": []}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.get(+ "/api/v1/cron/jobs",+ params={"project_id": "default"},+ headers={"X-Group-Id": "g1", "X-User-Id": "u1"},+ )+ assert r.status_code == 200+ assert dispatch.await_args.kwargs["method"] == "cron.job.list"+ params = dispatch.await_args.kwargs["params"]+ assert params["project_id"] == "default"+ assert params["group_id"] == "g1"+ assert params["user_id"] == "u1"++ async def _disp_toggle(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"job": {"id": "job-1"}}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp_toggle+ r2 = client.post(+ "/api/v1/cron/jobs/job-1/actions/toggle",+ json={"enabled": True},+ headers={"X-Group-Id": "g1"},+ )+ assert r2.status_code == 200+ tparams = dispatch.await_args.kwargs["params"]+ assert dispatch.await_args.kwargs["method"] == "cron.job.toggle"+ assert tparams["id"] == "job-1"+ assert tparams["enabled"] is True+ assert tparams["group_id"] == "g1"+++def test_cron_job_update_patch_body(app_with_mock):+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([+ {"type": "res", "id": rid, "ok": True, "payload": {"job": {"id": "job-1"}}},+ ])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ r = client.patch(+ "/api/v1/cron/jobs/job-1",+ json={"patch": {"name": "n2"}},+ )+ assert r.status_code == 200+ assert dispatch.await_args.kwargs["method"] == "cron.job.update"+ assert dispatch.await_args.kwargs["params"]["id"] == "job-1"+ assert dispatch.await_args.kwargs["params"]["patch"]["name"] == "n2"+++def test_openapi_includes_settings_and_workspace(app_with_mock):+ app, _dispatch = app_with_mock+ spec = TestClient(app).get("/openapi.json").json()+ paths = spec["paths"]+ assert "/api/v1/config" in paths+ assert "/api/v1/models" in paths+ assert "/api/v1/locale" in paths+ assert "/api/v1/cron/jobs" in paths+ assert "/api/v1/cron/jobs/{id}/actions/run-now" in paths+ assert "/api/v1/permissions/tools" in paths+ assert "/api/v1/skills/enterprise" in paths+ assert "/api/v1/harness/packages" in paths+ assert "/api/v1/catalog" in paths+++def _fill_mapped_path(path: str) -> str:+ return (+ path.replace("{tool}", "bash")+ .replace("{id}", "rule-1")+ .replace("{name}", "demo-skill")+ .replace("{package_id}", "native")+ )+++def test_mapped_routes_dispatch_rpc_method(app_with_mock):+ """Every table-driven HTTP surface reaches dispatch with the declared rpc_method."""+ app, dispatch = app_with_mock++ async def _disp(*args, **kwargs):+ rid = kwargs.get("request_id") or "r"+ peer = _FakePeer([{"type": "res", "id": rid, "ok": True, "payload": {"ok": True}}])+ return peer, rid, "s"++ dispatch.side_effect = _disp+ client = TestClient(app)+ failures: list[str] = []+ for route in web_http_routes.MAPPED_ROUTES:+ url = "/api/v1" + _fill_mapped_path(route.path)+ req_kwargs: dict[str, Any] = {}+ if route.accept_body:+ req_kwargs["json"] = {}+ resp = client.request(route.http_method, url, **req_kwargs)+ expect = 201 if route.created else 200+ got_method = (+ dispatch.await_args.kwargs.get("method") if dispatch.await_args else None+ )+ if resp.status_code != expect or got_method != route.rpc_method:+ failures.append(+ f"{route.http_method} {url} -> {resp.status_code} "+ f"method={got_method!r} want {expect}/{route.rpc_method} body={resp.text[:200]}"+ )+ assert not failures, "\n".join(failures)diff --git a/tests/unit_tests/test_web_http_file_compat.py b/tests/unit_tests/test_web_http_file_compat.pynew file mode 100644index 0000000000..06ec2c1e2f--- /dev/null+++ b/tests/unit_tests/test_web_http_file_compat.py@@ -0,0 +1,210 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Gateway Web HTTP ``/file-api/*`` and ``/share-api/*`` compat."""++from __future__ import annotations++from pathlib import Path+from urllib.parse import quote++import pytest+from fastapi.testclient import TestClient++from jiuwenswarm.agents.harness.common.tools.web_file_download import (+ WebFileDownloadManager,+ build_file_download_info,+)+from jiuwenswarm.channels.web.history_store import ChatHistoryStore, set_default_store+from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app+from jiuwenswarm.gateway.channel_manager.web.file_http import FileHttpRoots+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig+++def file_client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("AGENT_RUNTIME", raising=False)+ agent_root = tmp_path / "agent"+ workspace = agent_root / "workspace"+ workspace.mkdir(parents=True)+ (workspace / "hello.md").write_text("# hi\n", encoding="utf-8")+ image_path = agent_root / "sessions" / "s1" / "uploads" / "image.png"+ image_path.parent.mkdir(parents=True)+ image_bytes = b"\x89PNG\r\n\x1a\nimage-data"+ image_path.write_bytes(image_bytes)++ roots = FileHttpRoots(+ project_root=tmp_path,+ workspace_root=agent_root,+ agent_teams_root=tmp_path / "agent-teams",+ logs_root=tmp_path / "logs",+ auto_harness_root=tmp_path / "auto-harness",+ )+ for d in (roots.agent_teams_root, roots.logs_root, roots.auto_harness_root):+ d.mkdir(parents=True, exist_ok=True)++ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ app = create_web_http_app(channel)+ app.state.file_http_roots = roots+ client = TestClient(app)+ return client, roots, image_path, image_bytes+++def test_list_and_read_markdown(file_client):+ client, _roots, _img, _bytes = file_client+ r = client.get("/file-api/list-files", params={"dir": "agent/workspace"})+ assert r.status_code == 200+ names = {f["name"] for f in r.json()["files"]}+ assert "hello.md" in names++ r = client.get(+ "/file-api/file-content",+ params={"path": "agent/workspace/hello.md", "encoding": "utf-8"},+ )+ assert r.status_code == 200+ assert r.text.startswith("# hi")+++def test_raw_file(file_client):+ client, roots, image_path, image_bytes = file_client+ rel = str(image_path.relative_to(roots.project_root)).replace("\\", "/")+ r = client.get("/file-api/raw-file", params={"path": rel})+ assert r.status_code == 200+ assert r.headers["content-type"].startswith("image/png")+ assert r.content == image_bytes+++def test_path_traversal_forbidden(file_client):+ client, _roots, _img, _bytes = file_client+ r = client.get("/file-api/list-files", params={"dir": "../"})+ assert r.status_code == 403+++def test_default_roots_allow_legacy_agent_workspace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ """Personal layout: ``agent/workspace`` under user workspace, not only multi-tenant agent root."""+ user_root = tmp_path / "home" / ".jiuwenswarm"+ agent_ws = user_root / "agent" / "workspace"+ agent_ws.mkdir(parents=True)+ (agent_ws / "note.md").write_text("ok", encoding="utf-8")+ tenant_agent = user_root / "service_default" / "agent_default" / "agent"+ tenant_agent.mkdir(parents=True)++ monkeypatch.setattr(+ "jiuwenswarm.common.utils.get_user_workspace_dir",+ lambda: user_root,+ )+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.get_agent_root_dir",+ lambda: tenant_agent,+ )++ from jiuwenswarm.gateway.channel_manager.web.file_http import default_file_http_roots, list_files++ roots = default_file_http_roots()+ code, payload = list_files(roots, "agent/workspace")+ assert code == 200+ assert any(f["name"] == "note.md" for f in payload["files"])+++def test_download_token_and_range(file_client, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ client, _roots, _img, _bytes = file_client+ secret = "s" * 32+ monkeypatch.setenv("JIUWENSWARM_FILE_DOWNLOAD_SECRET", secret)+ recv = tmp_path / "recv"+ recv.mkdir()+ monkeypatch.setenv("JIUWENSWARM_WEB_RECEIVED_FILES", str(recv))+ WebFileDownloadManager.reset_instance()+ target = recv / "dl.bin"+ target.write_bytes(b"0123456789")+ info = build_file_download_info(str(target), "dl.bin", "sess")+ token = info["download_token"]++ r = client.head(f"/file-api/download?token={quote(token)}")+ assert r.status_code == 200+ assert r.headers["content-length"] == "10"++ r = client.get(+ f"/file-api/download?token={quote(token)}",+ headers={"Range": "bytes=2-5"},+ )+ assert r.status_code == 206+ assert r.content == b"2345"+++def test_share_enterprise_uses_history_store(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AGENT_RUNTIME", "kub")+ store = ChatHistoryStore.memory()+ set_default_store(store)+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ client = TestClient(create_web_http_app(channel))++ import asyncio++ async def _seed() -> None:+ await store.record_user(+ request_id="r1", session_id="share-1", query="hello", ts=1.0, user="u1",+ )++ asyncio.run(_seed())++ r = client.get("/share-api/snapshot", params={"session_id": "share-1", "user": "u1"})+ assert r.status_code == 200+ body = r.json()+ assert body["snapshot"]["session_id"] == "share-1"+ assert isinstance(body["snapshot"]["records"], list)+++def test_push_lands_on_gateway(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AGENT_RUNTIME", "kub")+ monkeypatch.setenv("JIUWENSWARM_WEB_RECEIVED_FILES", str(tmp_path / "recv"))+ monkeypatch.setenv("JIUWENSWARM_FILE_DOWNLOAD_SECRET", "t" * 32)+ WebFileDownloadManager.reset_instance()++ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ client = TestClient(create_web_http_app(channel))+ r = client.post(+ "/file-api/push",+ files={"file": ("a.txt", b"hello-push", "application/octet-stream")},+ data={"session_id": "s1", "filename": "a.txt"},+ )+ assert r.status_code == 200+ body = r.json()+ assert body["success"] is True+ assert body["download_token"]+ assert Path(body["file_path"]).is_file()++ r2 = client.get("/file-api/download", params={"token": body["download_token"]})+ assert r2.status_code == 200+ assert r2.content == b"hello-push"+++def test_push_sanitizes_path_traversal_filename(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ from jiuwenswarm.gateway.channel_manager.web.file_http import (+ is_path_under_directory,+ received_files_dir,+ )++ monkeypatch.setenv("AGENT_RUNTIME", "kub")+ recv = tmp_path / "recv"+ monkeypatch.setenv("JIUWENSWARM_WEB_RECEIVED_FILES", str(recv))+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ client = TestClient(create_web_http_app(channel))+ r = client.post(+ "/file-api/push",+ files={"file": ("evil.txt", b"bad", "application/octet-stream")},+ data={"session_id": "s1", "filename": "../../../outside.txt"},+ )+ assert r.status_code == 200+ saved = Path(r.json()["file_path"]).resolve()+ assert is_path_under_directory(received_files_dir(), saved)+ assert saved.name.endswith("_outside.txt")+ assert not (tmp_path / "outside.txt").exists()+++def test_catalog_includes_file_routes(file_client):+ client, *_ = file_client+ r = client.get("/api/v1/catalog")+ assert r.status_code == 200+ paths = {row["path"] for row in r.json()["data"]["routes"]}+ assert "/file-api/list-files" in paths+ assert "/share-api/snapshot" in pathsdiff --git a/tests/unit_tests/test_web_http_sessions_compat.py b/tests/unit_tests/test_web_http_sessions_compat.pynew file mode 100644index 0000000000..4bdd6d9216--- /dev/null+++ b/tests/unit_tests/test_web_http_sessions_compat.py@@ -0,0 +1,86 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Gateway ``GET /api/sessions*`` compat over ChatHistoryStore."""++from __future__ import annotations++import pytest+from fastapi.testclient import TestClient++from jiuwenswarm.channels.web.history_store import ChatHistoryStore, set_default_store+from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig+++def history_client(tmp_path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AGENT_RUNTIME", "kub")+ store = ChatHistoryStore.memory()+ set_default_store(store)+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ client = TestClient(create_web_http_app(channel))+ return client, store+++async def test_api_sessions_list_and_detail(history_client):+ client, store = history_client+ await store.record_user(+ request_id="r1", session_id="s1", query="hello", ts=1.0, user="u1",+ )+ await store.record_assistant(+ request_id="r1",+ session_id="s1",+ content="hi",+ event_type="chat.final",+ ts=2.0,+ )++ r = client.get("/api/sessions", params={"limit": 10, "user": "u1"})+ assert r.status_code == 200+ body = r.json()+ assert len(body["sessions"]) == 1+ assert body["sessions"][0]["session_id"] == "s1"++ r = client.get("/api/sessions/s1", params={"user": "u1"})+ assert r.status_code == 200+ detail = r.json()+ assert detail["session_id"] == "s1"+ assert isinstance(detail.get("messages"), list)+ assert len(detail["messages"]) >= 2++ r = client.get("/api/sessions/s1", params={"user": "other"})+ assert r.status_code == 404+ assert r.json()["error"] == "not_found"++ r = client.get("/api/sessions/missing")+ assert r.status_code == 404+++def test_api_sessions_empty_when_no_store(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("AGENT_RUNTIME", raising=False)+ # Force unavailable default by pointing mysql without host via empty memory reset.+ store = ChatHistoryStore(settings=None, memory=False)+ set_default_store(store)+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ client = TestClient(create_web_http_app(channel))+ r = client.get("/api/sessions")+ assert r.status_code == 200+ assert r.json()["sessions"] == []+++def test_catalog_includes_sessions_compat(history_client):+ client, _store = history_client+ r = client.get("/api/v1/catalog")+ assert r.status_code == 200+ paths = {row["path"] for row in r.json()["data"]["routes"]}+ assert "/api/sessions" in paths+ assert "/api/sessions/{session_id}" in paths+++def test_openapi_includes_sessions_compat(history_client):+ client, _store = history_client+ paths = client.get("/openapi.json").json()["paths"]+ assert "/api/sessions" in paths+ assert "/api/sessions/{session_id}" in pathsdiff --git a/tests/unit_tests/test_web_http_settings_handlers.py b/tests/unit_tests/test_web_http_settings_handlers.pynew file mode 100644index 0000000000..24d3d2debd--- /dev/null+++ b/tests/unit_tests/test_web_http_settings_handlers.py@@ -0,0 +1,167 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Settings Web HTTP routes through real WebChannel handlers (no dispatch mock)."""++from __future__ import annotations++from fastapi.testclient import TestClient++from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app+from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (+ WebHandlersBindParams,+ _register_web_handlers,+)+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig+++class _FakeCron:+ def __init__(self) -> None:+ self.jobs: dict[str, dict] = {+ "job-1": {+ "id": "job-1",+ "name": "n1",+ "enabled": True,+ "project_id": "default",+ },+ }+ self.run_calls: list[str] = []++ def job_metadata(self) -> dict:+ return {"modes": []}++ async def list_jobs(self, params=None):+ return list(self.jobs.values())++ async def get_job(self, job_id, **kwargs):+ return self.jobs.get(job_id)++ async def update_job(self, job_id, patch, **kwargs):+ if job_id not in self.jobs:+ raise KeyError(job_id)+ self.jobs[job_id] = {**self.jobs[job_id], **dict(patch or {})}+ return self.jobs[job_id]++ async def delete_job(self, job_id, **kwargs):+ return self.jobs.pop(job_id, None) is not None++ async def toggle_job(self, job_id, enabled, **kwargs):+ if job_id not in self.jobs:+ raise KeyError(job_id)+ self.jobs[job_id]["enabled"] = bool(enabled)+ return self.jobs[job_id]++ async def preview_job(self, job_id, count=5, **kwargs):+ if job_id not in self.jobs:+ raise KeyError(job_id)+ n = int(count) if count is not None else 5+ return [{"wake_at": "2026-01-01T00:00:00Z", "push_at": "2026-01-01T00:00:00Z"}] * n++ async def run_now_info(self, job_id):+ if job_id not in self.jobs:+ raise KeyError(job_id)+ return {"run_id": f"run-{job_id}", "session_id": f"sess-{job_id}"}++ async def run_now(self, job_id, **kwargs):+ if job_id not in self.jobs:+ raise KeyError(job_id)+ self.run_calls.append(job_id)+++def _client_with_cron(cron: _FakeCron) -> TestClient:+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ _register_web_handlers(+ WebHandlersBindParams(channel=channel, cron_controller=cron, cron_registry=cron),+ )+ return TestClient(create_web_http_app(channel))+++def test_settings_config_models_locale_roundtrip():+ cron = _FakeCron()+ client = _client_with_cron(cron)++ r = client.get("/api/v1/config")+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "config.get"+ assert r.json()["ok"] is True+ assert "app_version" in r.json()["data"]++ r = client.get("/api/v1/models")+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "models.list"+ body = r.json()+ assert body["ok"] is True+ assert "models" in body["data"]+ assert "active_model" in body["data"]++ r = client.get("/api/v1/locale")+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "locale.get_conf"+ lang = r.json()["data"]["preferred_language"]+ assert lang in {"zh", "en"}++ flip = "en" if lang == "zh" else "zh"+ r = client.put("/api/v1/locale", json={"preferred_language": flip})+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "locale.set_conf"+ assert r.json()["data"]["preferred_language"] == flip++ r = client.get("/api/v1/locale")+ assert r.json()["data"]["preferred_language"] == flip++ # restore+ client.put("/api/v1/locale", json={"preferred_language": lang})++ r = client.put("/api/v1/locale", json={"preferred_language": "fr"})+ assert r.status_code == 400+ assert r.json()["ok"] is False+ assert r.json()["error"]["code"] == "BAD_REQUEST"+++def test_cron_job_full_path():+ cron = _FakeCron()+ client = _client_with_cron(cron)++ r = client.get("/api/v1/cron/jobs", params={"project_id": "default"})+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "cron.job.list"+ assert any(j["id"] == "job-1" for j in r.json()["data"]["jobs"])++ r = client.get("/api/v1/cron/jobs/job-1")+ assert r.status_code == 200+ assert r.json()["data"]["job"]["name"] == "n1"++ r = client.patch("/api/v1/cron/jobs/job-1", json={"patch": {"name": "renamed"}})+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "cron.job.update"+ assert r.json()["data"]["job"]["name"] == "renamed"+ assert cron.jobs["job-1"]["name"] == "renamed"++ r = client.post("/api/v1/cron/jobs/job-1/actions/toggle", json={"enabled": False})+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "cron.job.toggle"+ assert r.json()["data"]["job"]["enabled"] is False++ r = client.post("/api/v1/cron/jobs/job-1/actions/preview", json={"count": 2})+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "cron.job.preview"+ assert len(r.json()["data"]["next"]) == 2++ r = client.post("/api/v1/cron/jobs/job-1/actions/run-now", json={})+ assert r.status_code == 200+ assert r.headers["x-web-rpc-method"] == "cron.job.run_now"+ assert r.json()["data"]["accepted"] is True+ assert r.json()["data"]["run_id"] == "run-job-1"+ assert cron.run_calls == ["job-1"]++ r = client.delete("/api/v1/cron/jobs/job-1")+ assert r.status_code == 200+ assert r.json()["data"]["deleted"] is True++ r = client.get("/api/v1/cron/jobs/job-1")+ assert r.status_code == 404+ assert r.json()["error"]["code"] == "NOT_FOUND"++ r = client.post("/api/v1/cron/jobs/missing/actions/toggle", json={})+ assert r.status_code == 400+ assert r.json()["error"]["message"] == "enabled is required"