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:用户web支持多集群切换
programmegirlc78d3cd1cdc6
diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.shindex e93c3c25b4..13214bf20e 100755--- a/deploy/enterprise/global_vars.sh+++ b/deploy/enterprise/global_vars.sh@@ -174,6 +174,8 @@ declare -A DEPLOY_VARS=(["MANAGER_SERVER_REPLICAS"]="1"["MANAGER_WEB_NAME"]="jiuwenclaw-manager-web"["MANAGER_WEB_PORT"]="5273"+ # nginx 动态上游 DNS;多数集群为 kube-dns / CoreDNS 此 Service 名+ ["MANAGER_WEB_RESOLVER"]="kube-dns.kube-system.svc.cluster.local"["MANAGER_WS_PORT"]="8766"["MINIO_IMAGE"]="minio/minio-arm64:RELEASE.2024-12-18T13-15-44Z"["MINIO_NAME"]="minio"diff --git a/deploy/enterprise/template_handler.sh b/deploy/enterprise/template_handler.shindex 7a8af07e6c..ed8929490a 100755--- a/deploy/enterprise/template_handler.sh+++ b/deploy/enterprise/template_handler.sh@@ -61,9 +61,11 @@ render_config_template(){}# Append a single hostPath code mount (volume + volumeMount) to the first-# container of every Deployment in <file>.+# container of every Deployment in <file>.+# 第 5 个参数可选:hostPath.type,默认 Directory;单文件用 File。add_code_mount() {local file="$1" name="$2" host_path="$3" mount_path="$4"+ local host_type="${5:-Directory}"yq eval 'select(.kind == "Deployment").spec.template.spec.containers[0].volumeMounts|= ((. // []) + [{@@ -77,7 +79,7 @@ add_code_mount() {"name": "'"${name}"'","hostPath": {"path": "'"${host_path}"'",- "type": "Directory"+ "type": "'"${host_type}"'"}}])' -i "${file}"@@ -97,6 +99,15 @@ mount_runtime_code() {"${DEPLOY_VARS["RUNTIME_POD_CODE_PATH"]}"}+# manager-web:把仓库 nginx 模板盖到镜像内 entrypoint 读取的路径。+mount_manager_web_nginx_template() {+ [ -z "${DEPLOY_VARS["RUNTIME_CODE_PATH"]:-}" ] && return+ add_code_mount "$1" "manager-web-nginx-template" \+ "${DEPLOY_VARS["RUNTIME_CODE_PATH"]}/docker/manager-web.nginx.conf.template" \+ "/etc/nginx/templates/default.conf.template" \+ "File"+}+mount_runtime_pkg() {[ -z "${DEPLOY_VARS["RUNTIME_CODE_PATH"]:-}" ] && returnlocal file="$1"@@ -135,6 +146,7 @@ enable_dev_mode_if_needed() {manager-web)[ "${DEPLOY_VARS["IS_MOUNT_MANAGER_WEB_CODE"]}" != "true" ] && returnmount_runtime_code "${file}"+ mount_manager_web_nginx_template "${file}";;*)warning "enable_dev_mode_if_needed: unknown component '${comp}', skipping"diff --git a/deploy/enterprise/templates/manager-server.template.yaml b/deploy/enterprise/templates/manager-server.template.yamlindex fb4b9bb19c..8658b030fe 100644--- a/deploy/enterprise/templates/manager-server.template.yaml+++ b/deploy/enterprise/templates/manager-server.template.yaml@@ -81,8 +81,15 @@ 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>>"+ # nginx 变量 proxy_pass 需 FQDN;短名作回退时由 Manager 扩成 *.svc.cluster.local+ - name: MANAGER_WEB_USER_WEB_TARGET+ value: "http://<<WEB_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<WEB_HTTP_PORT>>"+ - name: MANAGER_WEB_GATEWAY_HTTP_TARGET+ value: "http://<<GATEWAY_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<GATEWAY_WEB_HTTP_PORT>>"+ - name: MANAGER_WEB_GATEWAY_WS_TARGET+ value: "http://<<GATEWAY_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<WEB_PORT>>"+ - name: NAMESPACE+ value: "<<NAMESPACE>>"- name: AGENT_RUNTIME_SYNC_TIMEOUTvalue: "<<AGENT_RUNTIME_SYNC_TIMEOUT>>"- name: MANAGER_WS_ENABLEDdiff --git a/deploy/enterprise/templates/manager-web.template.yaml b/deploy/enterprise/templates/manager-web.template.yamlindex bfe318b645..523869fcd8 100644--- a/deploy/enterprise/templates/manager-web.template.yaml+++ b/deploy/enterprise/templates/manager-web.template.yaml@@ -31,15 +31,18 @@ spec:- name: MANAGER_WEB_PORTvalue: "<<MANAGER_WEB_PORT>>"- name: MANAGER_WEB_PROXY_TARGET- value: "http://<<MANAGER_SERVER_NAME>>:<<MANAGER_REST_PORT>>"+ value: "http://<<MANAGER_SERVER_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<MANAGER_REST_PORT>>"- name: MANAGER_WEB_IDP_TARGET- value: "http://<<IDENTITY_NAME>>:<<IDENTITY_REST_PORT>>"+ value: "http://<<IDENTITY_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<IDENTITY_REST_PORT>>"- name: MANAGER_WEB_USER_WEB_TARGET- value: "http://<<WEB_NAME>>:<<WEB_HTTP_PORT>>"+ value: "http://<<WEB_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<WEB_HTTP_PORT>>"- name: MANAGER_WEB_GATEWAY_HTTP_TARGET- value: "http://<<GATEWAY_NAME>>:<<GATEWAY_WEB_HTTP_PORT>>"+ value: "http://<<GATEWAY_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<GATEWAY_WEB_HTTP_PORT>>"- name: MANAGER_WEB_GATEWAY_WS_TARGET- value: "http://<<GATEWAY_NAME>>:<<WEB_PORT>>"+ value: "http://<<GATEWAY_NAME>>.<<NAMESPACE>>.svc.cluster.local:<<WEB_PORT>>"+ # nginx 变量 proxy_pass 需要 resolver;K8s 默认指向集群 DNS+ - name: MANAGER_WEB_RESOLVER+ value: "<<MANAGER_WEB_RESOLVER>>"- name: TZvalue: "<<TIMEZONE>>"diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsxindex 948ef9c819..9c4519cfe9 100644--- a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx@@ -52,27 +52,77 @@ function entryPath(): string {return pathname.startsWith('/chat') ? '/chat/' : '/';}-function contextUrl(selected: EnterpriseAgentContext, debugContext = false): string {+const ACTIVE_CLUSTER_STORAGE_KEY = 'jiuwenclaw_active_cluster';++function readKnownCluster(): string {+ try {+ return sessionStorage.getItem(ACTIVE_CLUSTER_STORAGE_KEY) || '';+ } catch {+ return '';+ }+}++function writeKnownCluster(jiuwenclawId: string): void {+ try {+ sessionStorage.setItem(ACTIVE_CLUSTER_STORAGE_KEY, jiuwenclawId);+ } catch {+ // 隐私模式等场景写失败时,仍以本次内存比较为准+ }+}++function contextUrl(+ selected: EnterpriseAgentContext,+ debugContext = false,+ resetPath = false,+): string {const query = new URLSearchParams({user_id: selected.user_id,group_id: selected.group_id,bot_id: selected.bot_id,});if (debugContext) query.set('debug_context', '1');- return `${entryPath()}?${query.toString()}`;+ const path = resetPath+ ? window.location.pathname.startsWith('/chat')+ ? '/chat/'+ : '/'+ : entryPath();+ return `${path}?${query.toString()}`;}-function activateContext(selected: EnterpriseAgentContext, navigate: boolean, debugContext = false): void {+function activateContext(+ selected: EnterpriseAgentContext,+ navigate: boolean,+ debugContext = false,+ resetPath = false,+): void {setRuntimeScope({userId: selected.user_id,groupId: selected.group_id,botId: selected.bot_id,});- const nextUrl = contextUrl(selected, debugContext);+ const nextUrl = contextUrl(selected, debugContext, resetPath);if (navigate) window.location.replace(nextUrl);else window.history.replaceState({}, '', nextUrl);}+/**+ * 写入 active-cluster Cookie。+ * Cookie 为 HttpOnly,前端读不到,用 sessionStorage 记录上次目标,避免每次启动都整页刷新。+ * 返回 true 表示相对上次已知实例发生了切换(需要 reload 让 nginx 改上游)。+ */+async function ensureActiveCluster(+ provider: NonNullable<ReturnType<typeof resolveEnterpriseAuthProvider>>,+ jiuwenclawId: string,+): Promise<boolean> {+ const next = jiuwenclawId.trim();+ if (!next || !provider.setActiveCluster) return false;+ const prev = readKnownCluster();+ if (prev === next) return false;+ await provider.setActiveCluster(next);+ writeKnownCluster(next);+ return Boolean(prev);+}+export function isDebugContext(search: string): boolean {return new URLSearchParams(search).get('debug_context') === '1';}@@ -208,6 +258,15 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {setPhase('empty');return;}+ const clusterChanged = await ensureActiveCluster(provider, selected.jiuwenclaw_id);+ if (cancelled) return;+ if (clusterChanged) {+ // Cookie 已指向新实例,整页刷新让 nginx 改打 /chat、/gateway-api+ window.location.replace(+ contextUrl(selected, isDebugContext(window.location.search), true),+ );+ return;+ }activateContext(selected, false, isDebugContext(window.location.search));setContext({ user, contexts, selected });setPhase('ready');@@ -234,7 +293,7 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {contextError,contextSwitching,onContextChange: key => {- if (contextSwitching) return;+ if (contextSwitching || !provider) return;const selected = context.contexts.find(item => agentContextKey(item) === key);if (!selected) return;// 自定义(debug_context)下即使三元组碰巧与某授权项相同,点选列表项也要退出自定义。@@ -242,7 +301,15 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {if (sameIdentity && !isDebugContext(window.location.search)) return;setContextSwitching(true);setContextError('');- activateContext(selected, true, false);+ void (async () => {+ try {+ const clusterChanged = await ensureActiveCluster(provider, selected.jiuwenclaw_id);+ activateContext(selected, true, false, clusterChanged);+ } catch (switchError) {+ setContextSwitching(false);+ setContextError(errorText(switchError));+ }+ })();},onCustomContextApply: input => {if (contextSwitching) return;@@ -270,7 +337,7 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {},onLogout: logout,};- }, [context, contextError, contextSwitching, logout, t]);+ }, [context, contextError, contextSwitching, logout, provider, t]);if (!enterprise) return <>{children}</>;if (phase !== 'ready' || !contextValue) return <EntryStatus phase={phase} error={error} onLogout={logout} />;diff --git a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.tsindex c515a0e139..d3c305d4af 100644--- a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts+++ b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts@@ -23,10 +23,10 @@ function requestMessage(body: unknown, fallback: string): string {return fallback;}-async function requestJson<T>(path: string): Promise<T> {+async function requestJson<T>(path: string, init: RequestInit = {}): Promise<T> {let response: Response;try {- response = await managerAuthenticatedFetch(path);+ response = await managerAuthenticatedFetch(path, init);} catch (error) {throw new EnterpriseAuthError(0, `网络请求失败:${error instanceof Error ? error.message : String(error)}`);}@@ -55,6 +55,19 @@ export const managerAuthProvider: EnterpriseAuthProvider = {if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载 Agent 上下文失败');return result.data?.contexts ?? [];},+ async setActiveCluster(jiuwenclawId: string) {+ const result = await requestJson<ManagerResponse<{ jiuwenclaw_id: string }>>(+ '/manager-api/v1/user-console/active-cluster',+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ jiuwenclaw_id: jiuwenclawId }),+ },+ );+ if (result.code !== 200) {+ throw new EnterpriseAuthError(result.code, result.message || '切换集群失败');+ }+ },async logout() {const refreshToken = getManagerRefreshToken();if (refreshToken) {diff --git a/jiuwenswarm/channels/web/frontend/src/auth/types.ts b/jiuwenswarm/channels/web/frontend/src/auth/types.tsindex 33b89f9540..4765abeaba 100644--- a/jiuwenswarm/channels/web/frontend/src/auth/types.ts+++ b/jiuwenswarm/channels/web/frontend/src/auth/types.ts@@ -8,6 +8,8 @@ export interface EnterpriseAuthProvider {redirectToLogin(): boolean;getCurrentUser(): Promise<EnterpriseUser>;listAgentContexts(): Promise<EnterpriseAgentContext[]>;+ /** 写入 Manager 用户面反代 Cookie ``jiuwenclaw_id``;模拟登录可省略。 */+ setActiveCluster?(jiuwenclawId: string): Promise<void>;logout(): Promise<void>;}