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(enterprise): 收口用户面配置能力
zhengshangyi6fdc266398d7
diff --git a/deploy/enterprise/check_handler.sh b/deploy/enterprise/check_handler.shindex edbd29a0cf..73f4e90e74 100755--- a/deploy/enterprise/check_handler.sh+++ b/deploy/enterprise/check_handler.sh@@ -17,13 +17,14 @@ check_boolean_value() {fi}-check_user_web_embedding_config() {- check_boolean_value "ENABLE_USER_WEB_EMBEDDING"+check_user_web_mode_config() {+ local mode="${DEPLOY_VARS["USER_WEB_MODE"]:-personal}"+ if [[ "${mode}" != "personal" && "${mode}" != "enterprise" ]]; then+ error "USER_WEB_MODE must be personal or enterprise, current value: ${mode}"+ ficheck_boolean_value "IS_UP_MANAGER_WEB"-- if [[ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" == "true" \- && "${DEPLOY_VARS["IS_UP_MANAGER_WEB"]}" != "true" ]]; then- error "ENABLE_USER_WEB_EMBEDDING=true requires IS_UP_MANAGER_WEB=true"+ if [[ "${mode}" == "enterprise" && "${DEPLOY_VARS["IS_UP_MANAGER_WEB"]}" != "true" ]]; then+ error "USER_WEB_MODE=enterprise requires IS_UP_MANAGER_WEB=true"fi}@@ -442,12 +443,12 @@ check_gateway_up_dependency(){}check_web_up_dependency(){- check_user_web_embedding_config- if [ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" == "true" ] \+ check_user_web_mode_config+ if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ] \&& ! module_is_selected "MANAGER"; thenif ! check_k8s_resource_exists \"deployment" "${DEPLOY_VARS["MANAGER_WEB_NAME"]}" "${DEPLOY_VARS["NAMESPACE"]}"; then- error "Embedded User Web requires the Manager Web module to be deployed"+ error "Enterprise User Web requires the Manager Web module to be deployed"fificheck_if_db_up@@ -459,12 +460,12 @@ check_web_up_dependency(){}check_manager_up_dependency(){- check_user_web_embedding_config- if [ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" == "true" ] \+ check_user_web_mode_config+ if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ] \&& ! module_is_selected "WEB"; thenif ! check_k8s_resource_exists \"deployment" "${DEPLOY_VARS["WEB_NAME"]}" "${DEPLOY_VARS["NAMESPACE"]}"; then- error "Embedded User Web requires the Web module to be deployed"+ error "Enterprise User Web requires the Web module to be deployed"fifi#check_if_rabbitmq_updiff --git a/deploy/enterprise/deploy.sh b/deploy/enterprise/deploy.shindex cfbf5b785e..2b6b75facb 100755--- a/deploy/enterprise/deploy.sh+++ b/deploy/enterprise/deploy.sh@@ -92,6 +92,20 @@ process_restart() {# ==================== Main function ====================main() {read_env_from_file "${CUSTOM_ENV_FILE}" "DEPLOY_VARS"++ # USER_WEB_MODE 是用户面产品形态的唯一开关;旧布尔变量仅作兼容输入。+ if [[ -z "${DEPLOY_VARS["USER_WEB_MODE"]:-}" ]]; then+ if [[ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]:-false}" == "true" ]]; then+ DEPLOY_VARS["USER_WEB_MODE"]="enterprise"+ warn "ENABLE_USER_WEB_EMBEDDING is deprecated; use USER_WEB_MODE=enterprise"+ else+ DEPLOY_VARS["USER_WEB_MODE"]="personal"+ fi+ fi+ DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]=$(+ [[ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]] && printf true || printf false+ )+parse_args "$@"detect_oscheck_dependencydiff --git a/deploy/enterprise/gateway_handler.sh b/deploy/enterprise/gateway_handler.shindex 951ae764fc..f5c5a1fc21 100755--- a/deploy/enterprise/gateway_handler.sh+++ b/deploy/enterprise/gateway_handler.sh@@ -149,8 +149,9 @@ deploy_gateway() {local is_external_pvc="${DEPLOY_VARS["ENABLE_EXTERNAL_PVC"]}"ensure_secret_configmap- exec_cmd kubectl create configmap -n ${namespace} ${envfile_name} --from-file=.env=${env_file}- exec_cmd kubectl create configmap -n ${namespace} ${conf_name} --from-file=config.yaml=${conf_file}+ # 使用 apply 保证重复部署幂等:ConfigMap 已存在时更新内容,不因 create 冲突失败。+ exec_cmd kubectl apply -f ${CONFIG_DIR}/gateway-envfile.configmap.yaml+ exec_cmd kubectl apply -f ${CONFIG_DIR}/gateway-config.configmap.yamlif [[ "${mount_type}" == "pvc" && "${is_external_pvc}" == "false" ]]; thenexec_cmd kubectl apply -f ${pvc_file}diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.shindex 57da000ff9..e6c3ba5a3f 100755--- a/deploy/enterprise/global_vars.sh+++ b/deploy/enterprise/global_vars.sh@@ -111,13 +111,17 @@ declare -A DEPLOY_VARS=(["DEPLOYMENT_MODE"]="standalone"["WEB_PORT"]="19000"["GATEWAY_PORT"]="19001"- ["GATEWAY_CONFIG_HTTP_PORT"]="8775"+ ["GATEWAY_HTTP_PORT"]="19001"+ ["GATEWAY_WS_PORT"]="19000"["GATEWAY_WEB_HTTP_PORT"]="19002"+ # Manager → Gateway 配置同步 HTTP(manager_config_receiver)+ ["GATEWAY_CONFIG_HTTP_PORT"]="8775"["ENABLE_EXTERNAL_OBS"]="false"["ENABLE_EXTERNAL_NFS"]="false"["ENABLE_EXTERNAL_PVC"]="false"["ENABLE_EXTERNAL_RABBITMQ"]="false"["ENABLE_EXTERNAL_REDIS"]="false"+ ["USER_WEB_MODE"]=""["ENABLE_USER_WEB_EMBEDDING"]="false"["FLUENT_BIT_NAME"]="fluent-bit"["FLUENT_BIT_IMAGE"]="fluent/fluent-bit:3.0.0"@@ -220,6 +224,7 @@ declare -A DEPLOY_VARS=(["AGENT_RUNTIME_IMAGE"]=""["AGENT_RUNTIME_REPLICAS"]="1"["AGENT_RUNTIME_PORT"]="8091"+ ["AGENT_RUNTIME_SYNC_TIMEOUT"]="10"["AGENT_RUNTIME_DB_NAME"]="runtime"["AGENT_RUNTIME_REDIS_DB"]="2"["AGENT_RUNTIME_REQUEST_TIMEOUT"]="300"diff --git a/deploy/enterprise/manager_handler.sh b/deploy/enterprise/manager_handler.shindex 7dded64a2d..647da55478 100755--- a/deploy/enterprise/manager_handler.sh+++ b/deploy/enterprise/manager_handler.sh@@ -86,12 +86,18 @@ deploy_manager() {exec_cmd kubectl apply -f ${manager_web_file}wait_k8s_resource_ready "deployment" "${manager_web_name}" "${namespace}"success "MANAGER_WEB_NODE_PORT: ${DEPLOY_VARS["MANAGER_WEB_NODE_PORT"]}"- fi- if [ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" == "true" ]; then- delete_k8s_resource \- "service" "${DEPLOY_VARS["WEB_NAME"]}-nodeport" "${namespace}"+ # WEB 先于 MANAGER 渲染时无法知道 Manager Web 的 NodePort。+ # Manager 就绪后重新渲染并应用 User Web,端口由 kubectl 实时读取。+ if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ] \+ && module_is_selected "WEB"; then+ # WEB 已经在前面分配过 NodePort;这里只重新渲染登录跳转地址,+ # 不能再次调用 ensure_available_port,否则会把自身端口判定为冲突。+ gen_web_file+ deploy_web+ fifi+}uninstall_manager() {diff --git a/deploy/enterprise/templates/gateway.template.env b/deploy/enterprise/templates/gateway.template.envindex e4d5ba4993..17454bc89c 100644--- a/deploy/enterprise/templates/gateway.template.env+++ b/deploy/enterprise/templates/gateway.template.env@@ -96,8 +96,10 @@ GATEWAY_CLAW_WS_PING_TIMEOUT=<<GATEWAY_CLAW_WS_PING_TIMEOUT>># Websocket ConfigurationWEB_HOST=0.0.0.0WEB_PORT=<<WEB_PORT>>+GATEWAY_WS_PORT=<<GATEWAY_WS_PORT>>GATEWAY_HOST=0.0.0.0-GATEWAY_PORT=<<GATEWAY_PORT>>+GATEWAY_PORT=<<GATEWAY_HTTP_PORT>>+GATEWAY_WEB_HTTP_PORT=<<GATEWAY_WEB_HTTP_PORT>># Enterprise Web: browser WS on app_enterprise_web; Gateway WS client to /gatewayENTERPRISE_WEB_ENABLED=true@@ -122,7 +124,6 @@ RUNTIME_DB_POOL_TIMEOUT=<<GATEWAY_DB_POOL_TIMEOUT>>GATEWAY_CONFIG_RECEIVER_ENABLED=trueGATEWAY_CONFIG_HTTP_HOST=0.0.0.0GATEWAY_CONFIG_HTTP_PORT=<<GATEWAY_CONFIG_HTTP_PORT>>-GATEWAY_WEB_HTTP_PORT=<<GATEWAY_WEB_HTTP_PORT>>GATEWAY_CONFIG_PUBLIC_HOST=<<GATEWAY_NAME>>GATEWAY_MANAGER_HTTP_URL=http://<<MANAGER_SERVER_NAME>>:<<MANAGER_REST_PORT>>GATEWAY_CONFIG_HEARTBEAT_SECONDS=60diff --git a/deploy/enterprise/templates/gateway.template.yaml b/deploy/enterprise/templates/gateway.template.yamlindex 5d39d2fbee..2b9b870e45 100644--- a/deploy/enterprise/templates/gateway.template.yaml+++ b/deploy/enterprise/templates/gateway.template.yaml@@ -78,6 +78,8 @@ spec:containerPort: <<WEB_PORT>>- name: acp-wscontainerPort: <<GATEWAY_PORT>>+ - name: http+ containerPort: <<GATEWAY_HTTP_PORT>>- name: web-httpcontainerPort: <<GATEWAY_WEB_HTTP_PORT>>- name: config-http@@ -103,6 +105,8 @@ spec:- secretRef:name: <<SECRET_CM_NAME>>env:+ - name: USER_WEB_MODE+ value: "<<USER_WEB_MODE>>"# downward API:注入当前 Pod 身份,供 RuntimeManagementAgentClient# 构建 agentserver pod 的 ownerReference(指向本 Pod),实现级联清理。- name: POD_NAME@@ -158,6 +162,9 @@ spec:- name: acp-wsport: <<GATEWAY_PORT>>targetPort: <<GATEWAY_PORT>>+ - name: http+ port: <<GATEWAY_HTTP_PORT>>+ targetPort: <<GATEWAY_HTTP_PORT>>- name: web-httpport: <<GATEWAY_WEB_HTTP_PORT>>targetPort: <<GATEWAY_WEB_HTTP_PORT>>diff --git a/deploy/enterprise/templates/manager-server.template.yaml b/deploy/enterprise/templates/manager-server.template.yamlindex 3c2d8cb944..4f5efd289b 100644--- a/deploy/enterprise/templates/manager-server.template.yaml+++ b/deploy/enterprise/templates/manager-server.template.yaml@@ -81,6 +81,10 @@ spec:value: "<<MANAGER_DB_NAME>>"- name: IDENTITY_PUBLIC_KEY_URLvalue: "http://<<IDENTITY_NAME>>:<<IDENTITY_REST_PORT>>/v1/auth/public_key"+ - name: AGENT_RUNTIME_ENDPOINT+ value: "http://<<AGENT_RUNTIME_NAME>>:<<AGENT_RUNTIME_PORT>>"+ - name: AGENT_RUNTIME_SYNC_TIMEOUT+ value: "<<AGENT_RUNTIME_SYNC_TIMEOUT>>"- name: MANAGER_WS_ENABLEDvalue: "true"- name: MANAGER_WS_HOSTdiff --git a/deploy/enterprise/templates/manager-web.template.yaml b/deploy/enterprise/templates/manager-web.template.yamlindex 639c319dd3..362c79af64 100644--- a/deploy/enterprise/templates/manager-web.template.yaml+++ b/deploy/enterprise/templates/manager-web.template.yaml@@ -28,14 +28,19 @@ spec:value: "0.0.0.0"- name: MANAGER_WEB_PORTvalue: "<<MANAGER_WEB_PORT>>"+ # 浏览器只能访问 Manager Web 同源路径,不能暴露 Kubernetes 内部 DNS。+ - name: VITE_API_BASE+ value: "/api"+ - name: VITE_IDP_BASE+ value: "/idp"- name: MANAGER_WEB_PROXY_TARGETvalue: "http://<<MANAGER_SERVER_NAME>>:<<MANAGER_REST_PORT>>"- name: MANAGER_WEB_IDP_TARGETvalue: "http://<<IDENTITY_NAME>>:<<IDENTITY_REST_PORT>>"- name: MANAGER_WEB_GATEWAY_SSE- value: "http://<<GATEWAY_NAME>>:<<GATEWAY_PORT>>/web/invoke"+ value: "http://<<GATEWAY_NAME>>:<<GATEWAY_WEB_HTTP_PORT>>/web/invoke"- name: MANAGER_WEB_USER_SERVER_TARGET- value: "http://<<WEB_NAME>>:<<WEB_WS_PORT>>"+ value: "http://<<WEB_NAME>>:<<WEB_HTTP_PORT>>"- name: TZvalue: "<<TIMEZONE>>"diff --git a/deploy/enterprise/templates/web.template.yaml b/deploy/enterprise/templates/web.template.yamlindex b9e24cf7c0..31bf7087b7 100644--- a/deploy/enterprise/templates/web.template.yaml+++ b/deploy/enterprise/templates/web.template.yaml@@ -34,6 +34,16 @@ spec:value: "0.0.0.0"- name: FRONTEND_HOSTvalue: "0.0.0.0"+ - name: USER_WEB_MODE+ value: "<<USER_WEB_MODE>>"+ - name: VITE_USER_WEB_MODE+ value: "<<USER_WEB_MODE>>"+ - name: VITE_ENABLE_USER_WEB_EMBEDDING+ value: "<<ENABLE_USER_WEB_EMBEDDING>>"+ - name: USER_WEB_IDP_TARGET+ value: "http://<<IDENTITY_NAME>>:<<IDENTITY_REST_PORT>>"+ - name: USER_WEB_MANAGER_TARGET+ value: "http://<<MANAGER_SERVER_NAME>>:<<MANAGER_REST_PORT>>"- name: FRONTEND_PORTvalue: "<<WEB_HTTP_PORT>>"- name: ENTERPRISE_WEB_WS_HOSTdiff --git a/deploy/enterprise/tests/test_identity_user_web_deploy.sh b/deploy/enterprise/tests/test_identity_user_web_deploy.shnew file mode 100755index 0000000000..4eca6a9ed5--- /dev/null+++ b/deploy/enterprise/tests/test_identity_user_web_deploy.sh@@ -0,0 +1,127 @@+#!/usr/bin/env bash+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"++source "${SCRIPT_DIR}/common.sh"+source "${SCRIPT_DIR}/global_vars.sh"+source "${SCRIPT_DIR}/cmd_handler.sh"+source "${SCRIPT_DIR}/envfile_handler.sh"+source "${SCRIPT_DIR}/template_handler.sh"+source "${SCRIPT_DIR}/check_handler.sh"+source "${SCRIPT_DIR}/web_handler.sh"+source "${SCRIPT_DIR}/manager_handler.sh"++TEST_DIR=""++cleanup() {+ if [ -n "${TEST_DIR}" ] && [ -d "${TEST_DIR}" ]; then+ rm -rf -- "${TEST_DIR}"+ fi+}++assert_equal() {+ local expected="$1"+ local actual="$2"+ local message="$3"+ if [ "${actual}" != "${expected}" ]; then+ echo "FAIL: ${message}: expected=${expected}, actual=${actual}" >&2+ exit 1+ fi+}++main() {+ check_cmd "yq"++ TEST_DIR="$(mktemp -d)"+ local test_dir="${TEST_DIR}"+ trap cleanup EXIT++ DEPLOY_VARS["OS_TYPE"]="linux"+ DEPLOY_VARS["MODE"]="product"+ DEPLOY_VARS["WEB_NODE_PORT"]="31001"+ DEPLOY_VARS["MANAGER_SERVER_NODE_PORT"]="31002"+ DEPLOY_VARS["MANAGER_WEB_NODE_PORT"]="31003"++ assert_equal \+ "false" \+ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" \+ "User Web embedding must be disabled by default"+ printf '%s\n' 'ENABLE_USER_WEB_EMBEDDING=true' > "${test_dir}/.env.custom"+ read_env_from_file "${test_dir}/.env.custom" "DEPLOY_VARS"+ assert_equal \+ "true" \+ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" \+ ".env.custom compatibility value must be read"++ CONFIG["WEB_FILE"]="${test_dir}/web.yaml"++ DEPLOY_VARS["USER_WEB_MODE"]="personal"+ DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]="false"+ gen_web_file+ assert_equal \+ "NodePort" \+ "$(yq eval-all 'select(.metadata.name == "jiuwenclaw-web-nodeport") | .spec.type' "${CONFIG["WEB_FILE"]}")" \+ "standalone mode must expose the User Web NodePort"+ assert_equal \+ "0.0.0.0" \+ "$(yq eval-all 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "FRONTEND_HOST").value' "${CONFIG["WEB_FILE"]}")" \+ "User Web frontend must listen on all interfaces"++ DEPLOY_VARS["USER_WEB_MODE"]="enterprise"+ DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]="true"+ gen_web_file+ assert_equal \+ "1" \+ "$(yq eval-all '[select(.metadata.name == "jiuwenclaw-web-nodeport")] | length' "${CONFIG["WEB_FILE"]}")" \+ "enterprise mode must retain the configured User Web NodePort"++ DEPLOY_VARS["IS_UP_MANAGER_WEB"]="false"+ if (check_user_web_mode_config) >/dev/null 2>&1; then+ echo "FAIL: embedded mode must require Manager Web" >&2+ exit 1+ fi++ DEPLOY_VARS["IS_UP_MANAGER_WEB"]="true"+ check_user_web_mode_config++ DEPLOY_VARS["USER_WEB_MODE"]="invalid"+ if (check_user_web_mode_config) >/dev/null 2>&1; then+ echo "FAIL: invalid boolean value must be rejected" >&2+ exit 1+ fi++ CONFIG["MANAGER_SERVER_FILE"]="${test_dir}/manager-server.yaml"+ render_config_template \+ "${CONFIG["MANAGER_SERVER_TEMPLATE_FILE"]}" \+ "${CONFIG["MANAGER_SERVER_FILE"]}" \+ "DEPLOY_VARS"+ assert_equal \+ "http://jiuwenclaw-identity:8770/v1/auth/public_key" \+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_PUBLIC_KEY_URL").value' "${CONFIG["MANAGER_SERVER_FILE"]}")" \+ "Manager Server must receive the Identity public-key URL"++ CONFIG["MANAGER_WEB_FILE"]="${test_dir}/manager-web.yaml"+ render_config_template \+ "${CONFIG["MANAGER_WEB_TEMPLATE_FILE"]}" \+ "${CONFIG["MANAGER_WEB_FILE"]}" \+ "DEPLOY_VARS"+ assert_equal \+ "0" \+ "$(yq eval-all '[select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_PUBLIC_KEY_URL")] | length' "${CONFIG["MANAGER_WEB_FILE"]}")" \+ "Manager Web must not receive the unused public-key URL"++ ensure_secret_configmap() { :; }+ exec_cmd() { :; }+ wait_k8s_resource_ready() { :; }+ success() { :; }++ DEPLOY_VARS["USER_WEB_MODE"]="enterprise"+ deploy_web+ DEPLOY_VARS["IS_UP_MANAGER_WEB"]="true"+ deploy_manager++ echo "PASS: identity and User Web deployment checks"+}++main "$@"diff --git a/deploy/enterprise/web_handler.sh b/deploy/enterprise/web_handler.shindex 07e505ae00..a7f1fb19ef 100755--- a/deploy/enterprise/web_handler.sh+++ b/deploy/enterprise/web_handler.sh@@ -7,12 +7,9 @@ gen_web_file() {local enable_external_obs="${DEPLOY_VARS["ENABLE_EXTERNAL_OBS"]}"local obs_url="${DEPLOY_VARS["MINIO_NAME"]}-headless.default:9000"+ # 用户面自己展示认证页,不跳转到 Manager Web;端口和内部服务地址由模板注入。render_config_template "${template_file}" "${file}" "DEPLOY_VARS"- if [ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" == "true" ]; then- local nodeport_name="${DEPLOY_VARS["WEB_NAME"]}-nodeport"- yq eval 'select(.metadata.name != "'"${nodeport_name}"'")' -i "${file}"- fiif [ "${DEPLOY_VARS["ENABLE_EXTERNAL_OBS"]}" == "true" ]; thenobs_url="${DEPLOY_VARS["OBS_URL"]}"@@ -48,14 +45,16 @@ gen_web_file() {add_resource_if_set "WEB" "${file}"+ # yq 追加资源配置时可能重复 env;Deployment strategic merge patch 不接受重复键,+ # 这里按名称去重,保留最后一次生成的值。+ yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env |= unique_by(.name)' -i "${file}"+enable_dev_mode_if_needed ${file} web}render_web_files() {render_secret_configmap- if [ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" != "true" ]; then- ensure_available_port "WEB_NODE_PORT"- fi+ ensure_available_port "WEB_NODE_PORT"gen_web_file}@@ -67,9 +66,8 @@ deploy_web() {ensure_secret_configmapexec_cmd kubectl apply -f ${file}wait_k8s_resource_ready "deployment" "${name}" "${namespace}"- if [ "${DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]}" == "true" ]; then- delete_k8s_resource "service" "${name}-nodeport" "${namespace}"- success "User Web is available through Manager Web; standalone NodePort is disabled"+ if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]; then+ success "USER_WEB_LOGIN_ENTRY_NODE_PORT: ${DEPLOY_VARS["WEB_NODE_PORT"]}"elsesuccess "WEB_NODE_PORT: ${DEPLOY_VARS["WEB_NODE_PORT"]}"fidiff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.pyindex 2d0617aa38..25f7036389 100644--- a/jiuwenswarm/channels/web/app_web.py+++ b/jiuwenswarm/channels/web/app_web.py@@ -84,7 +84,11 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):api_target = ""ws_target = ""web_http_target = ""+ idp_target = ""+ manager_api_target = ""ws_disable_compress = False+ embedding_enabled = False+ user_web_mode = "personal"logger = logging.getLogger(__name__)_HOP_BY_HOP_HEADERS = {@@ -532,6 +536,12 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):passdef _dispatch_proxy(self) -> bool:+ # 用户面认证和目录请求仍走同源地址,由本服务转发到集群内的 Identity/Manager。+ path = urlparse(self.path).path+ if path == "/idp" or path.startswith("/idp/"):+ return self._proxy_named_http(self.idp_target, "/idp")+ if path == "/manager-api" or path.startswith("/manager-api/"):+ return self._proxy_named_http(self.manager_api_target, "/manager-api", "/api")# /api/sessions* is handled by _is_web_http_route (Gateway Web HTTP), not WebChannel.if self._is_web_http_route():self._proxy_web_http()@@ -559,6 +569,30 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):return Truereturn False+ def _proxy_named_http(self, target: str, prefix: str, replacement: str = "") -> bool:+ if not target:+ self.send_error(502, "proxy target not configured")+ return True+ original_path = self.path+ parsed = urlparse(original_path)+ path = parsed.path+ if path == prefix:+ path = replacement or "/"+ elif replacement:+ path = replacement + path[len(prefix):]+ else:+ path = path[len(prefix):] or "/"+ if parsed.query:+ path += "?" + parsed.query+ self.path = path+ self.__dict__["api_target"] = target+ try:+ self._proxy_http()+ finally:+ self.path = original_path+ self.__dict__.pop("api_target", None)+ return True+def _proxy_web_http(self) -> None:if not self.web_http_target:self.send_error(502, "web http proxy target not configured")@@ -575,6 +609,17 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):returnif self._dispatch_proxy():return+ if self._is_document_request():+ index = Path(self.directory or os.getcwd()) / "index.html"+ body = index.read_text(encoding="utf-8").replace(+ "__JIUWEN_USER_WEB_EMBEDDING__", "true" if self.user_web_mode == "enterprise" else "false"+ ).replace("__JIUWEN_USER_WEB_MODE__", self.user_web_mode).encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ returnsuper().do_GET()def do_POST(self) -> None: # noqa: N802@@ -622,6 +667,10 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):def log_error(self, format: str, *args) -> None: # noqa: A002self.logger.error("%s - %s", self.address_string(), format % args)+ def _is_document_request(self) -> bool:+ path = urlparse(self.path).path+ return path in ("/", "/index.html") and "text/html" in self.headers.get("Accept", "")+def send_head(self):parsed = urlparse(self.path)req_path = unquote(parsed.path)@@ -792,6 +841,14 @@ def main() -> None:_ConfiguredHandler.api_target = api_target_ConfiguredHandler.ws_target = ws_target+ _ConfiguredHandler.idp_target = os.getenv("USER_WEB_IDP_TARGET", "").strip()+ _ConfiguredHandler.manager_api_target = os.getenv("USER_WEB_MANAGER_TARGET", "").strip()+ configured_mode = os.getenv("USER_WEB_MODE", "").strip().lower()+ if configured_mode not in {"personal", "enterprise"}:+ legacy_embedding = os.getenv("ENABLE_USER_WEB_EMBEDDING", "")+ configured_mode = "enterprise" if legacy_embedding.strip().lower() == "true" else "personal"+ _ConfiguredHandler.user_web_mode = configured_mode+ _ConfiguredHandler.embedding_enabled = configured_mode == "enterprise"_ConfiguredHandler.web_http_target = web_http_target_ConfiguredHandler.ws_disable_compress = args.ws_disable_compress_ConfiguredHandler.logger = loggerdiff --git a/jiuwenswarm/channels/web/frontend/index.html b/jiuwenswarm/channels/web/frontend/index.htmlindex 920e7d5e93..6c3ce02e4f 100644--- a/jiuwenswarm/channels/web/frontend/index.html+++ b/jiuwenswarm/channels/web/frontend/index.html@@ -10,6 +10,8 @@<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /></head><body>+ <script>window.__JIUWEN_USER_WEB_MODE__ = "__JIUWEN_USER_WEB_MODE__";+ window.__JIUWEN_USER_WEB_EMBEDDING__ = "__JIUWEN_USER_WEB_EMBEDDING__" === "true";</script><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 28c802ebd9..43208f0b0e 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -26,6 +26,7 @@ import {import type { CodeReviewTarget } from './features/code-mode/types';import { FEATURE_APP_UPDATER_UI } from './featureFlags';+import { ENTERPRISE_HIDDEN_NAV_ITEMS, isEnterpriseMode } from './edition';import {beginHistoryRestore,fetchHistoryPage,@@ -269,6 +270,8 @@ function AppContent() {return 'new';});+ const enterpriseMode = isEnterpriseMode();+ const enterpriseBlockedNav = new Set<MainNavKey>(ENTERPRISE_HIDDEN_NAV_ITEMS);const [activeNav, setActiveNav] = useState<MainNavKey>('chat');const [serverConfig, setServerConfig] = useState<Record<string, unknown> | null>(null);const [configError, setConfigError] = useState<string | null>(null);@@ -329,11 +332,11 @@ function AppContent() {useEffect(() => {const handler = (e: Event) => {const nav = (e as CustomEvent<MainNavKey>).detail;- if (nav) setActiveNav(nav);+ if (nav && !(enterpriseMode && enterpriseBlockedNav.has(nav))) setActiveNav(nav);};window.addEventListener('jiuwen:nav', handler);return () => window.removeEventListener('jiuwen:nav', handler);- }, []);+ }, [enterpriseMode]);const restartAutoCloseTimerRef = useRef<number | null>(null);const saveToastTimerRef = useRef<number | null>(null);@@ -2071,13 +2074,14 @@ function AppContent() {}, [deleteTarget, enterNewConversation, request, t]);const handleNavigate = useCallback((nav: MainNavKey) => {+ if (enterpriseMode && enterpriseBlockedNav.has(nav)) return;setActiveNav(nav);if (modelSetupGuideStep === 1 && nav === 'configpanel') {setModelSetupGuideStep(2);}if (nav === 'skills') setHasVisitedSkills(true);if (nav === 'channels') setHasVisitedChannels(true);- }, [modelSetupGuideStep]);+ }, [enterpriseMode, modelSetupGuideStep]);const skipModelSetupGuide = useCallback(() => {setModelSetupGuideStep(null);@@ -2207,7 +2211,7 @@ function AppContent() {isConnected={isConnected}onNewSession={handleNewSession}showNewSession={false}- hiddenNavItems={['sessions']}+ hiddenNavItems={enterpriseMode ? ['sessions', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions']}onMorePanelOpenChange={setSidebarMorePanelOpen}onSetupGuideRequest={openModelSetupGuide}/>diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsxnew file mode 100644index 0000000000..aa385ff239--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx@@ -0,0 +1,104 @@+import { FormEvent, ReactNode, useEffect, useState } from 'react';+import { setRuntimeScope } from './services/runtimeScope';+import { isEnterpriseMode } from './edition';++const ACCESS_KEY = 'openjiuwen_access_token';+const REFRESH_KEY = 'openjiuwen_refresh_token';++type User = { user_id: string; display_name: string };+type Org = { group_id: string; name: string };+type Gateway = { jiuwenclaw_id: string; jiuwenclaw_name: string; gateway_endpoint: string | null };+type Agent = { template_id: string; template_name: string; resource_id?: string };+type TokenResponse = { access_token: string; refresh_token: string };++async function request<T>(url: string, init: RequestInit = {}, unwrap = false): Promise<T> {+ const token = localStorage.getItem(ACCESS_KEY);+ const headers = new Headers(init.headers);+ if (token) headers.set('Authorization', `Bearer ${token}`);+ if (init.body && !(init.body instanceof URLSearchParams)) headers.set('Content-Type', 'application/json');+ const response = await fetch(url, { ...init, headers });+ const json = await response.json().catch(() => ({}));+ if (!response.ok) throw new Error(String(json.detail || json.message || response.statusText));+ return (unwrap && json && typeof json === 'object' && 'data' in json ? json.data : json) as T;+}++function runtimeScopeReady(): boolean {+ const query = new URLSearchParams(window.location.search);+ return Boolean(query.get('user_id') && query.get('group_id') && query.get('bot_id') && query.get('gateway_id'));+}++export function EnterpriseEntry({ children }: { children: ReactNode }) {+ const enabled = isEnterpriseMode();+ const [ready, setReady] = useState(!enabled || runtimeScopeReady());+ const [user, setUser] = useState<User | null>(null);+ const [username, setUsername] = useState('');+ const [password, setPassword] = useState('');+ const [error, setError] = useState('');+ const [orgs, setOrgs] = useState<Org[]>([]);+ const [gateways, setGateways] = useState<Gateway[]>([]);+ const [org, setOrg] = useState<Org | null>(null);+ const [gateway, setGateway] = useState<Gateway | null>(null);+ const [agents, setAgents] = useState<Agent[]>([]);++ useEffect(() => {+ if (!enabled || ready || !localStorage.getItem(ACCESS_KEY)) return;+ void Promise.all([+ request<User>('/idp/v1/auth/me'),+ request<{ orgs: Org[] }>('/idp/v1/auth/me/orgs'),+ request<{ gateways: Gateway[] }>('/manager-api/v1/user-console/gateways', {}, true),+ ]).then(([me, orgResult, gatewayResult]) => {+ setUser(me); setOrgs(orgResult.orgs); setGateways(gatewayResult.gateways);+ }).catch(() => { localStorage.removeItem(ACCESS_KEY); localStorage.removeItem(REFRESH_KEY); });+ }, [enabled, ready]);++ useEffect(() => {+ if (!org || !gateway) { setAgents([]); return; }+ void request<{ agents: Agent[] }>(+ `/manager-api/v1/user-console/agents?group_id=${encodeURIComponent(org.group_id)}&jiuwenclaw_id=${encodeURIComponent(gateway.jiuwenclaw_id)}`,+ {}, true,+ ).then((result) => setAgents(result.agents)).catch((e) => setError(e.message));+ }, [org, gateway]);++ if (ready) return <>{children}</>;++ async function login(event: FormEvent) {+ event.preventDefault(); setError('');+ try {+ const body = new URLSearchParams({ username: username.trim(), password });+ const token = await request<TokenResponse>('/idp/v1/auth/token', { method: 'POST', body });+ localStorage.setItem(ACCESS_KEY, token.access_token);+ localStorage.setItem(REFRESH_KEY, token.refresh_token);+ const [me, orgResult, gatewayResult] = await Promise.all([+ request<User>('/idp/v1/auth/me'),+ request<{ orgs: Org[] }>('/idp/v1/auth/me/orgs'),+ request<{ gateways: Gateway[] }>('/manager-api/v1/user-console/gateways', {}, true),+ ]);+ setUser(me); setOrgs(orgResult.orgs); setGateways(gatewayResult.gateways);+ } catch (e) { setError(e instanceof Error ? e.message : '登录失败'); }+ }++ function enter(agent: Agent) {+ if (!user || !org || !gateway) return;+ const botId = agent.resource_id || agent.template_id;+ setRuntimeScope({+ userId: user.user_id,+ groupId: org.group_id,+ botId,+ gatewayId: gateway.jiuwenclaw_id,+ });+ const query = new URLSearchParams({+ user_id: user.user_id,+ group_id: org.group_id,+ bot_id: botId,+ gateway_id: gateway.jiuwenclaw_id,+ });+ window.history.replaceState({}, '', `${window.location.pathname}?${query}`);+ setReady(true);+ }++ const shell = (content: ReactNode) => <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: '#f5f7fb', padding: 24 }}><div style={{ width: 420, background: '#fff', padding: 28, borderRadius: 12, boxShadow: '0 8px 30px #0001' }}>{content}{error && <div style={{ color: '#dc2626', marginTop: 12 }}>{error}</div>}</div></div>;+ if (!user) return shell(<form onSubmit={login}><h2>用户登录</h2><p>使用管理面统一身份中心账号登录</p><input style={{ width: '100%', padding: 10, marginTop: 12 }} placeholder="用户名" value={username} onChange={e => setUsername(e.target.value)} /><input style={{ width: '100%', padding: 10, marginTop: 12 }} type="password" placeholder="密码" value={password} onChange={e => setPassword(e.target.value)} /><button style={{ width: '100%', padding: 10, marginTop: 16 }} disabled={!username || !password}>登录</button></form>);+ if (!gateway) return shell(<><h2>选择组网</h2>{gateways.map(g => <button key={g.jiuwenclaw_id} style={{ width: '100%', padding: 10, marginTop: 8 }} onClick={() => setGateway(g)}>{g.jiuwenclaw_name}</button>)}</>);+ if (!org) return shell(<><h2>选择组织</h2>{orgs.map(o => <button key={o.group_id} style={{ width: '100%', padding: 10, marginTop: 8 }} onClick={() => setOrg(o)}>{o.name}</button>)}</>);+ return shell(<><h2>选择 Bot</h2>{agents.map(a => <button key={a.resource_id || a.template_id} style={{ width: '100%', padding: 10, marginTop: 8 }} onClick={() => enter(a)}>{a.template_name}</button>)}{agents.length === 0 && <p>暂无可用 Bot</p>}</>);+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsxindex 3329399b23..a028d2351b 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx@@ -18,6 +18,7 @@ import { getSkillAvatar } from "../../utils/skillAvatar";import { SkillGraphPanel, type SkillGraphPanelHandle } from "../SkillGraphPanel";import { MarkdownRenderer } from "../MarkdownRenderer";import { Switch } from "../Switch";+import { isEnterpriseMode } from "../../edition";/** 刷新会 git pull marketplace,略放宽;普通进页单次 RPC 一般很快。 */const SKILLS_FETCH_TIMEOUT_REFRESH_MS = 60_000;@@ -586,6 +587,7 @@ function SkillIndexTreeView({export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }: SkillPanelProps) {const { t, i18n } = useTranslation();+ const readOnly = isEnterpriseMode();const [activeTab, setActiveTab] = useState<"my" | "marketplace" | "index" | "graph">("my");const [mySkillsSubTab, setMySkillsSubTab] = useState<"all" | "enabled" | "disabled">("all");const [marketplaceSubTab, setMarketplaceSubTab] = useState<"builtin" | "swarmskills" | "online">("builtin");@@ -1578,7 +1580,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:</p></div><div className="flex items-center">- <button+ {!readOnly && <buttononClick={() => setSourceModalOpen(true)}className="flex items-center gap-1.5 px-1 py-1.5 rounded-lg text-sm text-text-muted hover:text-text hover:bg-secondary/50 ">@@ -1586,7 +1588,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" /></svg>{t('skills.actions.sourceManager')}- </button>+ </button>}<buttononClick={() => {if (activeTab === "index") {@@ -1616,7 +1618,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:</svg>{activeTab === "graph" && graphReading ? "正在读取技能总谱" : t('common.refresh')}</button>- <button+ {!readOnly && <buttononClick={handleImportLocal}className={`flex items-center gap-1.5 px-1 py-1.5 rounded-lg text-sm ${actionTarget === "import_local"@@ -1630,7 +1632,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:<path strokeLinecap="round" strokeLinejoin="round" d="M5 15v4a2 2 0 002 2h10a2 2 0 002-2v-4" /></svg>{t('skills.actions.importLocal')}- </button>+ </button>}</div></div>@@ -1709,7 +1711,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:) : null}</div>- {activeTab === "index" ? (+ {!readOnly && activeTab === "index" ? (<div className="mt-4 flex flex-col flex-1 min-h-0 gap-4 overflow-y-auto pr-2"><div className="rounded-lg border border-border bg-panel p-4"><div className="flex flex-wrap items-center justify-between gap-3">@@ -1933,13 +1935,13 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:</div>) : null}- {activeTab === "graph" ? (+ {!readOnly && activeTab === "graph" ? (<div className="mt-4 flex-1 min-h-0"><SkillGraphPanel ref={skillGraphPanelRef} onReadingChange={updateGraphReading} /></div>) : null}- {activeTab === "marketplace" ? (+ {!readOnly && activeTab === "marketplace" ? (<><div className="mt-4 flex items-center justify-between gap-4"><div className="flex items-center gap-2">@@ -2061,7 +2063,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:<Switchchecked={!isDisabled}onChange={() => toggleSkillDisabled(skill.name, skill.origin)}- disabled={isToggling}+ disabled={readOnly || isToggling}/>)}</div>@@ -2088,10 +2090,10 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:</div><div className="flex items-center mt-auto pt-2 gap-2 flex-shrink-0" style={{ width: "100%" }}><div className="flex gap-1.5 flex-1">- {renderEvolutionButton(skill)}+ {!readOnly && renderEvolutionButton(skill)}</div><div className="flex-shrink-0 ml-auto">- {renderActionButton(skill)}+ {!readOnly && renderActionButton(skill)}</div></div></>@@ -2334,12 +2336,12 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:</div></div><div className="flex flex-col items-end gap-2 flex-shrink-0">- {renderEvolutionButton(skill)}+ {!readOnly && renderEvolutionButton(skill)}<div className="flex items-center gap-2"><Switchchecked={!isDisabled}onChange={() => toggleSkillDisabled(skill.name, skill.origin)}- disabled={isToggling}+ disabled={readOnly || isToggling}/></div></div>@@ -2369,13 +2371,13 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:</div><div className="flex items-center mt-auto pt-2 gap-2 flex-shrink-0" style={{ width: "100%" }}><div className="flex gap-1.5 flex-1">- {renderEvolutionButton(skill)}+ {!readOnly && renderEvolutionButton(skill)}</div><div className="flex items-center gap-2"><Switchchecked={!isDisabled}onChange={() => toggleSkillDisabled(skill.name, skill.origin)}- disabled={isToggling}+ disabled={readOnly || isToggling}/></div></div>diff --git a/jiuwenswarm/channels/web/frontend/src/edition.ts b/jiuwenswarm/channels/web/frontend/src/edition.tsnew file mode 100644index 0000000000..1ee95be889--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/edition.ts@@ -0,0 +1,10 @@+export type UserWebMode = "personal" | "enterprise";+export const getUserWebMode = (): UserWebMode => {+ const injected = String(window.__JIUWEN_USER_WEB_MODE__ || "").toLowerCase();+ if (injected === "enterprise" || injected === "personal") return injected;+ const configured = String(import.meta.env.VITE_USER_WEB_MODE || "").toLowerCase();+ if (configured === "enterprise" || configured === "personal") return configured;+ return String(import.meta.env.VITE_ENABLE_USER_WEB_EMBEDDING).toLowerCase() === "true" ? "enterprise" : "personal";+};+export const isEnterpriseMode = (): boolean => getUserWebMode() === "enterprise";+export const ENTERPRISE_HIDDEN_NAV_ITEMS = ["channels", "agents", "teams", "extensions", "configpanel", "browserpanel", "updatepanel"] as const;diff --git a/jiuwenswarm/channels/web/frontend/src/main.tsx b/jiuwenswarm/channels/web/frontend/src/main.tsxindex cf4003b9f7..5485de03cc 100644--- a/jiuwenswarm/channels/web/frontend/src/main.tsx+++ b/jiuwenswarm/channels/web/frontend/src/main.tsx@@ -4,6 +4,7 @@ import { A2UIProvider } from '@a2ui/react';import type { A2UIClientEventMessage } from '@a2ui/react';import { injectStyles } from '@a2ui/react/styles';import App from './App.tsx'+import { EnterpriseEntry } from './EnterpriseEntry.tsx'import { dispatchA2UIAction } from './features/a2ui/actionBridge';import { installDesktopLocalFilesBridge } from './features/workspace/localFilePicker';import './styles/foundation.css'@@ -39,7 +40,9 @@ function handleA2UIAction(message: A2UIClientEventMessage) {}ReactDOM.createRoot(document.getElementById('root')!).render(- <A2UIProvider onAction={handleA2UIAction}>- <App />- </A2UIProvider>,+ <EnterpriseEntry>+ <A2UIProvider onAction={handleA2UIAction}>+ <App />+ </A2UIProvider>+ </EnterpriseEntry>,)diff --git a/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts b/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.tsindex f4cf7ded84..1b42053aad 100644--- a/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts@@ -2,6 +2,7 @@ export interface RuntimeScope {userId?: string;groupId?: string;botId?: string;+ gatewayId?: string;}function pickString(value: unknown): string | undefined {@@ -28,17 +29,40 @@ function pickQueryValue(query: URLSearchParams, key: string): string | undefinedexport function parseRuntimeScope(search: string): RuntimeScope {const query = new URLSearchParams(search);return {+ // 租户身份只允许由登录后的 Manager Web 选择上下文注入。userId: pickQueryValue(query, 'user_id'),groupId: pickQueryValue(query, 'group_id'),botId: pickQueryValue(query, 'bot_id'),+ gatewayId: pickQueryValue(query, 'gateway_id'),+ };+}++// 企业版嵌入入口会通过 query 注入租户路由身份;SPA 随后可能跳转到+// /chat/new 并移除 query。仅保存在当前页面内存,不写 local/sessionStorage。+let runtimeScope: RuntimeScope =+ typeof window === 'undefined' ? {} : parseRuntimeScope(window.location.search);++export function setRuntimeScope(scope: RuntimeScope): void {+ runtimeScope = {+ userId: pickString(scope.userId),+ groupId: pickString(scope.groupId),+ botId: pickString(scope.botId),+ gatewayId: pickString(scope.gatewayId),};}export function getRuntimeScope(): RuntimeScope {if (typeof window === 'undefined') {- return {};+ return runtimeScope;}- return parseRuntimeScope(window.location.search);+ const current = parseRuntimeScope(window.location.search);+ runtimeScope = {+ userId: current.userId ?? runtimeScope.userId,+ groupId: current.groupId ?? runtimeScope.groupId,+ botId: current.botId ?? runtimeScope.botId,+ gatewayId: current.gatewayId ?? runtimeScope.gatewayId,+ };+ return runtimeScope;}/** Add the current runtime scope to a WebSocket handshake query. */@@ -49,6 +73,7 @@ export function appendRuntimeScopeQuery(if (scope.userId) query.set('user_id', scope.userId);if (scope.groupId) query.set('group_id', scope.groupId);if (scope.botId) query.set('bot_id', scope.botId);+ if (scope.gatewayId) query.set('gateway_id', scope.gatewayId);return query;}@@ -59,6 +84,8 @@ export function buildRuntimeIdentityHeaders(scope: RuntimeScope = getRuntimeScope()): Record<string, string> {const headers: Record<string, string> = { 'X-Request-Id': requestId };+ const accessToken = typeof localStorage === 'undefined' ? null : localStorage.getItem('openjiuwen_access_token');+ if (accessToken) headers.Authorization = `Bearer ${accessToken}`;const userId = scope.userId ?? pickString(params.user_id);const groupId = scope.groupId ?? pickString(params.group_id);const botId = scope.botId ?? pickString(params.bot_id);@@ -66,6 +93,7 @@ export function buildRuntimeIdentityHeaders(if (userId) headers['X-User-Id'] = userId;if (groupId) headers['X-Group-Id'] = groupId;if (botId) headers['X-Bot-Id'] = botId;+ if (scope.gatewayId) headers['X-Jiuwenclaw-Id'] = scope.gatewayId;if (sessionId) headers['X-Session-Id'] = sessionId;return headers;}diff --git a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts b/jiuwenswarm/channels/web/frontend/src/vite-env.d.tsindex a22b395301..b5dda053f6 100644--- a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts+++ b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts@@ -44,4 +44,7 @@ interface Window {};/** Durable ingest hook invoked by desktop_app.py run_js on native file drops. */__JIUWEN_INGEST_LOCAL_FILES__?: (detail: unknown) => void;+ /** Set by the User Web server for enterprise embedding mode. */+ __JIUWEN_USER_WEB_MODE__?: string;+ __JIUWEN_USER_WEB_EMBEDDING__?: boolean;}diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.tsindex ab1ac2164a..85c113369d 100644--- a/jiuwenswarm/channels/web/frontend/vite.config.ts+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts@@ -321,13 +321,19 @@ function resolveWebHttpPort(wsPort: number): number {const frontendPort = portFromEnv('FRONTEND_PORT', 5173)const webPort = portFromEnv('WEB_PORT', 19000)-const webTarget = process.env.GATEWAY_URL?.replace(/\/$/, '') || `http://127.0.0.1:${webPort}`+const webTarget =+ process.env.GATEWAY_WEB_WS_URL?.replace(/\/$/, '') ||+ process.env.GATEWAY_URL?.replace(/\/$/, '') ||+ `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({+ // 产物会被 Manager Web 挂载在 /chat/ iframe 中;使用相对资源路径,+ // 避免 iframe 的 JS/CSS 请求回到 Manager 根路径。+ base: './',plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), react(), svgr()],optimizeDeps: {include: ['exceljs', 'jszip', 'saxes', 'ssf'],@@ -341,6 +347,8 @@ export default defineConfig({port: frontendPort,strictPort: true,proxy: {+ '/idp': { target: process.env.USER_WEB_IDP_TARGET || 'http://127.0.0.1:8770', changeOrigin: true, rewrite: (p) => p.replace(/^\/idp/, '') },+ '/manager-api': { target: process.env.USER_WEB_MANAGER_TARGET || 'http://127.0.0.1:8765', changeOrigin: true, rewrite: (p) => p.replace(/^\/manager-api/, '/api') },'/file-api': {target: webHttpTarget,changeOrigin: true,diff --git a/jiuwenswarm/gateway/channel_manager/web/invoke.py b/jiuwenswarm/gateway/channel_manager/web/invoke.pyindex 0c269e9b79..7a93dddfa5 100644--- a/jiuwenswarm/gateway/channel_manager/web/invoke.py+++ b/jiuwenswarm/gateway/channel_manager/web/invoke.py@@ -18,6 +18,29 @@ logger = logging.getLogger(__name__)# mapped routes already expose so WebSocket and HTTP have identical behavior._LOCAL_ROUTING_IDENTITY_PREFIXES = ("cron.", "skills.enterprise.")+_ENTERPRISE_BLOCKED_EXACT = frozenset({+ "config.set", "config.save_all", "models.replace_all", "models.save",+ "models.remove", "models.set_active", "path.set", "updater.download",+ "updater.upgrade", "updater.reset_source", "updater.set_conf",+})+_ENTERPRISE_BLOCKED_PREFIXES = ("agents.", "teams.", "extensions.", "plugins.")+_ENTERPRISE_SKILL_ALLOWED = frozenset({"skills.list", "skills.get", "skills.enterprise.list"})+++def is_enterprise_write_forbidden(method: str) -> bool:+ """Central guard shared by WS and HTTP; Cron and locale remain user-writable."""+ from jiuwenswarm.gateway.edition import is_gateway_enterprise++ if not is_gateway_enterprise():+ return False+ if method in _ENTERPRISE_BLOCKED_EXACT or method.startswith(_ENTERPRISE_BLOCKED_PREFIXES):+ return True+ if method.startswith("channel.") and (method.endswith(".set_conf") or method.endswith(".unbind")):+ return True+ if method.startswith("skills.") and method not in _ENTERPRISE_SKILL_ALLOWED:+ return True+ return False+async def dispatch_web_request(channel: Any,@@ -40,6 +63,13 @@ async def dispatch_web_request(MethodHandlerInvocation as _MethodHandlerInvocation,)+ if is_enterprise_write_forbidden(method):+ await channel.send_response(+ outbound, request_id, ok=False,+ error="企业版配置由管理面统一下发", code="FORBIDDEN",+ )+ return+handler = channel.rpc.method_handlers.get(method)handler_params = paramsif method.startswith(_LOCAL_ROUTING_IDENTITY_PREFIXES):diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/extension.yaml b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/extension.yamlindex 2e3ae80fc7..a04c8a373d 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/extension.yaml+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/extension.yaml@@ -4,11 +4,7 @@ version: 0.2.0description: Gateway HTTP config receiver for Claw Manager sync (replaces manager_ws_client WebSocket client)author: openjiuwenmin_jiuwenclaw_version: "0.1.0"-dependencies:- pydantic-settings: ">=2.0"- python-dotenv: ">=1.0"- # DBHandler / link_auth;与 runtime_management_extension 同源- openjiuwen_runtime_foundation: " @ git+https://gitcode.com/openJiuwen/agent-runtime.git@develop#subdirectory=foundation"+dependencies: {}config_schema:type: objectproperties:diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.pynew file mode 100644index 0000000000..4f47cd4b0f--- /dev/null+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py@@ -0,0 +1,18 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Gateway Config Receiver 对外可访问 endpoint 解析。"""++from __future__ import annotations++from .config import Settings, get_settings+++def resolve_public_endpoint(cfg: Settings | None = None) -> str:+ """Manager 回调用的 Gateway Config Receiver Base URL(无尾斜杠)。++ 由 ``GATEWAY_CONFIG_PUBLIC_HOST`` + ``GATEWAY_CONFIG_HTTP_PORT`` 拼接;+ host 未配置时默认 ``127.0.0.1``。+ """+ cfg = cfg or get_settings()+ port = int(cfg.gateway_config_http_port or 8775)+ host = (cfg.gateway_config_public_host or "").strip() or "127.0.0.1"+ return f"http://{host}:{port}"diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/extension.yaml b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/extension.yamlindex 1e2a2741c8..e98eead8f9 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/extension.yaml+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/extension.yaml@@ -4,8 +4,6 @@ version: 0.1.0description: OpenJiuwen Runtimeauthor: openjiuwenmin_jiuwenclaw_version: "0.1.0"-dependencies:- openjiuwen_runtime_management: " @ git+https://gitcode.com/openJiuwen/agent-runtime.git@develop_0708_release#subdirectory=management"- openjiuwen_runtime_foundation: " @ git+https://gitcode.com/openJiuwen/agent-runtime.git@develop_0708_release#subdirectory=foundation"+dependencies: {}config_schema:type: object