Skip to content

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

Python

fix(enterprise): 打通统一用户入口并补齐 Gateway 与联合认证部署配置

whqca6f735a0e7f
diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.example
index 4deeb7811f..79e1c1354e 100644
--- a/deploy/enterprise/.env.example
+++ b/deploy/enterprise/.env.example
@@ -22,7 +22,6 @@ IS_MOUNT_WEB_CODE="false"
# 是否要给 Manager Web 模块mount代码
# 注意 Manager Web 源代码代码需要npm intall之后,才能mount进容器,此操作只需要一次
-# 另外请手动创建 $RUNTIME_CODE_PATH/applications/access/user_web/dist空目录占位,满足 manager-web 对 --chat-dist 的存在性检查
IS_MOUNT_MANAGER_WEB_CODE="false"
# 数据库类型,支持mysql、sqlite、postgresql, 不配默认就是sqlite
@@ -456,11 +455,14 @@ MANAGER_WEB_IMAGE=""
# 控制是否启动Manager 前端模块
IS_UP_MANAGER_WEB=false
-# 是否由 Manager Web 作为用户面统一登录入口
-# false:User Web 保持独立 NodePort 入口
-# true:用户登录 Manager Web 后通过 /user 内嵌 User Web,且不再暴露 User Web NodePort
-# 启用时必须同时设置 IS_UP_MANAGER_WEB=true
-ENABLE_USER_WEB_EMBEDDING=false
+# 用户面产品形态:personal 或 enterprise
+# personal:通过 User Web NodePort 提供独立用户面
+# enterprise:通过 Manager Web 统一登录并内嵌用户面,不暴露 User Web NodePort
+# enterprise 模式必须同时设置 IS_UP_MANAGER_WEB=true
+USER_WEB_MODE=personal
+
+# 已废弃,仅兼容旧配置;新部署请使用 USER_WEB_MODE
+# ENABLE_USER_WEB_EMBEDDING=false
# Manager 前端模块对外暴露的主机端口
# 不设置就自动寻找空闲端口,如需要设置,请确保该端口的唯一性(范围: 30000-32767)
@@ -486,6 +488,14 @@ IDENTITY_IMAGE=""
IDENTITY_SEED_ADMIN=true
IDENTITY_SEED_USER1=true
+# 联合认证 Demo Provider(仅用于本地/集成链路验证,默认关闭)
+# 通过 Manager Web 统一入口访问时,PUBLIC_PATH_PREFIX 保持 /idp。
+IDENTITY_FEDERATION_DEMO_ENABLED=false
+IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX=/idp
+IDENTITY_FEDERATION_REQUEST_TTL=300
+IDENTITY_FEDERATION_CODE_TTL=60
+IDENTITY_FEDERATION_DEMO_ADMIN_GROUP=enterprise-admins
+
# ====================== Agent Runtime 服务配置 ======================
# Agent Runtime 服务镜像地址
diff --git a/deploy/enterprise/README.md b/deploy/enterprise/README.md
index ec26fda421..a7060cd820 100644
--- a/deploy/enterprise/README.md
+++ b/deploy/enterprise/README.md
@@ -646,6 +646,21 @@ Manager 为平台管理模块,提供策略下发和配置、业务实例监控
IS_UP_MANAGER_WEB=false
```
+Identity Center 的企业联合认证 Demo 默认关闭。需要验证联合登录链路时,在
+`.env.custom` 中显式开启;该 Demo 只用于联调,不接收或验证真实 SAML 报文:
+
+```bash
+IDENTITY_FEDERATION_DEMO_ENABLED=true
+IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX=/idp
+IDENTITY_FEDERATION_REQUEST_TTL=300
+IDENTITY_FEDERATION_CODE_TTL=60
+IDENTITY_FEDERATION_DEMO_ADMIN_GROUP=enterprise-admins
+```
+
+开启后应通过 Manager Web 的 `/idp` 同源代理访问 Identity Center,因此
+`IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX` 保持 `/idp`。登录页会根据 Identity Center
+返回的可用连接动态显示企业登录入口,不需要额外的 Manager Web 开关。
+
### 4.3 部署 Web(可选部署)
Web 为 JiuwenSwarm 企业版面向终端用户的对话可视化前端,用于用户直接和大模型机器人在线对话功能。该模块为可选组件,若业务仅通过飞书渠道与机器人交互、无需网页端对话入口,则可不部署。
@@ -657,35 +672,41 @@ Web 为 JiuwenSwarm 企业版面向终端用户的对话可视化前端,用于
#### 4.3.1 用户面入口模式
-用户面支持独立入口和 Manager Web 统一登录入口两种部署方式。通过 `.env.custom` 配置:
+用户面通过 `USER_WEB_MODE` 选择产品形态:
```bash
-# false:保留 User Web 独立 NodePort 入口(默认,兼容原有部署)
-# true:用户登录 Manager Web 后从 /user 进入内嵌 User Web,不暴露 User Web NodePort
-ENABLE_USER_WEB_EMBEDDING=false
+# personal:通过 User Web NodePort 提供独立用户面
+# enterprise:通过 Manager Web 统一登录并内嵌用户面,不暴露 User Web NodePort
+USER_WEB_MODE=personal
```
-启用统一入口时,Manager Web 是用户面唯一的集群外入口,User Web 仍会部署并保留
-ClusterIP,供 Manager Web 转发文件请求等内部调用。配置必须同时满足:
+`personal` 模式下,用户通过 User Web NodePort 直接使用独立用户面。`enterprise`
+模式下,Manager Web 是唯一对外入口:用户先通过 Identity Center 登录,在 Manager Web
+中选择组网、组织和 Bot,再进入同源 `/chat/` 内嵌用户面。User Web 仍保留供 Manager Web
+访问的 ClusterIP 服务,但部署脚本不会创建其 NodePort;enterprise 模式必须部署 Manager Web:
```bash
-ENABLE_USER_WEB_EMBEDDING=true
+USER_WEB_MODE=enterprise
IS_UP_MANAGER_WEB=true
```
-统一入口使用以下同源路由,不需要额外暴露 Identity、Manager Server、Gateway 或
-User Server:
+旧配置 `ENABLE_USER_WEB_EMBEDDING` 仅作兼容输入:`true` 等价于
+`USER_WEB_MODE=enterprise`,`false` 等价于 `USER_WEB_MODE=personal`。新部署不应继续使用。
+
+Manager Web 内嵌入口使用以下同源路由,不需要额外暴露 Identity、Manager Server 或
+Gateway:
| 路径 | 目标服务 | 用途 |
|---|---|---|
| `/idp/*` | Identity Center | 登录、刷新令牌和用户信息 |
| `/api/*` | Manager Server | 管理面与用户目录接口 |
-| `/chat/*` | Manager Web 内置 User Web | 用户面对话界面 |
-| `/web/invoke` | Gateway HTTP/SSE | 对话请求与流式响应 |
-| `/file-api/*` | User Server | 文件相关接口 |
+| `/chat/*` | User Web HTTP | 用户面对话界面 |
+| `/ws*` | Gateway WebSocket | 用户面默认消息通道 |
+| `/gateway-api/*` | Gateway Web HTTP/SSE | 用户面 REST/SSE 通道,与 Manager `/api/v1` 隔离 |
+| `/file-api/*`、`/share-api/*` | Gateway Web HTTP | 文件与分享接口 |
-从独立入口切换为统一入口时,部署脚本会删除同命名空间中已有的 User Web NodePort
-Service,避免用户绕过统一登录入口;切回独立入口并重新部署 Web 后会恢复 NodePort。
+Manager Web 与 `/chat/` 使用同一浏览器源,登录状态由 Manager Web 统一管理。User Web
+只消费 Manager Web 注入的用户、组织、Bot 和组网上下文,不提供另一套登录入口。
#### 4.3.2 升级已有 MySQL 数据库
diff --git a/deploy/enterprise/deploy.sh b/deploy/enterprise/deploy.sh
index 2b6b75facb..b6c698eb94 100755
--- a/deploy/enterprise/deploy.sh
+++ b/deploy/enterprise/deploy.sh
@@ -97,7 +97,7 @@ main() {
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"
+ warning "ENABLE_USER_WEB_EMBEDDING is deprecated; use USER_WEB_MODE=enterprise"
else
DEPLOY_VARS["USER_WEB_MODE"]="personal"
fi
diff --git a/deploy/enterprise/example/manager-web.yaml b/deploy/enterprise/example/manager-web.yaml
index fc863fad5b..5eb46ee5f2 100644
--- a/deploy/enterprise/example/manager-web.yaml
+++ b/deploy/enterprise/example/manager-web.yaml
@@ -32,10 +32,12 @@ spec:
value: "http://jiuwenclaw-manager-server:8765"
- name: MANAGER_WEB_IDP_TARGET
value: "http://jiuwenclaw-identity:8770"
- - name: MANAGER_WEB_GATEWAY_SSE
- value: "http://jiuwenclaw-gateway:19001/web/invoke"
- - name: MANAGER_WEB_USER_SERVER_TARGET
- value: "http://jiuwenclaw-web:19000"
+ - name: MANAGER_WEB_USER_WEB_TARGET
+ value: "http://jiuwenclaw-web:5173"
+ - name: MANAGER_WEB_GATEWAY_HTTP_TARGET
+ value: "http://jiuwenclaw-gateway:19002"
+ - name: MANAGER_WEB_GATEWAY_WS_TARGET
+ value: "http://jiuwenclaw-gateway:19000"
- name: TZ
value: "Asia/Shanghai"
diff --git a/deploy/enterprise/example/web.yaml b/deploy/enterprise/example/web.yaml
index 9571a4916a..1ec5fdb645 100644
--- a/deploy/enterprise/example/web.yaml
+++ b/deploy/enterprise/example/web.yaml
@@ -79,6 +79,9 @@ spec:
selector:
app: jiuwenclaw-web
ports:
+ - name: http
+ port: 5173
+ targetPort: 5173
- name: websocket
port: 19000 # Service 端口
targetPort: 19000 # 容器端口
diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.sh
index e13835276c..44b719ad94 100755
--- a/deploy/enterprise/global_vars.sh
+++ b/deploy/enterprise/global_vars.sh
@@ -150,6 +150,11 @@ declare -A DEPLOY_VARS=(
["IDENTITY_DB_NAME"]="identity"
["IDENTITY_SEED_ADMIN"]="true"
["IDENTITY_SEED_USER1"]="true"
+ ["IDENTITY_FEDERATION_DEMO_ENABLED"]="false"
+ ["IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX"]="/idp"
+ ["IDENTITY_FEDERATION_REQUEST_TTL"]="300"
+ ["IDENTITY_FEDERATION_CODE_TTL"]="60"
+ ["IDENTITY_FEDERATION_DEMO_ADMIN_GROUP"]="enterprise-admins"
["JINA_NAME"]="jina"
["JINA_CACHE_IMAGE"]="nginx:alpine"
["JINA_READER_IMAGE"]="ghcr.1ms.run/jina-ai/reader:latest"
diff --git a/deploy/enterprise/template_handler.sh b/deploy/enterprise/template_handler.sh
index 77ce34591a..302dd17786 100755
--- a/deploy/enterprise/template_handler.sh
+++ b/deploy/enterprise/template_handler.sh
@@ -115,32 +115,27 @@ mount_core_pkg() {
"${DEPLOY_VARS["CORE_POD_PKG_PATH"]}"
}
-# Override the container command to run the frontend vite dev server (HMR) in
-# <workdir> on <port>, bound to 0.0.0.0 so the Service/NodePort can reach it.
-# Usage: run_frontend_dev <file> <workdir> <port>
-run_frontend_dev() {
- local file="$1" comp="$2"
- local workdir="" port=""
+# User Web 挂载代码时先构建静态资源,再走与产品镜像相同的入口。
+# Vite dev HTML 使用根路径资源,不能完整经由 Manager Web 的 /chat 子路径代理。
+run_web_mounted() {
+ local file="$1"
+ [ -z "${DEPLOY_VARS["CLAW_POD_CODE_PATH"]:-}" ] && return
+ local root="${DEPLOY_VARS["CLAW_POD_CODE_PATH"]}"
+ local workdir="${root}/jiuwenswarm/channels/web/frontend"
- case "${comp}" in
- web)
- [ -z "${DEPLOY_VARS["CLAW_POD_CODE_PATH"]:-}" ] && return
- workdir="${DEPLOY_VARS["CLAW_POD_CODE_PATH"]}/jiuwenswarm/channels/web/frontend"
- port="${DEPLOY_VARS["WEB_HTTP_PORT"]}"
- ;;
- manager-web)
- [ -z "${DEPLOY_VARS["RUNTIME_CODE_PATH"]:-}" ] && return
- workdir="${DEPLOY_VARS["RUNTIME_POD_CODE_PATH"]}/applications/manager/manager_web"
- port="${DEPLOY_VARS["MANAGER_WEB_PORT"]}"
- ;;
- *)
- warning "run_frontend_dev: unknown component '${comp}', skipping"
- return
- ;;
- esac
+ yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].command = ["/bin/sh", "-c"]' -i "${file}"
+ yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].args = ["cd '"${workdir}"' && npm run build && cd '"${root}"' && exec jiuwenswarm-start web"]' -i "${file}"
+}
+
+# Manager Web 的挂载验证走与产品镜像相同的 Python 统一入口,
+# 以覆盖鉴权、HTTP/SSE 和 WebSocket 反向代理。
+run_manager_web_mounted() {
+ local file="$1"
+ [ -z "${DEPLOY_VARS["RUNTIME_POD_CODE_PATH"]:-}" ] && return
+ local workdir="${DEPLOY_VARS["RUNTIME_POD_CODE_PATH"]}/applications/manager/manager_web"
yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].command = ["/bin/sh", "-c"]' -i "${file}"
- yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].args = ["cd '"${workdir}"' && npm run dev -- --host 0.0.0.0 --port '"${port}"'"]' -i "${file}"
+ yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].args = ["cd '"${workdir}"' && npm run build && exec manager-web"]' -i "${file}"
}
enable_dev_mode_if_needed() {
@@ -158,7 +153,7 @@ enable_dev_mode_if_needed() {
mount_claw_code "${file}"
mount_runtime_pkg "${file}"
mount_core_pkg "${file}"
- run_frontend_dev "${file}" "${comp}"
+ run_web_mounted "${file}"
;;
manager-server)
mount_runtime_code "${file}"
@@ -172,7 +167,7 @@ enable_dev_mode_if_needed() {
manager-web)
[ "${DEPLOY_VARS["IS_MOUNT_MANAGER_WEB_CODE"]}" != "true" ] && return
mount_runtime_code "${file}"
- run_frontend_dev "${file}" "${comp}"
+ run_manager_web_mounted "${file}"
;;
*)
warning "enable_dev_mode_if_needed: unknown component '${comp}', skipping"
@@ -215,4 +210,4 @@ add_resource_if_set() {
if [ -n "${DEPLOY_VARS["${module}_MEMORY_LIMIT"]:-}" ]; then
yq eval 'select(.kind == "'"${kind_type}"'").spec.template.spec.containers[0].resources.limits.memory = "'"${DEPLOY_VARS["${module}_MEMORY_LIMIT"]}"'"' -i "${file}"
fi
-}
\ No newline at end of file
+}
diff --git a/deploy/enterprise/templates/.env.custom.template b/deploy/enterprise/templates/.env.custom.template
index c2ce358615..9fc60cc356 100644
--- a/deploy/enterprise/templates/.env.custom.template
+++ b/deploy/enterprise/templates/.env.custom.template
@@ -22,11 +22,18 @@ JIUWENSWARM_EDITION="enterprise"
GATEWAY_SESSION_MAP_SCOPE="per_chat_bot_user"
JIUWENBOX_ENABLED=true
-# 是否启动 Manager Web;启用用户面内嵌模式时必须为 true
+# 是否启动 Manager Web;USER_WEB_MODE=enterprise 时必须为 true
IS_UP_MANAGER_WEB=true
-# false:User Web 保持独立入口;true:通过 Manager Web 登录后内嵌访问
-ENABLE_USER_WEB_EMBEDDING=false
+# 用户面产品形态:personal(独立 NodePort 入口)或 enterprise(仅通过 Manager Web 进入)
+USER_WEB_MODE=personal
+
+# 联合认证 Demo Provider(仅用于部署联调,默认关闭)
+IDENTITY_FEDERATION_DEMO_ENABLED=false
+IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX=/idp
+IDENTITY_FEDERATION_REQUEST_TTL=300
+IDENTITY_FEDERATION_CODE_TTL=60
+IDENTITY_FEDERATION_DEMO_ADMIN_GROUP=enterprise-admins
# 设置空闲端口,请确保该端口的唯一性(范围: 30000-32767)
diff --git a/deploy/enterprise/templates/gateway.template.yaml b/deploy/enterprise/templates/gateway.template.yaml
index f6ab3e9dd8..73a6b09090 100644
--- a/deploy/enterprise/templates/gateway.template.yaml
+++ b/deploy/enterprise/templates/gateway.template.yaml
@@ -168,4 +168,4 @@ spec:
- name: config-http
port: <<GATEWAY_CONFIG_HTTP_PORT>>
targetPort: <<GATEWAY_CONFIG_HTTP_PORT>>
- type: ClusterIP # 集群内部访问,不需要外网
\ No newline at end of file
+ type: ClusterIP # 集群内部访问,不需要外网
diff --git a/deploy/enterprise/templates/identity.template.yaml b/deploy/enterprise/templates/identity.template.yaml
index 7c5f9e38a8..66752579f5 100644
--- a/deploy/enterprise/templates/identity.template.yaml
+++ b/deploy/enterprise/templates/identity.template.yaml
@@ -58,5 +58,15 @@ spec:
value: "<<IDENTITY_SEED_ADMIN>>"
- name: IDENTITY_SEED_USER1
value: "<<IDENTITY_SEED_USER1>>"
+ - name: IDENTITY_FEDERATION_DEMO_ENABLED
+ value: "<<IDENTITY_FEDERATION_DEMO_ENABLED>>"
+ - name: IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX
+ value: "<<IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX>>"
+ - name: IDENTITY_FEDERATION_REQUEST_TTL
+ value: "<<IDENTITY_FEDERATION_REQUEST_TTL>>"
+ - name: IDENTITY_FEDERATION_CODE_TTL
+ value: "<<IDENTITY_FEDERATION_CODE_TTL>>"
+ - name: IDENTITY_FEDERATION_DEMO_ADMIN_GROUP
+ value: "<<IDENTITY_FEDERATION_DEMO_ADMIN_GROUP>>"
- name: TZ
value: "<<TIMEZONE>>"
diff --git a/deploy/enterprise/templates/manager-web.template.yaml b/deploy/enterprise/templates/manager-web.template.yaml
index 362c79af64..2be8e507da 100644
--- a/deploy/enterprise/templates/manager-web.template.yaml
+++ b/deploy/enterprise/templates/manager-web.template.yaml
@@ -37,10 +37,12 @@ spec:
value: "http://<<MANAGER_SERVER_NAME>>:<<MANAGER_REST_PORT>>"
- name: MANAGER_WEB_IDP_TARGET
value: "http://<<IDENTITY_NAME>>:<<IDENTITY_REST_PORT>>"
- - name: MANAGER_WEB_GATEWAY_SSE
- value: "http://<<GATEWAY_NAME>>:<<GATEWAY_WEB_HTTP_PORT>>/web/invoke"
- - name: MANAGER_WEB_USER_SERVER_TARGET
+ - name: MANAGER_WEB_USER_WEB_TARGET
value: "http://<<WEB_NAME>>:<<WEB_HTTP_PORT>>"
+ - name: MANAGER_WEB_GATEWAY_HTTP_TARGET
+ value: "http://<<GATEWAY_NAME>>:<<GATEWAY_WEB_HTTP_PORT>>"
+ - name: MANAGER_WEB_GATEWAY_WS_TARGET
+ value: "http://<<GATEWAY_NAME>>:<<WEB_PORT>>"
- name: TZ
value: "<<TIMEZONE>>"
diff --git a/deploy/enterprise/templates/web.template.yaml b/deploy/enterprise/templates/web.template.yaml
index cc99d43fa3..9153a0e381 100644
--- a/deploy/enterprise/templates/web.template.yaml
+++ b/deploy/enterprise/templates/web.template.yaml
@@ -86,6 +86,9 @@ spec:
selector:
app: <<WEB_NAME>>
ports:
+ - name: http
+ port: <<WEB_HTTP_PORT>>
+ targetPort: <<WEB_HTTP_PORT>>
- name: websocket
port: <<WEB_WS_PORT>> # Service 端口
targetPort: <<WEB_WS_PORT>> # 容器端口
diff --git a/deploy/enterprise/tests/test_identity_user_web_deploy.sh b/deploy/enterprise/tests/test_identity_user_web_deploy.sh
index 4eca6a9ed5..fd091667d6 100755
--- a/deploy/enterprise/tests/test_identity_user_web_deploy.sh
+++ b/deploy/enterprise/tests/test_identity_user_web_deploy.sh
@@ -72,9 +72,9 @@ main() {
DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]="true"
gen_web_file
assert_equal \
- "1" \
+ "0" \
"$(yq eval-all '[select(.metadata.name == "jiuwenclaw-web-nodeport")] | length' "${CONFIG["WEB_FILE"]}")" \
- "enterprise mode must retain the configured User Web NodePort"
+ "enterprise mode must not expose the User Web NodePort"
DEPLOY_VARS["IS_UP_MANAGER_WEB"]="false"
if (check_user_web_mode_config) >/dev/null 2>&1; then
@@ -101,6 +101,32 @@ main() {
"$(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["IDENTITY_FILE"]="${test_dir}/identity.yaml"
+ render_config_template \
+ "${CONFIG["IDENTITY_TEMPLATE_FILE"]}" \
+ "${CONFIG["IDENTITY_FILE"]}" \
+ "DEPLOY_VARS"
+ assert_equal \
+ "false" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_DEMO_ENABLED").value' "${CONFIG["IDENTITY_FILE"]}")" \
+ "Identity federation Demo must remain disabled by default"
+ assert_equal \
+ "/idp" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_PUBLIC_PATH_PREFIX").value' "${CONFIG["IDENTITY_FILE"]}")" \
+ "Identity federation browser URLs must use the Manager Web IDP prefix"
+ assert_equal \
+ "300" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_REQUEST_TTL").value' "${CONFIG["IDENTITY_FILE"]}")" \
+ "Identity federation request TTL must be rendered"
+ assert_equal \
+ "60" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_CODE_TTL").value' "${CONFIG["IDENTITY_FILE"]}")" \
+ "Identity federation code TTL must be rendered"
+ assert_equal \
+ "enterprise-admins" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "IDENTITY_FEDERATION_DEMO_ADMIN_GROUP").value' "${CONFIG["IDENTITY_FILE"]}")" \
+ "Identity federation admin group must be rendered"
+
CONFIG["MANAGER_WEB_FILE"]="${test_dir}/manager-web.yaml"
render_config_template \
"${CONFIG["MANAGER_WEB_TEMPLATE_FILE"]}" \
@@ -110,8 +136,43 @@ main() {
"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"
+ assert_equal \
+ "http://jiuwenclaw-web:5173" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_USER_WEB_TARGET").value' "${CONFIG["MANAGER_WEB_FILE"]}")" \
+ "Manager Web must route /chat to the User Web HTTP service"
+ assert_equal \
+ "http://jiuwenclaw-gateway:19002" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_GATEWAY_HTTP_TARGET").value' "${CONFIG["MANAGER_WEB_FILE"]}")" \
+ "Manager Web must route HTTP/SSE to the Gateway Web HTTP service"
+ assert_equal \
+ "http://jiuwenclaw-gateway:19000" \
+ "$(yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_GATEWAY_WS_TARGET").value' "${CONFIG["MANAGER_WEB_FILE"]}")" \
+ "Manager Web must route WebSocket to the Gateway WebSocket service"
+ assert_equal \
+ "0" \
+ "$(yq eval-all '[select(.kind == "Deployment").spec.template.spec.containers[0].env[] | select(.name == "MANAGER_WEB_GATEWAY_SSE" or .name == "MANAGER_WEB_USER_SERVER_TARGET")] | length' "${CONFIG["MANAGER_WEB_FILE"]}")" \
+ "obsolete Manager Web proxy variables must not be rendered"
+ assert_equal \
+ "5173" \
+ "$(yq eval-all 'select(.kind == "Service" and .metadata.name == "jiuwenclaw-web").spec.ports[] | select(.name == "http").port' "${CONFIG["WEB_FILE"]}")" \
+ "User Web ClusterIP service must expose its HTTP port"
+
+ CONFIG["GATEWAY_FILE"]="${test_dir}/gateway.yaml"
+ render_config_template \
+ "${CONFIG["GATEWAY_TEMPLATE_FILE"]}" \
+ "${CONFIG["GATEWAY_FILE"]}" \
+ "DEPLOY_VARS"
+ assert_equal \
+ "1" \
+ "$(yq eval-all '[select(.kind == "Service" and .metadata.name == "jiuwenclaw-gateway").spec.ports[] | select(.port == 19001)] | length' "${CONFIG["GATEWAY_FILE"]}")" \
+ "Gateway Service must expose its shared HTTP and ACP listener only once"
+ assert_equal \
+ "http" \
+ "$(yq eval-all 'select(.kind == "Service" and .metadata.name == "jiuwenclaw-gateway").spec.ports[] | select(.port == 19001).name' "${CONFIG["GATEWAY_FILE"]}")" \
+ "Gateway shared listener must use the HTTP service port"
ensure_secret_configmap() { :; }
+ delete_k8s_resource() { :; }
exec_cmd() { :; }
wait_k8s_resource_ready() { :; }
success() { :; }
diff --git a/deploy/enterprise/update_conf.sh b/deploy/enterprise/update_conf.sh
index 38aa5d3eee..6ca9a5395f 100755
--- a/deploy/enterprise/update_conf.sh
+++ b/deploy/enterprise/update_conf.sh
@@ -8,7 +8,8 @@ rm -f "${DEST_FILE}"
cp -f "${SRC_FILE}" "${DEST_FILE}"
yq eval '.gateway.agent_client.type = "jiuwen"' -i "${DEST_FILE}"
-yq eval '.gateway.edition = "${JIUWENSWARM_EDITION:-enterprise}"' -i "${DEST_FILE}"
+JIUWENSWARM_EDITION="${JIUWENSWARM_EDITION:-enterprise}" \
+ yq eval '.gateway.edition = strenv(JIUWENSWARM_EDITION)' -i "${DEST_FILE}"
yq eval '.gateway.session_map_scope = "<<GATEWAY_SESSION_MAP_SCOPE>>"' -i "${DEST_FILE}"
yq eval '.channels.feishu = {}' -i "${DEST_FILE}"
yq eval '.react.max_iterations = "<<AGENT_SERVER_REACT_MAX_ITER>>"' -i "${DEST_FILE}"
diff --git a/deploy/enterprise/web_handler.sh b/deploy/enterprise/web_handler.sh
index a7f1fb19ef..2a9e44b491 100755
--- a/deploy/enterprise/web_handler.sh
+++ b/deploy/enterprise/web_handler.sh
@@ -7,9 +7,12 @@ 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["USER_WEB_MODE"]}" == "enterprise" ]; then
+ local nodeport_name="${DEPLOY_VARS["WEB_NAME"]}-nodeport"
+ yq eval 'select(.metadata.name != "'"${nodeport_name}"'")' -i "${file}"
+ fi
if [ "${DEPLOY_VARS["ENABLE_EXTERNAL_OBS"]}" == "true" ]; then
obs_url="${DEPLOY_VARS["OBS_URL"]}"
@@ -54,7 +57,9 @@ gen_web_file() {
render_web_files() {
render_secret_configmap
- ensure_available_port "WEB_NODE_PORT"
+ if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" != "enterprise" ]; then
+ ensure_available_port "WEB_NODE_PORT"
+ fi
gen_web_file
}
@@ -67,7 +72,8 @@ deploy_web() {
exec_cmd kubectl apply -f ${file}
wait_k8s_resource_ready "deployment" "${name}" "${namespace}"
if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]; then
- success "USER_WEB_LOGIN_ENTRY_NODE_PORT: ${DEPLOY_VARS["WEB_NODE_PORT"]}"
+ delete_k8s_resource "service" "${name}-nodeport" "${namespace}"
+ success "User Web is available through Manager Web; standalone NodePort is disabled"
else
success "WEB_NODE_PORT: ${DEPLOY_VARS["WEB_NODE_PORT"]}"
fi
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.py
index 25f7036389..274d9dcc75 100644
--- a/jiuwenswarm/channels/web/app_web.py
+++ b/jiuwenswarm/channels/web/app_web.py
@@ -68,6 +68,14 @@ def _default_dist_dir() -> Path:
return dist_dir
+def _inject_user_web_runtime_config(document: str, mode: str) -> str:
+ """Inject runtime mode values without modifying JavaScript property names."""
+ return document.replace("__JIUWEN_USER_WEB_MODE_VALUE__", mode).replace(
+ "__JIUWEN_USER_WEB_EMBEDDING_VALUE__",
+ "true" if mode == "enterprise" else "false",
+ )
+
+
class _SpaStaticHandler(SimpleHTTPRequestHandler):
"""Static file handler with SPA fallback to index.html."""
@@ -561,6 +569,8 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
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 == "/gateway-api" or path.startswith("/gateway-api/"):
+ return True
if path.startswith("/file-api/") or path.startswith("/share-api/"):
return True
if path == "/api/sessions" or path.startswith("/api/sessions/"):
@@ -597,11 +607,16 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
if not self.web_http_target:
self.send_error(502, "web http proxy target not configured")
return
+ original_path = self.path
+ parsed_path = urlparse(original_path).path
+ if parsed_path == "/gateway-api" or parsed_path.startswith("/gateway-api/"):
+ self.path = f"/api{original_path[len('/gateway-api'):]}"
self.__dict__["api_target"] = self.web_http_target
try:
self._proxy_http()
finally:
self.__dict__.pop("api_target", None)
+ self.path = original_path
def do_GET(self) -> None: # noqa: N802
if self._is_web_http_route():
@@ -611,9 +626,9 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
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")
+ body = _inject_user_web_runtime_config(
+ index.read_text(encoding="utf-8"), 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)))
@@ -860,7 +875,7 @@ def main() -> None:
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",
+ "[jiuwenswarm-web] /gateway-api,/file-api,/share-api,/api/sessions*,/api/v1* -> %s",
web_http_target,
)
logger.info("[jiuwenswarm-web] ws disable compress: %s", args.ws_disable_compress)
diff --git a/jiuwenswarm/channels/web/frontend/index.html b/jiuwenswarm/channels/web/frontend/index.html
index 6c3ce02e4f..7c6f230ee3 100644
--- a/jiuwenswarm/channels/web/frontend/index.html
+++ b/jiuwenswarm/channels/web/frontend/index.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="zh-CN" data-theme="default" data-color-mode="light">
<head>
<meta charset="UTF-8" />
@@ -10,8 +10,10 @@
<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>
+ <script>
+ window.__JIUWEN_USER_WEB_MODE__ = '__JIUWEN_USER_WEB_MODE_VALUE__';
+ window.__JIUWEN_USER_WEB_EMBEDDING__ = '__JIUWEN_USER_WEB_EMBEDDING_VALUE__' === 'true';
+ </script>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index 29fcbffeab..67d9f11125 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -22,6 +22,7 @@
"test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs",
"test:web-http-client": "tsc src/services/webHttpClient.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/web-http-client --skipLibCheck --noEmitOnError && node --test tests/webHttpClient.test.mjs",
"test:runtime-scope": "tsc src/services/runtimeScope.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/runtime-scope --skipLibCheck --noEmitOnError && node --test tests/runtimeScope.test.mjs",
+ "test:user-web-entry": "esbuild src/EnterpriseEntry.tsx --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/user-web-entry/EnterpriseEntry.mjs --define:import.meta.env.VITE_USER_WEB_MODE='\"personal\"' --define:import.meta.env.VITE_ENABLE_USER_WEB_EMBEDDING='\"false\"' && node --test tests/userWebEntry.test.mjs",
"test:a2a-ingress-panel": "tsc src/components/A2AIngressPanel/a2aIngressPanelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/a2a-ingress-panel-state --skipLibCheck --noEmitOnError && node --test tests/a2aIngressPanelState.test.mjs",
"test:chat-store-streaming": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/chatStoreStreaming.test.mjs",
"test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs",
diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
index f397888c9e..dd2657df18 100644
--- a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
@@ -1,140 +1,94 @@
-import { FormEvent, ReactNode, useEffect, useMemo, useState } from 'react';
-import { setRuntimeScope } from './services/runtimeScope';
+import { type ReactNode, useEffect, useState } from 'react';
import { isEnterpriseMode } from './edition';
-import { EnterpriseContext } from './services/enterpriseContext';
+import { EnterpriseContext, type EnterpriseContextSnapshot, type EnterpriseContextValue } from './services/enterpriseContext';
+import { getRuntimeScope } from './services/runtimeScope';
const ACCESS_KEY = 'openjiuwen_access_token';
-const REFRESH_KEY = 'openjiuwen_refresh_token';
-const CONTEXT_KEY = 'jiuwenclaw:enterprise-context';
-type CachedContext = { userId: string; gatewayId: string; orgId: string; botId: string };
+const CONTEXT_READY_MESSAGE = 'jiuwenswarm:enterprise-context-ready';
+const CONTEXT_SNAPSHOT_MESSAGE = 'jiuwenswarm:enterprise-context-snapshot';
+const CONTEXT_CHANGE_MESSAGE = 'jiuwenswarm:enterprise-context-change';
+const CONTEXT_LOGOUT_MESSAGE = 'jiuwenswarm:enterprise-context-logout';
-function readCachedContext(): CachedContext | null {
- try {
- const value = JSON.parse(localStorage.getItem(CONTEXT_KEY) || 'null') as CachedContext | null;
- return value && value.userId && value.gatewayId && value.orgId && value.botId ? value : null;
- } catch { return null; }
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null;
}
-
-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 isContextSnapshot(value: unknown): value is EnterpriseContextSnapshot {
+ if (!isRecord(value) || !isRecord(value.user) || !isRecord(value.org) || !isRecord(value.gateway)) {
+ return false;
+ }
+ return (
+ typeof value.user.user_id === 'string' &&
+ typeof value.user.display_name === 'string' &&
+ typeof value.org.group_id === 'string' &&
+ typeof value.org.name === 'string' &&
+ Array.isArray(value.orgs) &&
+ typeof value.gateway.jiuwenclaw_id === 'string' &&
+ typeof value.gateway.jiuwenclaw_name === 'string' &&
+ Array.isArray(value.gateways) &&
+ Array.isArray(value.agents) &&
+ typeof value.selectedBot === 'string'
+ );
}
-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'));
+function hasManagerRuntimeContext(): boolean {
+ const scope = getRuntimeScope();
+ return Boolean(scope.userId && scope.groupId && scope.botId && scope.gatewayId);
}
-function persistRuntimeScopeUrl(userId: string, groupId: string, botId: string, gatewayId: string): void {
- const query = new URLSearchParams(window.location.search);
- query.set('user_id', userId);
- query.set('group_id', groupId);
- query.set('bot_id', botId);
- query.set('gateway_id', gatewayId);
- window.history.replaceState({}, '', `${window.location.pathname}?${query.toString()}`);
+function canEnterEnterpriseUserWeb(): boolean {
+ if (typeof localStorage === 'undefined') {
+ return false;
+ }
+ return Boolean(localStorage.getItem(ACCESS_KEY)) && hasManagerRuntimeContext();
}
export function EnterpriseEntry({ children }: { children: ReactNode }) {
- const enabled = isEnterpriseMode();
- const cached = useMemo(readCachedContext, []);
- 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[]>([]);
- const [selectedBot, setSelectedBot] = useState<string | null>(null);
+ const [context, setContext] = useState<EnterpriseContextSnapshot | null>(null);
useEffect(() => {
- if (!enabled || user || !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);
- const query = new URLSearchParams(window.location.search);
- const saved = cached?.userId === me.user_id ? cached : null;
- const gatewayId = query.get('gateway_id') || saved?.gatewayId;
- const orgId = query.get('group_id') || saved?.orgId;
- const botId = query.get('bot_id') || saved?.botId;
- setGateway(gatewayResult.gateways.find((item) => item.jiuwenclaw_id === gatewayId) || null);
- setOrg(orgResult.orgs.find((item) => item.group_id === orgId) || null);
- setSelectedBot(botId || null);
- }).catch(() => { localStorage.removeItem(ACCESS_KEY); localStorage.removeItem(REFRESH_KEY); localStorage.removeItem(CONTEXT_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]);
-
- useEffect(() => {
- if (!user || !org || !gateway || !selectedBot) return;
- const agent = agents.find((item) => (item.resource_id || item.template_id) === selectedBot);
- if (!agent) return;
- setRuntimeScope({ userId: user.user_id, groupId: org.group_id, botId: selectedBot, gatewayId: gateway.jiuwenclaw_id });
- persistRuntimeScopeUrl(user.user_id, org.group_id, selectedBot, gateway.jiuwenclaw_id);
- setReady(true);
- }, [agents, gateway, org, selectedBot, user]);
-
- if (ready && user && org && gateway && selectedBot) return <EnterpriseContext.Provider value={{ user, org, orgs, gateway, gateways, agents, selectedBot, onOrgChange: (id) => { setOrg(orgs.find((item) => item.group_id === id) || null); setSelectedBot(null); setReady(false); }, onGatewayChange: (id) => { setGateway(gateways.find((item) => item.jiuwenclaw_id === id) || null); setOrg(null); setSelectedBot(null); setReady(false); }, onBotChange: (id) => { const agent = agents.find((item) => (item.resource_id || item.template_id) === id); if (agent) enter(agent); } }}>{children}</EnterpriseContext.Provider>;
-
- 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 : '登录失败'); }
+ if (!isEnterpriseMode() || typeof window.addEventListener !== 'function' || window.parent === window) {
+ return;
+ }
+
+ const handleMessage = (event: MessageEvent) => {
+ if (event.source !== window.parent || event.origin !== window.location.origin) return;
+ if (!isRecord(event.data) || event.data.type !== CONTEXT_SNAPSHOT_MESSAGE) return;
+ if (isContextSnapshot(event.data.context)) setContext(event.data.context);
+ };
+
+ window.addEventListener('message', handleMessage);
+ window.parent.postMessage({ type: CONTEXT_READY_MESSAGE }, window.location.origin);
+ return () => window.removeEventListener('message', handleMessage);
+ }, []);
+
+ if (!isEnterpriseMode() || canEnterEnterpriseUserWeb()) {
+ if (!context) return <>{children}</>;
+
+ const requestChange = (field: 'group_id' | 'gateway_id' | 'bot_id', value: string) => {
+ window.parent.postMessage({ type: CONTEXT_CHANGE_MESSAGE, field, value }, window.location.origin);
+ };
+ const contextValue: EnterpriseContextValue = {
+ ...context,
+ onOrgChange: id => requestChange('group_id', id),
+ onGatewayChange: id => requestChange('gateway_id', id),
+ onBotChange: id => requestChange('bot_id', id),
+ onLogout: () => window.parent.postMessage({ type: CONTEXT_LOGOUT_MESSAGE }, window.location.origin),
+ };
+ return <EnterpriseContext.Provider value={contextValue}>{children}</EnterpriseContext.Provider>;
}
- function enter(agent: Agent) {
- if (!user || !org || !gateway) return;
- const botId = agent.resource_id || agent.template_id;
- localStorage.setItem(CONTEXT_KEY, JSON.stringify({ userId: user.user_id, gatewayId: gateway.jiuwenclaw_id, orgId: org.group_id, botId }));
- setSelectedBot(botId || null);
- setRuntimeScope({
- userId: user.user_id,
- groupId: org.group_id,
- botId,
- gatewayId: gateway.jiuwenclaw_id,
- });
- persistRuntimeScopeUrl(user.user_id, org.group_id, botId, gateway.jiuwenclaw_id);
- setReady(true);
- }
-
- const shell = (content: ReactNode) => <div className="enterprise-entry"><div className="enterprise-entry__glow" /><div className="enterprise-entry__card"><div className="enterprise-entry__brand">JIUWEN<span>CLAW</span></div>{content}{error && <div className="enterprise-entry__error">{error}</div>}</div></div>;
- if (!user) return shell(<form onSubmit={login}><div className="enterprise-entry__eyebrow">ENTERPRISE WORKSPACE</div><h1>欢迎回来</h1><p>使用管理面统一身份中心账号登录,进入你的智能工作空间。</p><input className="enterprise-entry__input" placeholder="用户名" value={username} onChange={e => setUsername(e.target.value)} /><input className="enterprise-entry__input" type="password" placeholder="密码" value={password} onChange={e => setPassword(e.target.value)} /><button className="enterprise-entry__button" disabled={!username || !password}>登录工作空间</button></form>);
- if (!gateway) return shell(<><div className="enterprise-entry__eyebrow">STEP 1 / 3</div><h1>选择组网</h1><p>请选择管理面已授权的组网。</p>{gateways.map(g => <button className="enterprise-entry__option" key={g.jiuwenclaw_id} onClick={() => setGateway(g)}><strong>{g.jiuwenclaw_name}</strong><small>{g.gateway_endpoint || g.jiuwenclaw_id}</small></button>)}</>);
- if (!org) return shell(<><div className="enterprise-entry__eyebrow">STEP 2 / 3</div><h1>选择租户</h1><p>选择你要进入的企业工作空间。</p>{orgs.map(o => <button className="enterprise-entry__option" key={o.group_id} onClick={() => setOrg(o)}><strong>{o.name}</strong><small>{o.group_id}</small></button>)}</>);
- return <>{!ready && shell(<><div className="enterprise-entry__eyebrow">STEP 3 / 3</div><h1>选择 Bot</h1><p>选择一个 Bot 开始工作,之后会自动记住你的选择。</p>{agents.map(a => <button className="enterprise-entry__option" key={a.resource_id || a.template_id} onClick={() => enter(a)}><strong>{a.template_name}</strong><small>{a.resource_id || a.template_id}</small></button>)}{agents.length === 0 && <p>暂无可用 Bot</p>}</>)}</>;
-
+ return (
+ <div className="enterprise-entry">
+ <div className="enterprise-entry__glow" />
+ <div className="enterprise-entry__card">
+ <div className="enterprise-entry__brand">
+ JIUWEN<span>CLAW</span>
+ </div>
+ <div className="enterprise-entry__eyebrow">ENTERPRISE WORKSPACE</div>
+ <h1>请从 Manager Web 进入</h1>
+ <p>企业模式由 Manager Web 统一完成登录及组网、组织和 Bot 选择。</p>
+ </div>
+ </div>
+ );
}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
index 6e18f7442a..63d59a7e88 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
@@ -23,7 +23,8 @@ import MoreDesignIcon from '../../assets/更多.svg?react';
import { webRequest } from '../../services/webClient';
import { useEnterpriseContext } from '../../services/enterpriseContext';
-type MainNavKey = 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';
+type MainNavKey =
+ 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';
interface SessionSidebarProps {
activeNav: MainNavKey;
@@ -44,7 +45,11 @@ interface NavItem {
const teamNavIcon = (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>
- <path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a8.96 8.96 0 01-12 0m12 0a3.75 3.75 0 00-6 0m6 0A8.96 8.96 0 0012 15.75a8.96 8.96 0 00-6 2.97m12 0A9 9 0 1012 21a8.96 8.96 0 006-2.28zM15 9.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M18 18.72a8.96 8.96 0 01-12 0m12 0a3.75 3.75 0 00-6 0m6 0A8.96 8.96 0 0012 15.75a8.96 8.96 0 00-6 2.97m12 0A9 9 0 1012 21a8.96 8.96 0 006-2.28zM15 9.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z"
+ />
</svg>
);
@@ -83,12 +88,7 @@ function AdvancedConfigPanel({
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
- if (
- panelRef.current &&
- !panelRef.current.contains(event.target as Node) &&
- buttonRef.current &&
- !buttonRef.current.contains(event.target as Node)
- ) {
+ if (panelRef.current && !panelRef.current.contains(event.target as Node) && buttonRef.current && !buttonRef.current.contains(event.target as Node)) {
onClose();
}
}
@@ -115,9 +115,7 @@ function AdvancedConfigPanel({
<span className="config-row__label">{t('sessionSidebar.connectionStatus')}</span>
<div className={`connection-status ${isConnected ? 'connection-status--connected' : 'connection-status--disconnected'}`}>
<span className="connection-status__dot" />
- <span className="connection-status__text">
- {isConnected ? t('connection.connected') : t('connection.disconnected')}
- </span>
+ <span className="connection-status__text">{isConnected ? t('connection.connected') : t('connection.disconnected')}</span>
</div>
</div>
@@ -131,21 +129,14 @@ function AdvancedConfigPanel({
<div className="config-row">
<span className="config-row__label">{t('sessionSidebar.language')}</span>
<div className="segmented-control">
- <button
- className={`segmented-control__btn ${isZh ? 'segmented-control__btn--active' : ''}`}
- onClick={() => handleLanguageChange('zh')}
- >
+ <button className={`segmented-control__btn ${isZh ? 'segmented-control__btn--active' : ''}`} onClick={() => handleLanguageChange('zh')}>
中
</button>
- <button
- className={`segmented-control__btn ${!isZh ? 'segmented-control__btn--active' : ''}`}
- onClick={() => handleLanguageChange('en')}
- >
+ <button className={`segmented-control__btn ${!isZh ? 'segmented-control__btn--active' : ''}`} onClick={() => handleLanguageChange('en')}>
En
</button>
</div>
</div>
-
</div>
);
}
@@ -195,13 +186,12 @@ export function SessionSidebar({
};
const getNavItemLabel = (item: NavItem) => t(item.labelKey);
- const visibleMainNavItems = mainNavItems.filter((item) => !hiddenNavItems.includes(item.key));
- const visibleMoreNavItems = moreNavItems.filter((item) => !hiddenNavItems.includes(item.key));
- const isMoreActive = visibleMoreNavItems.some((item) => item.key === activeNav);
+ const visibleMainNavItems = mainNavItems.filter(item => !hiddenNavItems.includes(item.key));
+ const visibleMoreNavItems = moreNavItems.filter(item => !hiddenNavItems.includes(item.key));
+ const isMoreActive = visibleMoreNavItems.some(item => item.key === activeNav);
// 定时任务(cron)是"工作"区内与会话同级的视图,没有独立的导航图标,
// 因此进入定时任务时"工作"导航项也应保持选中态
- const isNavItemActive = (item: NavItem) =>
- activeNav === item.key || (item.key === 'chat' && activeNav === 'cron');
+ const isNavItemActive = (item: NavItem) => activeNav === item.key || (item.key === 'chat' && activeNav === 'cron');
useLayoutEffect(() => {
onMorePanelOpenChange?.(isMoreActive);
@@ -215,10 +205,7 @@ export function SessionSidebar({
</div>
{showNewSession && (
- <button
- className="icon-rail-nav-item"
- onClick={handleNewSession}
- >
+ <button className="icon-rail-nav-item" onClick={handleNewSession}>
<span className="icon-rail-nav-item__icon">
<PlusIcon aria-hidden width="16" height="16" />
</span>
@@ -226,7 +213,7 @@ export function SessionSidebar({
</button>
)}
- {visibleMainNavItems.map((item) => (
+ {visibleMainNavItems.map(item => (
<button
key={item.key}
className={`icon-rail-nav-item${isNavItemActive(item) ? ' icon-rail-nav-item--active' : ''}`}
@@ -254,7 +241,7 @@ export function SessionSidebar({
<div className="icon-rail-more-panel">
<div className="icon-rail-more-panel__title">{t('sessionSidebar.moreSettings')}</div>
<nav className="icon-rail-more-panel__list" aria-label={t('sessionSidebar.moreSettings')}>
- {visibleMoreNavItems.map((item) => (
+ {visibleMoreNavItems.map(item => (
<button
key={item.key}
className={`icon-rail-more-panel__item${activeNav === item.key ? ' icon-rail-more-panel__item--active' : ''}`}
@@ -273,32 +260,60 @@ export function SessionSidebar({
<div className="icon-rail-spacer" />
{enterprise && (
- <button type="button" className={`icon-rail-nav-item${contextOpen ? ' icon-rail-nav-item--active' : ''}`} onClick={() => setContextOpen((open) => !open)} aria-label="用户上下文" title="用户上下文">
+ <button
+ type="button"
+ className={`icon-rail-nav-item${contextOpen ? ' icon-rail-nav-item--active' : ''}`}
+ onClick={() => setContextOpen(open => !open)}
+ aria-label="用户上下文"
+ title="用户上下文"
+ >
<span className="icon-rail-nav-item__icon">{(enterprise.user.display_name || enterprise.user.user_id).slice(0, 1).toUpperCase()}</span>
<span className="icon-rail-nav-item__label">用户</span>
</button>
)}
{enterprise && contextOpen && (
<div className="enterprise-context-popover">
- <div className="enterprise-context-popover__user">{enterprise.user.display_name || enterprise.user.user_id}<small>{enterprise.user.user_id}</small></div>
- <label>租户<select value={enterprise.org.group_id} onChange={(event) => enterprise.onOrgChange(event.target.value)}>{enterprise.orgs.map((item) => <option key={item.group_id} value={item.group_id}>{item.name}</option>)}</select></label>
- <label>组网<select value={enterprise.gateway.jiuwenclaw_id} onChange={(event) => enterprise.onGatewayChange(event.target.value)}>{enterprise.gateways.map((item) => <option key={item.jiuwenclaw_id} value={item.jiuwenclaw_id}>{item.jiuwenclaw_name}</option>)}</select></label>
- <label>Bot<select value={enterprise.selectedBot} onChange={(event) => enterprise.onBotChange(event.target.value)}>{enterprise.agents.map((item) => <option key={item.resource_id || item.template_id} value={item.resource_id || item.template_id}>{item.template_name}</option>)}</select></label>
- <button type="button" className="enterprise-context-popover__logout" onClick={() => {
- localStorage.removeItem('openjiuwen_access_token');
- localStorage.removeItem('openjiuwen_refresh_token');
- localStorage.removeItem('jiuwenclaw:enterprise-context');
- window.location.reload();
- }}>注销登录</button>
+ <div className="enterprise-context-popover__user">
+ {enterprise.user.display_name || enterprise.user.user_id}
+ <small>{enterprise.user.user_id}</small>
+ </div>
+ <label>
+ 组织(group_id)
+ <select value={enterprise.org.group_id} onChange={event => enterprise.onOrgChange(event.target.value)}>
+ {enterprise.orgs.map(item => (
+ <option key={item.group_id} value={item.group_id}>
+ {item.name} · {item.group_id}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label>
+ 组网(gateway_id)
+ <select value={enterprise.gateway.jiuwenclaw_id} onChange={event => enterprise.onGatewayChange(event.target.value)}>
+ {enterprise.gateways.map(item => (
+ <option key={item.jiuwenclaw_id} value={item.jiuwenclaw_id}>
+ {item.jiuwenclaw_name} · {item.jiuwenclaw_id}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label>
+ Agent(bot_id)
+ <select value={enterprise.selectedBot} onChange={event => enterprise.onBotChange(event.target.value)}>
+ {enterprise.agents.map(item => (
+ <option key={item.resource_id || item.template_id} value={item.resource_id || item.template_id}>
+ {item.template_name} · {item.resource_id || item.template_id}
+ </option>
+ ))}
+ </select>
+ </label>
+ <button type="button" className="enterprise-context-popover__logout" onClick={enterprise.onLogout}>
+ 注销登录
+ </button>
</div>
)}
- <button
- ref={settingsRef}
- className="icon-rail-nav-item"
- onClick={toggleAdvancedConfig}
- aria-label={t('sessionSidebar.moreSettings')}
- >
+ <button ref={settingsRef} className="icon-rail-nav-item" onClick={toggleAdvancedConfig} aria-label={t('sessionSidebar.moreSettings')}>
<span className="icon-rail-nav-item__icon">
<AdvancedConfigIcon aria-hidden width="16" height="16" />
</span>
diff --git a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
index c7e708019f..c197a4152c 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
@@ -1,6 +1,6 @@
import { createContext, useContext } from 'react';
-export type EnterpriseContextValue = {
+export type EnterpriseContextSnapshot = {
user: { user_id: string; display_name: string };
org: { group_id: string; name: string };
orgs: { group_id: string; name: string }[];
@@ -8,10 +8,16 @@ export type EnterpriseContextValue = {
gateways: { jiuwenclaw_id: string; jiuwenclaw_name: string; gateway_endpoint: string | null }[];
agents: { template_id: string; template_name: string; resource_id?: string }[];
selectedBot: string;
+};
+
+export type EnterpriseContextValue = EnterpriseContextSnapshot & {
onOrgChange: (id: string) => void;
onGatewayChange: (id: string) => void;
onBotChange: (id: string) => void;
+ onLogout: () => void;
};
export const EnterpriseContext = createContext<EnterpriseContextValue | null>(null);
-export function useEnterpriseContext() { return useContext(EnterpriseContext); }
+export function useEnterpriseContext() {
+ return useContext(EnterpriseContext);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/utils/env.ts b/jiuwenswarm/channels/web/frontend/src/utils/env.ts
index f71d7f245b..c092c33a5f 100644
--- a/jiuwenswarm/channels/web/frontend/src/utils/env.ts
+++ b/jiuwenswarm/channels/web/frontend/src/utils/env.ts
@@ -36,11 +36,11 @@ export function getWebTransport(): WebTransport {
return "websocket";
}
-/** Gateway A2 前缀,默认同源 `/api/v1`。不要和 H1 `/api/sessions` 混用。 */
+/** Gateway A2 前缀,默认同源 `/gateway-api/v1`,避免与 Manager `/api/v1` 冲突。 */
export function getGatewayHttpBase(): string {
const raw = import.meta.env.VITE_GATEWAY_HTTP_BASE ?? import.meta.env.VITE_WEB_HTTP_BASE;
if (!raw) {
- return "/api/v1";
+ return "/gateway-api/v1";
}
const normalized = normalizeBase(raw);
if (normalized.endsWith("/api/v1")) {
diff --git a/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs b/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs
index 9130a8af3a..cb6bd2709e 100644
--- a/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs
@@ -8,10 +8,12 @@ import {
} from '../node_modules/.cache/runtime-scope/services/runtimeScope.js';
test('runtime scope is parsed and added to websocket query', () => {
- const scope = parseRuntimeScope('?user_id=%20u1%20&group_id=g1&bot_id=b1&ignored=x');
- assert.deepEqual(scope, { userId: 'u1', groupId: 'g1', botId: 'b1' });
+ const scope = parseRuntimeScope(
+ '?user_id=%20u1%20&group_id=g1&bot_id=b1&gateway_id=gw1&ignored=x'
+ );
+ assert.deepEqual(scope, { userId: 'u1', groupId: 'g1', botId: 'b1', gatewayId: 'gw1' });
const query = appendRuntimeScopeQuery(new URLSearchParams('provider=p'), scope);
- assert.equal(query.toString(), 'provider=p&user_id=u1&group_id=g1&bot_id=b1');
+ assert.equal(query.toString(), 'provider=p&user_id=u1&group_id=g1&bot_id=b1&gateway_id=gw1');
});
test('runtime scope takes precedence in HTTP identity headers', () => {
@@ -24,13 +26,14 @@ test('runtime scope takes precedence in HTTP identity headers', () => {
bot_id: 'payload-bot',
session_id: 'session-1',
},
- { userId: 'u1', groupId: 'g1', botId: 'b1' }
+ { userId: 'u1', groupId: 'g1', botId: 'b1', gatewayId: 'gw1' }
),
{
'X-Request-Id': 'req-1',
'X-User-Id': 'u1',
'X-Group-Id': 'g1',
'X-Bot-Id': 'b1',
+ 'X-Jiuwenclaw-Id': 'gw1',
'X-Session-Id': 'session-1',
}
);
diff --git a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
new file mode 100644
index 0000000000..a35178d406
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+
+const values = new Map();
+globalThis.localStorage = {
+ getItem(key) {
+ return values.get(key) ?? null;
+ },
+ removeItem(key) {
+ values.delete(key);
+ },
+ setItem(key, value) {
+ values.set(key, String(value));
+ },
+};
+globalThis.window = {
+ __JIUWEN_USER_WEB_MODE__: 'personal',
+ history: { replaceState() {} },
+ location: { pathname: '/', search: '' },
+};
+
+const { EnterpriseEntry } = await import('../node_modules/.cache/user-web-entry/EnterpriseEntry.mjs');
+
+function renderEntry(mode) {
+ window.__JIUWEN_USER_WEB_MODE__ = mode;
+ return renderToStaticMarkup(React.createElement(EnterpriseEntry, null, React.createElement('div', { id: 'personal-content' }, 'personal content')));
+}
+
+function resetBrowserState() {
+ values.clear();
+ window.location.search = '';
+}
+
+test('personal mode renders the standalone User Web without enterprise authentication', () => {
+ resetBrowserState();
+ const html = renderEntry('personal');
+
+ assert.match(html, /personal content/);
+ assert.doesNotMatch(html, /ENTERPRISE WORKSPACE|请从 Manager Web 进入/);
+});
+
+test('enterprise mode rejects direct access without Manager Web context', () => {
+ resetBrowserState();
+ const html = renderEntry('enterprise');
+
+ assert.match(html, /ENTERPRISE WORKSPACE/);
+ assert.match(html, /请从 Manager Web 进入/);
+ assert.doesNotMatch(html, /personal content/);
+ assert.doesNotMatch(html, /用户名|密码|登录工作空间/);
+});
+
+test('enterprise mode renders the embedded User Web with Manager authentication and scope', () => {
+ resetBrowserState();
+ localStorage.setItem('openjiuwen_access_token', 'manager-token');
+ window.location.search = '?user_id=user-1&group_id=group-1&bot_id=bot-1&gateway_id=gateway-1';
+
+ const html = renderEntry('enterprise');
+
+ assert.match(html, /personal content/);
+ assert.doesNotMatch(html, /请从 Manager Web 进入/);
+});
diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.ts
index 85c113369d..6731f5244c 100644
--- a/jiuwenswarm/channels/web/frontend/vite.config.ts
+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts
@@ -331,8 +331,7 @@ const webHttpTarget =
`http://127.0.0.1:${webHttpPort}`
export default defineConfig({
- // 产物会被 Manager Web 挂载在 /chat/ iframe 中;使用相对资源路径,
- // 避免 iframe 的 JS/CSS 请求回到 Manager 根路径。
+ // 相对资源路径同时支持独立根路径与 Manager Web 的 /chat/ 同源转发。
base: './',
plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), react(), svgr()],
optimizeDeps: {
@@ -362,6 +361,11 @@ export default defineConfig({
target: webHttpTarget,
changeOrigin: true,
},
+ '/gateway-api': {
+ target: webHttpTarget,
+ changeOrigin: true,
+ rewrite: (requestPath) => requestPath.replace(/^\/gateway-api/, '/api'),
+ },
'/api/sessions': {
target: webHttpTarget,
changeOrigin: true,
diff --git a/tests/unit_tests/test_app_web_gateway_api_proxy.py b/tests/unit_tests/test_app_web_gateway_api_proxy.py
new file mode 100644
index 0000000000..7933443558
--- /dev/null
+++ b/tests/unit_tests/test_app_web_gateway_api_proxy.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.channels.web.app_web import (
+ _SpaStaticHandler,
+ _inject_user_web_runtime_config,
+)
+
+
+def _handler(path: str) -> _SpaStaticHandler:
+ handler = object.__new__(_SpaStaticHandler)
+ handler.path = path
+ handler.web_http_target = "http://gateway:19002"
+ return handler
+
+
+def test_gateway_api_is_classified_as_gateway_web_http_route() -> None:
+ assert _handler("/gateway-api/v1/chat/completions")._is_web_http_route()
+
+
+def test_gateway_api_prefix_is_rewritten_for_upstream(monkeypatch) -> None:
+ handler = _handler("/gateway-api/v1/chat/completions?mode=work")
+ captured: dict[str, str] = {}
+
+ def proxy_http() -> None:
+ captured["path"] = handler.path
+ captured["target"] = handler.api_target
+
+ monkeypatch.setattr(handler, "_proxy_http", proxy_http)
+ handler._proxy_web_http()
+
+ assert captured == {
+ "path": "/api/v1/chat/completions?mode=work",
+ "target": "http://gateway:19002",
+ }
+ assert handler.path == "/gateway-api/v1/chat/completions?mode=work"
+
+
+ ("mode", "embedding"),
+ [("personal", "false"), ("enterprise", "true")],
+)
+def test_user_web_runtime_mode_injection_preserves_property_names(
+ mode: str,
+ embedding: str,
+) -> None:
+ frontend_index = (
+ Path(__file__).resolve().parents[2]
+ / "jiuwenswarm"
+ / "channels"
+ / "web"
+ / "frontend"
+ / "index.html"
+ ).read_text(encoding="utf-8")
+
+ rendered = _inject_user_web_runtime_config(frontend_index, mode)
+
+ assert f"window.__JIUWEN_USER_WEB_MODE__ = '{mode}'" in rendered
+ assert "window.__JIUWEN_USER_WEB_EMBEDDING__" in rendered
+ assert f"'{embedding}' === 'true'" in rendered
+ assert "__JIUWEN_USER_WEB_MODE_VALUE__" not in rendered
+ assert "__JIUWEN_USER_WEB_EMBEDDING_VALUE__" not in rendered