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:用户面user_id/group_id/bot_id设置优化

programmegirle80d94aeb921
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.py
index f9fbaca8e6..9f9706d455 100644
--- a/jiuwenswarm/channels/web/app_web.py
+++ b/jiuwenswarm/channels/web/app_web.py
@@ -139,7 +139,7 @@ def _probe_identity_service(target: str, timeout: float = 3.0) -> tuple[bool, st
def _probe_manager_service(target: str, timeout: float = 3.0) -> tuple[bool, str]:
return _probe_http_service(
- target, "/api/v1/user-console/gateways", "Manager业务接口", timeout
+ target, "/api/v1/user-console/agent-contexts", "Manager业务接口", timeout
)
diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
index e86a12cd58..948ef9c819 100644
--- a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
@@ -1,78 +1,46 @@
import { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
import { isLoginAuthSimulateEnabled } from './auth/config';
import { resolveEnterpriseAuthProvider } from './auth/providerRegistry';
-import { EnterpriseAuthError, type EnterpriseAuthProvider } from './auth/types';
+import { EnterpriseAuthError } from './auth/types';
import { isEnterprise } from './edition';
import {
+ agentContextKey,
EnterpriseContext,
- type EnterpriseAgent,
+ type EnterpriseAgentContext,
type EnterpriseContextSnapshot,
type EnterpriseContextValue,
- type EnterpriseGateway,
- type EnterpriseOrg,
} from './services/enterpriseContext';
import { parseRuntimeScope, setRuntimeScope } from './services/runtimeScope';
type EntryPhase = 'loading' | 'ready' | 'empty' | 'error' | 'redirecting' | 'login-required';
-interface ContextCandidate {
- gateway: EnterpriseGateway;
- org: EnterpriseOrg;
-}
-
-interface ResolvedContext extends ContextCandidate {
- agents: EnterpriseAgent[];
- selectedBot: string;
-}
-
-function agentRuntimeId(agent: EnterpriseAgent): string {
- return agent.resource_id || agent.template_id;
-}
-
-function movePreferredFirst<T>(items: T[], matches: (item: T) => boolean): T[] {
- const preferredIndex = items.findIndex(matches);
+function movePreferredFirst(items: EnterpriseAgentContext[], preferredKey?: string): EnterpriseAgentContext[] {
+ if (!preferredKey) return items;
+ const preferredIndex = items.findIndex(item => agentContextKey(item) === preferredKey);
if (preferredIndex <= 0) return items;
return [items[preferredIndex], ...items.slice(0, preferredIndex), ...items.slice(preferredIndex + 1)];
}
-/**
- * Build a deterministic list of authorized gateway/organization combinations.
- * URL values only affect ordering; every selected combination is still checked
- * against the server before it becomes active.
- */
-export function orderedContextCandidates(
- gateways: EnterpriseGateway[],
- orgs: EnterpriseOrg[],
- preferredGatewayId?: string,
- preferredOrgId?: string,
-): ContextCandidate[] {
- const orderedGateways = movePreferredFirst([...gateways], item => item.jiuwenclaw_id === preferredGatewayId);
- const orderedOrgs = movePreferredFirst([...orgs], item => item.group_id === preferredOrgId);
- return orderedGateways.flatMap(gateway => orderedOrgs.map(org => ({ gateway, org })));
-}
-
-export function chooseAgent(agents: EnterpriseAgent[], preferredBotId?: string): EnterpriseAgent | null {
- return agents.find(agent => agentRuntimeId(agent) === preferredBotId) ?? agents[0] ?? null;
-}
-
-async function resolveFirstContext(
- provider: EnterpriseAuthProvider,
- candidates: ContextCandidate[],
- preferredBotId?: string,
-): Promise<ResolvedContext | null> {
- let firstError: unknown = null;
- for (const candidate of candidates) {
- try {
- const agents = await provider.listAgents(candidate.org.group_id, candidate.gateway.jiuwenclaw_id);
- const selected = chooseAgent(agents, preferredBotId);
- if (selected) return { ...candidate, agents, selectedBot: agentRuntimeId(selected) };
- } catch (error) {
- if (error instanceof EnterpriseAuthError && error.status === 401) throw error;
- firstError ??= error;
- }
+export function chooseAgentContext(
+ contexts: EnterpriseAgentContext[],
+ preferred?: { botId?: string; groupId?: string; userId?: string },
+): EnterpriseAgentContext | null {
+ if (!contexts.length) return null;
+ if (preferred?.botId && preferred.groupId && preferred.userId) {
+ const exact = contexts.find(
+ item =>
+ item.bot_id === preferred.botId &&
+ item.group_id === preferred.groupId &&
+ item.user_id === preferred.userId,
+ );
+ if (exact) return exact;
}
- if (firstError) throw firstError;
- return null;
+ if (preferred?.botId) {
+ const byBot = contexts.find(item => item.bot_id === preferred.botId);
+ if (byBot) return byBot;
+ }
+ return contexts[0] ?? null;
}
function entryPath(): string {
@@ -84,25 +52,23 @@ function entryPath(): string {
return pathname.startsWith('/chat') ? '/chat/' : '/';
}
-function contextUrl(userId: string, resolved: ResolvedContext, debugContext = false): string {
+function contextUrl(selected: EnterpriseAgentContext, debugContext = false): string {
const query = new URLSearchParams({
- user_id: userId,
- group_id: resolved.org.group_id,
- bot_id: resolved.selectedBot,
- gateway_id: resolved.gateway.jiuwenclaw_id,
+ 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()}`;
}
-function activateContext(userId: string, resolved: ResolvedContext, navigate: boolean, debugContext = false): void {
+function activateContext(selected: EnterpriseAgentContext, navigate: boolean, debugContext = false): void {
setRuntimeScope({
- userId,
- groupId: resolved.org.group_id,
- botId: resolved.selectedBot,
- gatewayId: resolved.gateway.jiuwenclaw_id,
+ userId: selected.user_id,
+ groupId: selected.group_id,
+ botId: selected.bot_id,
});
- const nextUrl = contextUrl(userId, resolved, debugContext);
+ const nextUrl = contextUrl(selected, debugContext);
if (navigate) window.location.replace(nextUrl);
else window.history.replaceState({}, '', nextUrl);
}
@@ -111,40 +77,19 @@ export function isDebugContext(search: string): boolean {
return new URLSearchParams(search).get('debug_context') === '1';
}
-export function buildRequestedDebugContext(
- orgs: EnterpriseOrg[],
- gateways: EnterpriseGateway[],
- agents: EnterpriseAgent[],
+export function buildCustomContext(
preferred: ReturnType<typeof parseRuntimeScope>,
-): ResolvedContext | null {
- if (!preferred.groupId || !preferred.gatewayId || !preferred.botId) return null;
- const org = orgs.find(item => item.group_id === preferred.groupId) ?? {
+ fallbackGatewayId = '',
+): EnterpriseAgentContext | null {
+ if (!preferred.groupId || !preferred.botId || !preferred.userId) return null;
+ return {
+ bot_id: preferred.botId,
group_id: preferred.groupId,
- name: preferred.groupId,
- };
- const gateway = gateways.find(item => item.jiuwenclaw_id === preferred.gatewayId) ?? {
- jiuwenclaw_id: preferred.gatewayId,
- jiuwenclaw_name: preferred.gatewayId,
- gateway_endpoint: null,
+ user_id: preferred.userId,
+ jiuwenclaw_id: fallbackGatewayId,
+ agent_name: preferred.botId,
+ group_name: preferred.groupId,
};
- return { org, gateway, agents, selectedBot: preferred.botId };
-}
-
-async function resolveRequestedDebugContext(
- provider: EnterpriseAuthProvider,
- orgs: EnterpriseOrg[],
- gateways: EnterpriseGateway[],
- preferred: ReturnType<typeof parseRuntimeScope>,
-): Promise<ResolvedContext | null> {
- if (!preferred.groupId || !preferred.gatewayId || !preferred.botId) return null;
- let agents: EnterpriseAgent[] = [];
- try {
- agents = await provider.listAgents(preferred.groupId, preferred.gatewayId);
- } catch (error) {
- if (error instanceof EnterpriseAuthError && error.status === 401) throw error;
- // 自定义 ID 用于联调错误路由;列表查询失败不能覆盖手工输入的上下文。
- }
- return buildRequestedDebugContext(orgs, gateways, agents, preferred);
}
function errorText(error: unknown): string {
@@ -176,7 +121,7 @@ function EntryStatus({ phase, error, onLogout }: { phase: EntryPhase; error: str
</h1>
<p>
{empty
- ? '当前账号没有可用的组织、组网和 Agent 组合,请联系管理员完成授权。'
+ ? '当前账号没有可用的 Agent 上下文组合,请联系管理员完成授权。'
: failed
? error
: loginRequired
@@ -194,6 +139,7 @@ function EntryStatus({ phase, error, onLogout }: { phase: EntryPhase; error: str
}
export function EnterpriseEntry({ children }: { children: ReactNode }) {
+ const { t } = useTranslation();
const enterprise = isEnterprise();
const simulateLogin = enterprise && isLoginAuthSimulateEnabled();
const provider = useMemo(
@@ -222,33 +168,48 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
const bootstrap = async () => {
try {
const preferred = parseRuntimeScope(window.location.search);
- const [user, orgs, gateways] = await Promise.all([
- provider.getCurrentUser(),
- provider.listOrganizations(),
- provider.listGateways(),
- ]);
- const resolved = isDebugContext(window.location.search)
- ? await resolveRequestedDebugContext(provider, orgs, gateways, preferred)
- : await resolveFirstContext(
- provider,
- orderedContextCandidates(gateways, orgs, preferred.gatewayId, preferred.groupId),
- preferred.botId,
- );
+ const [user, contexts] = await Promise.all([provider.getCurrentUser(), provider.listAgentContexts()]);
if (cancelled) return;
- if (!resolved) {
+
+ let selected: EnterpriseAgentContext | null = null;
+ if (isDebugContext(window.location.search)) {
+ const matched = preferred.botId
+ ? contexts.find(item => item.bot_id === preferred.botId)
+ : undefined;
+ // 旧版 debug URL 可省略 user_id(默认取登录用户),与 chooseAgentContext 对齐。
+ selected = buildCustomContext(
+ {
+ ...preferred,
+ userId: preferred.userId || user.user_id,
+ },
+ matched?.jiuwenclaw_id || contexts[0]?.jiuwenclaw_id || '',
+ );
+ }
+ if (!selected) {
+ selected = chooseAgentContext(
+ movePreferredFirst(
+ contexts,
+ preferred.botId && preferred.groupId && preferred.userId
+ ? agentContextKey({
+ bot_id: preferred.botId,
+ group_id: preferred.groupId,
+ user_id: preferred.userId,
+ })
+ : undefined,
+ ),
+ {
+ botId: preferred.botId,
+ groupId: preferred.groupId,
+ userId: preferred.userId || user.user_id,
+ },
+ );
+ }
+ if (!selected) {
setPhase('empty');
return;
}
- activateContext(user.user_id, resolved, false);
- setContext({
- user,
- org: resolved.org,
- orgs,
- gateway: resolved.gateway,
- gateways,
- agents: resolved.agents,
- selectedBot: resolved.selectedBot,
- });
+ activateContext(selected, false, isDebugContext(window.location.search));
+ setContext({ user, contexts, selected });
setPhase('ready');
} catch (bootstrapError) {
if (cancelled) return;
@@ -266,117 +227,50 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
};
}, [enterprise, provider]);
- const switchContext = useCallback(
- async (candidates: ContextCandidate[], preferredBotId?: string, missingMessage = '所选范围内暂无可用 Agent') => {
- if (!context || contextSwitching || !provider) return;
- setContextSwitching(true);
- setContextError('');
- try {
- const resolved = await resolveFirstContext(provider, candidates, preferredBotId);
- if (!resolved) {
- setContextError(missingMessage);
- return;
- }
- activateContext(context.user.user_id, resolved, true);
- } catch (switchError) {
- if (switchError instanceof EnterpriseAuthError && switchError.status === 401) {
- if (!provider.redirectToLogin()) setPhase('login-required');
- return;
- }
- setContextError(errorText(switchError));
- } finally {
- setContextSwitching(false);
- }
- },
- [context, contextSwitching, provider],
- );
-
const contextValue = useMemo<EnterpriseContextValue | null>(() => {
if (!context) return null;
return {
...context,
contextError,
contextSwitching,
- onOrgChange: orgId => {
- const org = context.orgs.find(item => item.group_id === orgId);
- if (!org) {
- const normalized = orgId.trim();
- if (!normalized) return;
- activateContext(
- context.user.user_id,
- { ...context, org: { group_id: normalized, name: normalized } },
- true,
- true,
- );
- return;
- }
- const gateways = movePreferredFirst([...context.gateways], item => item.jiuwenclaw_id === context.gateway.jiuwenclaw_id);
- void switchContext(
- gateways.map(gateway => ({ gateway, org })),
- undefined,
- '该组织暂无可用 Agent',
- );
+ onContextChange: key => {
+ if (contextSwitching) return;
+ const selected = context.contexts.find(item => agentContextKey(item) === key);
+ if (!selected) return;
+ // 自定义(debug_context)下即使三元组碰巧与某授权项相同,点选列表项也要退出自定义。
+ const sameIdentity = agentContextKey(selected) === agentContextKey(context.selected);
+ if (sameIdentity && !isDebugContext(window.location.search)) return;
+ setContextSwitching(true);
+ setContextError('');
+ activateContext(selected, true, false);
},
- onGatewayChange: gatewayId => {
- const gateway = context.gateways.find(item => item.jiuwenclaw_id === gatewayId);
- if (!gateway) {
- const normalized = gatewayId.trim();
- if (!normalized) return;
- activateContext(
- context.user.user_id,
- {
- ...context,
- gateway: {
- jiuwenclaw_id: normalized,
- jiuwenclaw_name: normalized,
- gateway_endpoint: null,
- },
- },
- true,
- true,
- );
- return;
- }
- const orgs = movePreferredFirst([...context.orgs], item => item.group_id === context.org.group_id);
- void switchContext(
- orgs.map(org => ({ gateway, org })),
- undefined,
- '该组网暂无可用 Agent',
- );
- },
- onBotChange: botId => {
- const selected = context.agents.find(agent => agentRuntimeId(agent) === botId);
- if (botId === context.selectedBot) return;
- if (!selected) {
- const normalized = botId.trim();
- if (!normalized) return;
- activateContext(
- context.user.user_id,
- {
- gateway: context.gateway,
- org: context.org,
- agents: context.agents,
- selectedBot: normalized,
- },
- true,
- true,
- );
+ onCustomContextApply: input => {
+ if (contextSwitching) return;
+ const botId = input.botId.trim();
+ const groupId = input.groupId.trim();
+ const userId = input.userId.trim();
+ if (!botId || !groupId || !userId) {
+ setContextError(t('sessionSidebar.enterpriseContext.customRequired'));
return;
}
+ setContextSwitching(true);
+ setContextError('');
activateContext(
- context.user.user_id,
{
- gateway: context.gateway,
- org: context.org,
- agents: context.agents,
- selectedBot: botId,
+ bot_id: botId,
+ group_id: groupId,
+ user_id: userId,
+ jiuwenclaw_id: context.selected.jiuwenclaw_id,
+ agent_name: botId,
+ group_name: groupId,
},
true,
+ true,
);
},
onLogout: logout,
};
- }, [context, contextError, contextSwitching, logout, switchContext]);
+ }, [context, contextError, contextSwitching, logout, 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.ts
index 9c0c0b9e64..c515a0e139 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
@@ -1,9 +1,4 @@
-import type {
- EnterpriseAgent,
- EnterpriseGateway,
- EnterpriseOrg,
- EnterpriseUser,
-} from '../../services/enterpriseContext';
+import type { EnterpriseAgentContext, EnterpriseUser } from '../../services/enterpriseContext';
import { EnterpriseAuthError, type EnterpriseAuthProvider } from '../types';
import {
clearManagerTokens,
@@ -53,20 +48,12 @@ export const managerAuthProvider: EnterpriseAuthProvider = {
return redirectToManagerLogin();
},
getCurrentUser: () => requestJson<EnterpriseUser>('/idp/v1/auth/me'),
- async listOrganizations() {
- const result = await requestJson<{ orgs: EnterpriseOrg[] }>('/idp/v1/auth/me/orgs');
- return result.orgs ?? [];
- },
- async listGateways() {
- const result = await requestJson<ManagerResponse<{ gateways: EnterpriseGateway[] }>>('/manager-api/v1/user-console/gateways');
- if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载组网失败');
- return result.data?.gateways ?? [];
- },
- async listAgents(groupId, gatewayId) {
- const query = new URLSearchParams({ group_id: groupId, jiuwenclaw_id: gatewayId });
- const result = await requestJson<ManagerResponse<{ agents: EnterpriseAgent[] }>>(`/manager-api/v1/user-console/agents?${query.toString()}`);
- if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载 Agent 失败');
- return result.data?.agents ?? [];
+ async listAgentContexts() {
+ const result = await requestJson<ManagerResponse<{ contexts: EnterpriseAgentContext[] }>>(
+ '/manager-api/v1/user-console/agent-contexts',
+ );
+ if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载 Agent 上下文失败');
+ return result.data?.contexts ?? [];
},
async logout() {
const refreshToken = getManagerRefreshToken();
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
index ef65d50cff..189ddd2736 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
@@ -1,4 +1,7 @@
-import type { EnterpriseContextSnapshot } from '../../services/enterpriseContext';
+import {
+ type EnterpriseAgentContext,
+ type EnterpriseContextSnapshot,
+} from '../../services/enterpriseContext';
import { parseRuntimeScope } from '../../services/runtimeScope';
import type { EnterpriseAuthProvider } from '../types';
@@ -8,26 +11,31 @@ const DEFAULTS = {
groupId: 'default',
groupName: 'Debug Organization',
gatewayId: 'debug-gateway',
- gatewayName: 'Debug Gateway',
botId: 'default',
- botName: 'Debug Agent',
+ agentName: 'Debug Agent',
} as const;
-export function buildSimulatedEnterpriseContext(search = ''): EnterpriseContextSnapshot {
+function buildContext(search = ''): EnterpriseAgentContext {
const preferred = parseRuntimeScope(search);
- const user = { user_id: preferred.userId || DEFAULTS.userId, display_name: DEFAULTS.displayName };
- const org = { group_id: preferred.groupId || DEFAULTS.groupId, name: DEFAULTS.groupName };
- const gateway = {
- jiuwenclaw_id: preferred.gatewayId || DEFAULTS.gatewayId,
- jiuwenclaw_name: DEFAULTS.gatewayName,
- gateway_endpoint: null,
+ const botId = preferred.botId || DEFAULTS.botId;
+ const groupId = preferred.groupId || DEFAULTS.groupId;
+ return {
+ bot_id: botId,
+ group_id: groupId,
+ user_id: preferred.userId || DEFAULTS.userId,
+ jiuwenclaw_id: DEFAULTS.gatewayId,
+ agent_name: DEFAULTS.agentName,
+ group_name: DEFAULTS.groupName,
};
- const agent = {
- template_id: preferred.botId || DEFAULTS.botId,
- template_name: DEFAULTS.botName,
- resource_id: preferred.botId || DEFAULTS.botId,
+}
+
+export function buildSimulatedEnterpriseContext(search = ''): EnterpriseContextSnapshot {
+ const selected = buildContext(search);
+ return {
+ user: { user_id: selected.user_id, display_name: DEFAULTS.displayName },
+ contexts: [selected],
+ selected,
};
- return { user, org, orgs: [org], gateway, gateways: [gateway], agents: [agent], selectedBot: agent.resource_id };
}
function entryPath(): string {
@@ -36,16 +44,14 @@ function entryPath(): string {
export const simulatedAuthProvider: EnterpriseAuthProvider = {
id: 'simulate',
- startupMessage: '【登录认证模拟调试模式已开启】使用默认用户、组织、组网和 Agent 候选值',
+ startupMessage: '【登录认证模拟调试模式已开启】使用默认 Agent 上下文候选值',
isAuthenticated: () => true,
redirectToLogin: () => {
window.location.replace(entryPath());
return true;
},
getCurrentUser: async () => buildSimulatedEnterpriseContext(window.location.search).user,
- listOrganizations: async () => buildSimulatedEnterpriseContext(window.location.search).orgs,
- listGateways: async () => buildSimulatedEnterpriseContext(window.location.search).gateways,
- listAgents: async () => buildSimulatedEnterpriseContext(window.location.search).agents,
+ listAgentContexts: async () => buildSimulatedEnterpriseContext(window.location.search).contexts,
async logout() {
window.location.replace(entryPath());
},
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/types.ts b/jiuwenswarm/channels/web/frontend/src/auth/types.ts
index 599858e63f..33b89f9540 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/types.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/types.ts
@@ -1,9 +1,4 @@
-import type {
- EnterpriseAgent,
- EnterpriseGateway,
- EnterpriseOrg,
- EnterpriseUser,
-} from '../services/enterpriseContext';
+import type { EnterpriseAgentContext, EnterpriseUser } from '../services/enterpriseContext';
export interface EnterpriseAuthProvider {
readonly id: 'manager' | 'simulate';
@@ -12,9 +7,7 @@ export interface EnterpriseAuthProvider {
/** Return false when the User Web itself has already fallen back to /auth. */
redirectToLogin(): boolean;
getCurrentUser(): Promise<EnterpriseUser>;
- listOrganizations(): Promise<EnterpriseOrg[]>;
- listGateways(): Promise<EnterpriseGateway[]>;
- listAgents(groupId: string, gatewayId: string): Promise<EnterpriseAgent[]>;
+ listAgentContexts(): Promise<EnterpriseAgentContext[]>;
logout(): Promise<void>;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/EditableCombobox.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/EditableCombobox.tsx
index 30a811da35..4b0f8b966c 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/EditableCombobox.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/EditableCombobox.tsx
@@ -9,15 +9,24 @@ interface EditableComboboxProps {
ariaLabel: string;
disabled?: boolean;
emptyText?: string;
+ placeholder?: string;
onChange: (value: string) => void;
options: EditableComboboxOption[];
value: string;
}
-export function EditableCombobox({ ariaLabel, disabled = false, emptyText = '没有匹配项', onChange, options, value }: EditableComboboxProps) {
+export function EditableCombobox({
+ ariaLabel,
+ disabled = false,
+ emptyText = '没有匹配项',
+ placeholder,
+ onChange,
+ options,
+ value,
+}: EditableComboboxProps) {
const listboxId = useId();
const selectedOption = options.find(option => option.value === value);
- const selectedLabel = selectedOption?.label ?? value;
+ const selectedLabel = selectedOption?.label ?? (value ? value : '');
const [inputValue, setInputValue] = useState(selectedLabel);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
@@ -54,7 +63,9 @@ export function EditableCombobox({ ariaLabel, disabled = false, emptyText = '没
setOpen(false);
setInputValue(option.label);
setActiveIndex(0);
- if (option.value !== value) onChange(option.value);
+ // 显式点选始终通知父组件:自定义生效后 value 可能仍停在某项,
+ // 再点同一项时也需要触发切换回授权 Agent。
+ onChange(option.value);
};
const handleBlur = (event: FocusEvent<HTMLDivElement>) => {
@@ -98,6 +109,7 @@ export function EditableCombobox({ ariaLabel, disabled = false, emptyText = '没
aria-activedescendant={open && filteredOptions.length > 0 ? `${listboxId}-option-${activeIndex}` : undefined}
autoComplete="off"
disabled={disabled}
+ placeholder={placeholder}
value={inputValue}
onChange={event => {
setInputValue(event.target.value);
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css
index 8e50360d6e..d647368a2c 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css
@@ -330,7 +330,7 @@
z-index: 1500;
left: 72px;
bottom: 56px;
- width: 240px;
+ width: 280px;
padding: 14px;
border: 1px solid var(--color-border-default);
border-radius: 12px;
@@ -442,10 +442,92 @@
}
/* 企业版用户面:与主侧栏统一的克制弹层样式。 */
-.enterprise-context-popover { padding: 12px; border-radius: 12px; background: var(--color-surface-popover); box-shadow: var(--effect-shadow-lg); }
+.enterprise-context-popover { width: 280px; padding: 12px; border-radius: 12px; background: var(--color-surface-popover); box-shadow: var(--effect-shadow-lg); }
.enterprise-context-popover__user { margin: 0 2px 8px; padding: 4px 4px 10px; font-size: 13px; }
+.enterprise-context-popover__modes {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 4px;
+ margin: 0 0 4px;
+ padding: 3px;
+ border: 1px solid var(--color-border-default);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--color-surface-card) 70%, transparent);
+}
+.enterprise-context-popover__mode {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ height: 28px;
+ padding: 0 8px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--color-text-secondary);
+ cursor: pointer;
+ font-size: 11px;
+}
+.enterprise-context-popover__mode--active {
+ background: var(--color-surface-card);
+ color: var(--color-text-primary);
+ font-weight: 600;
+ box-shadow: var(--effect-shadow-sm, 0 1px 2px rgba(0, 0, 0, 0.06));
+}
+.enterprise-context-popover__mode-check {
+ color: #16a34a;
+ font-size: 12px;
+ font-weight: 700;
+ line-height: 1;
+}
+.enterprise-context-popover__mode:disabled {
+ cursor: wait;
+ opacity: 0.65;
+}
.enterprise-context-popover label { margin-top: 8px; font-size: 11px; }
.enterprise-context-popover .editable-combobox { margin-top: 4px; }
+.enterprise-context-popover__input {
+ display: block;
+ box-sizing: border-box;
+ width: 100%;
+ height: 32px;
+ margin-top: 4px;
+ padding: 0 9px;
+ border: 1px solid var(--color-border-default);
+ border-radius: 7px;
+ outline: none;
+ background: var(--color-surface-card);
+ color: var(--color-text-primary);
+ font-size: 12px;
+}
+.enterprise-context-popover__input:focus {
+ border-color: var(--color-action-primary);
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-action-primary) 16%, transparent);
+}
+.enterprise-context-popover__input:disabled {
+ cursor: wait;
+ opacity: 0.65;
+}
+.enterprise-context-popover__apply {
+ width: 100%;
+ margin-top: 10px;
+ padding: 8px 10px;
+ border: 1px solid var(--color-border-default);
+ border-radius: 7px;
+ background: var(--color-surface-card);
+ color: var(--color-text-primary);
+ cursor: pointer;
+ font-size: 12px;
+ text-align: center;
+}
+.enterprise-context-popover__apply:hover:not(:disabled) {
+ border-color: var(--color-action-primary);
+ color: var(--color-action-primary);
+}
+.enterprise-context-popover__apply:disabled {
+ cursor: wait;
+ opacity: 0.65;
+}
.enterprise-context-popover__status { margin-top: 10px; color: var(--color-text-secondary); font-size: 11px; }
.enterprise-context-popover__error { margin-top: 10px; color: var(--color-feedback-danger); font-size: 11px; line-height: 1.45; }
.enterprise-context-popover__logout { width: 100%; margin-top: 12px; padding: 8px 10px; border: 1px solid var(--color-border-default); border-radius: 7px; background: transparent; color: var(--color-feedback-danger); cursor: pointer; font-size: 12px; text-align: center; }
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
index df50648fb7..1d5d6535e5 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
@@ -4,7 +4,7 @@
* Redesigned sidebar with logo, navigation, and advanced config panel.
*/
-import { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';
+import { useState, useRef, useEffect, useLayoutEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import './SessionSidebar.css';
import ChannelIcon from '../../assets/sidebar/channel.svg?react';
@@ -21,11 +21,17 @@ import SkillDesignIcon from '../../assets/技能.svg?react';
import AgentDesignIcon from '../../assets/智能体.svg?react';
import MoreDesignIcon from '../../assets/更多.svg?react';
import { webRequest } from '../../services/webClient';
-import { useEnterpriseContext } from '../../services/enterpriseContext';
+import {
+ agentContextKey,
+ formatAgentContextLabel,
+ useEnterpriseContext,
+} from '../../services/enterpriseContext';
import { isClickOutside } from './clickOutside';
import { EditableCombobox } from './EditableCombobox';
import type { MainNavKey } from '../../features/mainNavigationState';
+type ContextMode = 'select' | 'custom';
+
interface SessionSidebarProps {
activeNav: MainNavKey;
onNavigate: (nav: MainNavKey) => void;
@@ -156,6 +162,11 @@ export function SessionSidebar({
const settingsRef = useRef<HTMLButtonElement>(null);
const enterprise = useEnterpriseContext();
const [contextOpen, setContextOpen] = useState(false);
+ const [contextMode, setContextMode] = useState<ContextMode>('select');
+ const [listSelectionKey, setListSelectionKey] = useState('');
+ const [customBotId, setCustomBotId] = useState('');
+ const [customGroupId, setCustomGroupId] = useState('');
+ const [customUserId, setCustomUserId] = useState('');
const contextButtonRef = useRef<HTMLButtonElement>(null);
const contextPanelRef = useRef<HTMLDivElement>(null);
@@ -213,6 +224,49 @@ export function SessionSidebar({
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [contextOpen]);
+ useEffect(() => {
+ if (!enterprise || !contextOpen) return;
+ setCustomBotId(enterprise.selected.bot_id);
+ setCustomGroupId(enterprise.selected.group_id);
+ setCustomUserId(enterprise.selected.user_id);
+ }, [contextOpen, enterprise?.selected]);
+
+ const activeMode: ContextMode = useMemo(() => {
+ if (!enterprise) return 'select';
+ const selectedKey = agentContextKey(enterprise.selected);
+ return enterprise.contexts.some(item => agentContextKey(item) === selectedKey) ? 'select' : 'custom';
+ }, [enterprise]);
+
+ // 生效身份变化后(含自定义应用后刷新)自动落到对应页签,避免误以为还在「选择 Agent」。
+ useEffect(() => {
+ setContextMode(activeMode);
+ }, [activeMode]);
+
+ // 「选择 Agent」下拉只跟授权列表走;自定义生效时不预选第一项,
+ // 否则点选同一项时 combobox 认为值未变、不会触发切换。
+ useEffect(() => {
+ if (!enterprise?.contexts.length) return;
+ const selectedKey = agentContextKey(enterprise.selected);
+ if (enterprise.contexts.some(item => agentContextKey(item) === selectedKey)) {
+ setListSelectionKey(selectedKey);
+ return;
+ }
+ setListSelectionKey('');
+ }, [
+ enterprise?.contexts,
+ enterprise?.selected.bot_id,
+ enterprise?.selected.group_id,
+ enterprise?.selected.user_id,
+ ]);
+
+ const agentContextOptions = useMemo(
+ () =>
+ (enterprise?.contexts ?? []).map(item => ({
+ value: agentContextKey(item),
+ label: formatAgentContextLabel(item),
+ })),
+ [enterprise?.contexts],
+ );
return (
<aside className="sidebar sidebar--icon-rail">
<div className="icon-rail-logo">
@@ -280,11 +334,11 @@ export function SessionSidebar({
type="button"
className={`icon-rail-nav-item${contextOpen ? ' icon-rail-nav-item--active' : ''}`}
onClick={() => setContextOpen(open => !open)}
- aria-label="用户上下文"
- title="用户上下文"
+ aria-label={t('sessionSidebar.enterpriseContext.userContext')}
+ title={t('sessionSidebar.enterpriseContext.userContext')}
>
<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>
+ <span className="icon-rail-nav-item__label">{t('sessionSidebar.enterpriseContext.user')}</span>
</button>
)}
{enterprise && contextOpen && (
@@ -293,43 +347,112 @@ export function SessionSidebar({
{enterprise.user.display_name || enterprise.user.user_id}
<small>{enterprise.user.user_id}</small>
</div>
- <label>
- 组织(group_id)
- <EditableCombobox
- ariaLabel="组织(group_id)"
- value={enterprise.org.group_id}
- disabled={enterprise.contextSwitching}
- options={enterprise.orgs.map(item => ({ value: item.group_id, label: `${item.name} · ${item.group_id}` }))}
- onChange={enterprise.onOrgChange}
- />
- </label>
- <label>
- 组网(gateway_id)
- <EditableCombobox
- ariaLabel="组网(gateway_id)"
- value={enterprise.gateway.jiuwenclaw_id}
+ <div className="enterprise-context-popover__modes" role="tablist" aria-label={t('sessionSidebar.enterpriseContext.modeAria')}>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={contextMode === 'select'}
+ className={`enterprise-context-popover__mode${contextMode === 'select' ? ' enterprise-context-popover__mode--active' : ''}`}
disabled={enterprise.contextSwitching}
- options={enterprise.gateways.map(item => ({ value: item.jiuwenclaw_id, label: `${item.jiuwenclaw_name} · ${item.jiuwenclaw_id}` }))}
- onChange={enterprise.onGatewayChange}
- />
- </label>
- <label>
- Agent(bot_id)
- <EditableCombobox
- ariaLabel="Agent(bot_id)"
- value={enterprise.selectedBot}
+ onClick={() => {
+ // 自定义生效时清空下拉,避免仍显示上次项导致再点同一项无反应。
+ if (activeMode === 'custom') setListSelectionKey('');
+ setContextMode('select');
+ }}
+ >
+ {t('sessionSidebar.enterpriseContext.selectAgent')}
+ {activeMode === 'select' && (
+ <span className="enterprise-context-popover__mode-check" aria-hidden>
+ ✓
+ </span>
+ )}
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={contextMode === 'custom'}
+ className={`enterprise-context-popover__mode${contextMode === 'custom' ? ' enterprise-context-popover__mode--active' : ''}`}
disabled={enterprise.contextSwitching}
- options={enterprise.agents.map(item => ({
- value: item.resource_id || item.template_id,
- label: `${item.template_name} · ${item.resource_id || item.template_id}`,
- }))}
- onChange={enterprise.onBotChange}
- />
- </label>
- {enterprise.contextSwitching && <div className="enterprise-context-popover__status">正在切换...</div>}
+ onClick={() => setContextMode('custom')}
+ >
+ {t('sessionSidebar.enterpriseContext.custom')}
+ {activeMode === 'custom' && (
+ <span className="enterprise-context-popover__mode-check" aria-hidden>
+ ✓
+ </span>
+ )}
+ </button>
+ </div>
+ {contextMode === 'select' ? (
+ <label>
+ {t('sessionSidebar.enterpriseContext.agentOrgLabel')}
+ <EditableCombobox
+ ariaLabel={t('sessionSidebar.enterpriseContext.agentOrgLabel')}
+ emptyText={t('sessionSidebar.enterpriseContext.noMatch')}
+ placeholder={t('sessionSidebar.enterpriseContext.pleaseSelect')}
+ value={listSelectionKey}
+ disabled={enterprise.contextSwitching}
+ options={agentContextOptions}
+ onChange={key => {
+ setListSelectionKey(key);
+ enterprise.onContextChange(key);
+ }}
+ />
+ </label>
+ ) : (
+ <>
+ <label>
+ {t('sessionSidebar.enterpriseContext.botId')}
+ <input
+ className="enterprise-context-popover__input"
+ value={customBotId}
+ disabled={enterprise.contextSwitching}
+ onChange={event => setCustomBotId(event.target.value)}
+ aria-label={t('sessionSidebar.enterpriseContext.botId')}
+ />
+ </label>
+ <label>
+ {t('sessionSidebar.enterpriseContext.groupId')}
+ <input
+ className="enterprise-context-popover__input"
+ value={customGroupId}
+ disabled={enterprise.contextSwitching}
+ onChange={event => setCustomGroupId(event.target.value)}
+ aria-label={t('sessionSidebar.enterpriseContext.groupId')}
+ />
+ </label>
+ <label>
+ {t('sessionSidebar.enterpriseContext.userId')}
+ <input
+ className="enterprise-context-popover__input"
+ value={customUserId}
+ disabled={enterprise.contextSwitching}
+ onChange={event => setCustomUserId(event.target.value)}
+ aria-label={t('sessionSidebar.enterpriseContext.userId')}
+ />
+ </label>
+ <button
+ type="button"
+ className="enterprise-context-popover__apply"
+ disabled={enterprise.contextSwitching}
+ onClick={() =>
+ enterprise.onCustomContextApply({
+ botId: customBotId,
+ groupId: customGroupId,
+ userId: customUserId,
+ })
+ }
+ >
+ {t('sessionSidebar.enterpriseContext.apply')}
+ </button>
+ </>
+ )}
+ {enterprise.contextSwitching && (
+ <div className="enterprise-context-popover__status">{t('sessionSidebar.enterpriseContext.switching')}</div>
+ )}
{enterprise.contextError && <div className="enterprise-context-popover__error">{enterprise.contextError}</div>}
<button type="button" className="enterprise-context-popover__logout" onClick={enterprise.onLogout}>
- 注销登录
+ {t('sessionSidebar.enterpriseContext.logout')}
</button>
</div>
)}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index a1216bb1d0..6a7073adcf 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -411,7 +411,6 @@ function getConnectSignature(options: WebConnectOptions): string {
userId: scope.userId || '',
groupId: scope.groupId || '',
botId: scope.botId || '',
- gatewayId: scope.gatewayId || '',
});
}
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index cba7884317..3298b7f148 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -544,7 +544,24 @@
"connectionStatus": "Connection Status",
"version": "Version",
"language": "Language",
- "moreSettings": "More Settings"
+ "moreSettings": "More Settings",
+ "enterpriseContext": {
+ "user": "User",
+ "userContext": "User context",
+ "modeAria": "Context setup mode",
+ "selectAgent": "Select Agent",
+ "custom": "Custom",
+ "agentOrgLabel": "Agent name - Organization name",
+ "botId": "bot_id",
+ "groupId": "group_id",
+ "userId": "user_id",
+ "apply": "Apply",
+ "switching": "Switching...",
+ "logout": "Sign out",
+ "customRequired": "Please fill in bot_id, group_id, and user_id",
+ "noMatch": "No matches",
+ "pleaseSelect": "Please select"
+ }
},
"a2aIngress": {
"security": {
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 060980c2d7..575e1184f1 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -545,7 +545,24 @@
"connectionStatus": "连接状态",
"version": "版本",
"language": "语言",
- "moreSettings": "更多设置"
+ "moreSettings": "更多设置",
+ "enterpriseContext": {
+ "user": "用户",
+ "userContext": "用户上下文",
+ "modeAria": "上下文设定方式",
+ "selectAgent": "选择 Agent",
+ "custom": "自定义",
+ "agentOrgLabel": "agent名称-组织名称",
+ "botId": "bot_id",
+ "groupId": "group_id",
+ "userId": "user_id",
+ "apply": "应用",
+ "switching": "正在切换...",
+ "logout": "注销登录",
+ "customRequired": "请填写 bot_id、group_id、user_id",
+ "noMatch": "没有匹配项",
+ "pleaseSelect": "请选择"
+ }
},
"a2aIngress": {
"security": {
diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/routing/route.ts b/jiuwenswarm/channels/web/frontend/src/multi-session/routing/route.ts
index b8920b5e22..d2fc689c04 100644
--- a/jiuwenswarm/channels/web/frontend/src/multi-session/routing/route.ts
+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/routing/route.ts
@@ -22,7 +22,6 @@ function appendEnterpriseScope(path: string): string {
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);
const suffix = query.toString();
return suffix ? `${path}?${suffix}` : path;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
index 1a8a67969d..e94d566914 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
@@ -1,33 +1,41 @@
import { createContext, useContext } from 'react';
export type EnterpriseUser = { user_id: string; display_name: string };
-export type EnterpriseOrg = { group_id: string; name: string };
-export type EnterpriseGateway = {
+
+/** Manager 返回的可访问上下文;任选一项即可访问对应 Agent。 */
+export type EnterpriseAgentContext = {
+ bot_id: string;
+ group_id: string;
+ user_id: string;
jiuwenclaw_id: string;
- jiuwenclaw_name: string;
- gateway_endpoint: string | null;
+ agent_name: string;
+ group_name: string;
};
-export type EnterpriseAgent = { template_id: string; template_name: string; resource_id?: string };
export type EnterpriseContextSnapshot = {
user: EnterpriseUser;
- org: EnterpriseOrg;
- orgs: EnterpriseOrg[];
- gateway: EnterpriseGateway;
- gateways: EnterpriseGateway[];
- agents: EnterpriseAgent[];
- selectedBot: string;
+ contexts: EnterpriseAgentContext[];
+ selected: EnterpriseAgentContext;
};
export type EnterpriseContextValue = EnterpriseContextSnapshot & {
contextError: string;
contextSwitching: boolean;
- onOrgChange: (id: string) => void;
- onGatewayChange: (id: string) => void;
- onBotChange: (id: string) => void;
+ onContextChange: (key: string) => void;
+ onCustomContextApply: (input: { botId: string; groupId: string; userId: string }) => void;
onLogout: () => void;
};
+export function agentContextKey(item: Pick<EnterpriseAgentContext, 'bot_id' | 'group_id' | 'user_id'>): string {
+ return `${item.bot_id}\u0001${item.group_id}\u0001${item.user_id}`;
+}
+
+export function formatAgentContextLabel(item: EnterpriseAgentContext): string {
+ const agentName = item.agent_name?.trim() || item.bot_id;
+ const groupName = item.group_name?.trim() || item.group_id;
+ return `${agentName}-${groupName}`;
+}
+
export const EnterpriseContext = createContext<EnterpriseContextValue | null>(null);
export function useEnterpriseContext() {
return useContext(EnterpriseContext);
diff --git a/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts b/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts
index d9d1913fbe..8628530365 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts
@@ -2,7 +2,6 @@ export interface RuntimeScope {
userId?: string;
groupId?: string;
botId?: string;
- gatewayId?: string;
}
/** Dispatched when enterprise routing identity changes; WS should reconnect. */
@@ -26,26 +25,21 @@ function scopeSignature(scope: RuntimeScope): string {
userId: scope.userId || '',
groupId: scope.groupId || '',
botId: scope.botId || '',
- gatewayId: scope.gatewayId || '',
});
}
/**
* Read the runtime routing scope supplied by the embedding shell.
*
- * The values are transport context rather than business form fields. They are
- * intentionally kept in memory and are not written to localStorage or
- * sessionStorage. Authentication and authorization remain the responsibility
- * of the outer shell and server-side access control.
+ * 用户面路由身份仅为 ``user_id`` / ``group_id`` / ``bot_id``(不含 gateway_id)。
+ * 仅保存在内存,不写 local/sessionStorage。
*/
export 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'),
};
}
@@ -59,7 +53,6 @@ export function setRuntimeScope(scope: RuntimeScope): void {
userId: pickString(scope.userId),
groupId: pickString(scope.groupId),
botId: pickString(scope.botId),
- gatewayId: pickString(scope.gatewayId),
};
const changed = scopeSignature(runtimeScope) !== scopeSignature(next);
runtimeScope = next;
@@ -77,7 +70,6 @@ export function getRuntimeScope(): RuntimeScope {
userId: current.userId ?? runtimeScope.userId,
groupId: current.groupId ?? runtimeScope.groupId,
botId: current.botId ?? runtimeScope.botId,
- gatewayId: current.gatewayId ?? runtimeScope.gatewayId,
};
return runtimeScope;
}
@@ -90,7 +82,6 @@ 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;
}
@@ -110,7 +101,6 @@ 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-Gateway-Id'] = scope.gatewayId;
if (sessionId) headers['X-Session-Id'] = sessionId;
return headers;
}
diff --git a/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs b/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs
index af4c4bb9e6..a659adf209 100644
--- a/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs
@@ -11,9 +11,10 @@ test('runtime scope is parsed and added to websocket query', () => {
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' });
+ // 用户面忽略 URL 中的 gateway_id(遗留参数)。
+ assert.deepEqual(scope, { userId: 'u1', groupId: 'g1', botId: 'b1' });
const query = appendRuntimeScopeQuery(new URLSearchParams('provider=p'), scope);
- assert.equal(query.toString(), 'provider=p&user_id=u1&group_id=g1&bot_id=b1&gateway_id=gw1');
+ assert.equal(query.toString(), 'provider=p&user_id=u1&group_id=g1&bot_id=b1');
});
test('runtime scope takes precedence in HTTP identity headers', () => {
@@ -26,14 +27,13 @@ test('runtime scope takes precedence in HTTP identity headers', () => {
bot_id: 'payload-bot',
session_id: 'session-1',
},
- { userId: 'u1', groupId: 'g1', botId: 'b1', gatewayId: 'gw1' }
+ { userId: 'u1', groupId: 'g1', botId: 'b1' }
),
{
'X-Request-Id': 'req-1',
'X-User-Id': 'u1',
'X-Group-Id': 'g1',
'X-Bot-Id': 'b1',
- 'X-Gateway-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
index ce83a35e60..ff47eca1f4 100644
--- a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
@@ -23,10 +23,9 @@ globalThis.window = {
const {
EnterpriseEntry,
- buildRequestedDebugContext,
- chooseAgent,
+ buildCustomContext,
+ chooseAgentContext,
isDebugContext,
- orderedContextCandidates,
} = await import('../node_modules/.cache/user-web-entry/EnterpriseEntry.mjs');
const {
isAuthEntryPath,
@@ -66,7 +65,7 @@ test('enterprise edition redirects unauthenticated users instead of rendering Us
test('enterprise edition loads and validates an authorized context before rendering User Web', () => {
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';
+ window.location.search = '?user_id=user-1&group_id=group-1&bot_id=bot-1';
const html = renderEntry('enterprise');
@@ -79,19 +78,17 @@ test('simulated enterprise login uses local defaults without an access token', (
const context = buildSimulatedEnterpriseContext('');
assert.equal(context.user.user_id, 'default');
- assert.equal(context.org.group_id, 'default');
- assert.equal(context.gateway.jiuwenclaw_id, 'debug-gateway');
- assert.equal(context.selectedBot, 'default');
+ assert.equal(context.selected.group_id, 'default');
+ assert.equal(context.selected.bot_id, 'default');
assert.doesNotMatch(renderEntry('enterprise', true), /正在前往登录页/);
});
test('simulated enterprise login accepts URL tuple overrides', () => {
- const context = buildSimulatedEnterpriseContext('?user_id=u1&group_id=g1&gateway_id=gw1&bot_id=b1');
+ const context = buildSimulatedEnterpriseContext('?user_id=u1&group_id=g1&bot_id=b1');
assert.equal(context.user.user_id, 'u1');
- assert.equal(context.org.group_id, 'g1');
- assert.equal(context.gateway.jiuwenclaw_id, 'gw1');
- assert.equal(context.selectedBot, 'b1');
+ assert.equal(context.selected.group_id, 'g1');
+ assert.equal(context.selected.bot_id, 'b1');
});
test('LOGIN_AUTH_SIMULATE accepts only booleans and defaults to true', () => {
@@ -107,51 +104,31 @@ test('auth entry path guard stops User Web from redirecting /auth to itself', ()
assert.equal(isAuthEntryPath('/chat/'), false);
});
-test('context candidates prefer URL values but retain every authorized combination', () => {
- const gateways = [
- { jiuwenclaw_id: 'gateway-1', jiuwenclaw_name: 'Gateway 1', gateway_endpoint: null },
- { jiuwenclaw_id: 'gateway-2', jiuwenclaw_name: 'Gateway 2', gateway_endpoint: null },
+test('agent context selection prefers an exact URL tuple and otherwise falls back', () => {
+ const contexts = [
+ { bot_id: 'agent-1', group_id: 'group-1', user_id: 'user-1', jiuwenclaw_id: 'gw-1', agent_name: 'Agent 1', group_name: 'Group 1' },
+ { bot_id: 'agent-2', group_id: 'group-2', user_id: 'user-1', jiuwenclaw_id: 'gw-2', agent_name: 'Agent 2', group_name: 'Group 2' },
];
- const orgs = [
- { group_id: 'group-1', name: 'Group 1' },
- { group_id: 'group-2', name: 'Group 2' },
- ];
-
- const candidates = orderedContextCandidates(gateways, orgs, 'gateway-2', 'group-2');
- assert.deepEqual(
- candidates.map(({ gateway, org }) => [gateway.jiuwenclaw_id, org.group_id]),
- [
- ['gateway-2', 'group-2'],
- ['gateway-2', 'group-1'],
- ['gateway-1', 'group-2'],
- ['gateway-1', 'group-1'],
- ],
+ assert.equal(
+ chooseAgentContext(contexts, { botId: 'agent-2', groupId: 'group-2', userId: 'user-1' })?.bot_id,
+ 'agent-2',
);
-});
-
-test('agent selection accepts a still-authorized URL agent and otherwise falls back to the first agent', () => {
- const agents = [
- { template_id: 'template-1', template_name: 'Agent 1', resource_id: 'agent-1' },
- { template_id: 'template-2', template_name: 'Agent 2', resource_id: 'agent-2' },
- ];
-
- assert.equal(chooseAgent(agents, 'agent-2')?.resource_id, 'agent-2');
- assert.equal(chooseAgent(agents, 'removed-agent')?.resource_id, 'agent-1');
- assert.equal(chooseAgent([], 'agent-2'), null);
+ assert.equal(chooseAgentContext(contexts, { botId: 'agent-2' })?.group_id, 'group-2');
+ assert.equal(chooseAgentContext(contexts, { botId: 'removed-agent' })?.bot_id, 'agent-1');
+ assert.equal(chooseAgentContext([], { botId: 'agent-2' }), null);
});
test('debug context preserves explicitly entered routing identifiers', () => {
- const debugContext = buildRequestedDebugContext(
- [{ group_id: 'group-1', name: 'Group 1' }],
- [{ jiuwenclaw_id: 'gateway-1', jiuwenclaw_name: 'Gateway 1', gateway_endpoint: null }],
- [],
- { groupId: 'debug-group', gatewayId: 'debug-gateway', botId: 'debug-bot' },
+ const debugContext = buildCustomContext(
+ { userId: 'debug-user', groupId: 'debug-group', botId: 'debug-bot' },
+ 'resolved-gateway',
);
assert.equal(isDebugContext('?debug_context=1'), true);
assert.equal(isDebugContext('?debug_context=0'), false);
- assert.equal(debugContext?.org.group_id, 'debug-group');
- assert.equal(debugContext?.gateway.jiuwenclaw_id, 'debug-gateway');
- assert.equal(debugContext?.selectedBot, 'debug-bot');
+ assert.equal(debugContext?.group_id, 'debug-group');
+ assert.equal(debugContext?.jiuwenclaw_id, 'resolved-gateway');
+ assert.equal(debugContext?.bot_id, 'debug-bot');
+ assert.equal(debugContext?.user_id, 'debug-user');
});
diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.ts
index 583737f9e7..6723b30224 100644
--- a/jiuwenswarm/channels/web/frontend/vite.config.ts
+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts
@@ -367,7 +367,7 @@ function loginAuthStartupCheck(): Plugin {
console.info('[jiuwenswarm-web] 【正式身份认证模式,依赖manager ID认证服务】')
const targets = [
{ name: 'manager ID认证服务', env: 'USER_WEB_IDP_TARGET', target: process.env.USER_WEB_IDP_TARGET, path: '/v1/auth/me' },
- { name: 'Manager业务接口', env: 'USER_WEB_MANAGER_TARGET', target: process.env.USER_WEB_MANAGER_TARGET, path: '/api/v1/user-console/gateways' },
+ { name: 'Manager业务接口', env: 'USER_WEB_MANAGER_TARGET', target: process.env.USER_WEB_MANAGER_TARGET, path: '/api/v1/user-console/agent-contexts' },
]
const missing = targets.filter(({ target }) => !target).map(({ env }) => env)
if (missing.length > 0) {
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/config_effective_policy_models.py b/jiuwenswarm/gateway/config/enterprise/tables/config_effective_policy_models.py
deleted file mode 100644
index ea74f03c39..0000000000
--- a/jiuwenswarm/gateway/config/enterprise/tables/config_effective_policy_models.py
+++ /dev/null
@@ -1,129 +0,0 @@
-# coding: utf-8
-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
-
-"""配置生效策略与默认模板映射表(与 Claw Manager 企业级数据模型对齐)。"""
-
-from __future__ import annotations
-
-from openjiuwen_runtime.foundation.db.table_def import (
- ColumnDefinition,
- IndexDefinition,
- TableDefinition,
-)
-
-CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF = TableDefinition(
- table_name="config_effective_global_policy",
- columns=[
- ColumnDefinition(
- "id",
- "integer",
- primary_key=True,
- autoincrement=True,
- nullable=False,
- ),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
- ColumnDefinition("policy_id", "string", length=100, nullable=False),
- ColumnDefinition("policy_name", "string", length=128, nullable=False),
- ColumnDefinition("policy_desc", "string", length=512, nullable=True),
- ColumnDefinition("priority", "integer", nullable=False),
- ColumnDefinition("template_ref", "json", nullable=False),
- ColumnDefinition("enabled", "boolean", nullable=False, default=True),
- ColumnDefinition("data", "json", nullable=True),
- ColumnDefinition("created_at", "datetime", nullable=False),
- ColumnDefinition("updated_at", "datetime", nullable=False),
- ],
- indexes=[
- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),
- ],
-)
-
-
-CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF = TableDefinition(
- table_name="config_effective_service_policy",
- columns=[
- ColumnDefinition(
- "id",
- "integer",
- primary_key=True,
- autoincrement=True,
- nullable=False,
- ),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
- ColumnDefinition("policy_id", "string", length=100, nullable=False),
- ColumnDefinition("policy_name", "string", length=128, nullable=False),
- ColumnDefinition("policy_desc", "string", length=512, nullable=True),
- ColumnDefinition("service_id", "string", length=512, nullable=False),
- ColumnDefinition("priority", "integer", nullable=False),
- ColumnDefinition("match_expr", "string", length=8192, nullable=True),
- ColumnDefinition("template_ref", "json", nullable=False),
- ColumnDefinition("enabled", "boolean", nullable=False, default=True),
- ColumnDefinition("data", "json", nullable=True),
- ColumnDefinition("created_at", "datetime", nullable=False),
- ColumnDefinition("updated_at", "datetime", nullable=False),
- ],
- indexes=[
- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),
- ],
-)
-
-
-CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF = TableDefinition(
- table_name="config_effective_agent_policy",
- columns=[
- ColumnDefinition(
- "id",
- "integer",
- primary_key=True,
- autoincrement=True,
- nullable=False,
- ),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
- ColumnDefinition("policy_id", "string", length=100, nullable=False),
- ColumnDefinition("policy_name", "string", length=128, nullable=False),
- ColumnDefinition("policy_desc", "string", length=512, nullable=True),
- ColumnDefinition("agent_id", "string", length=512, nullable=False),
- ColumnDefinition("workspace_dir", "string", length=512, nullable=True),
- ColumnDefinition("service_policy_id", "string", length=100, nullable=False),
- ColumnDefinition("priority", "integer", nullable=False, default=0),
- ColumnDefinition("match_expr", "string", length=8192, nullable=True),
- ColumnDefinition("template_ref", "json", nullable=False),
- ColumnDefinition("send_file_allowed", "boolean", nullable=False, default=True),
- ColumnDefinition("enabled", "boolean", nullable=False, default=True),
- ColumnDefinition("data", "json", nullable=True),
- ColumnDefinition("created_at", "datetime", nullable=False),
- ColumnDefinition("updated_at", "datetime", nullable=False),
- ],
- indexes=[
- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),
- ],
-)
-
-
-CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF = TableDefinition(
- table_name="config_default_template_mapping",
- columns=[
- ColumnDefinition(
- "id",
- "integer",
- primary_key=True,
- autoincrement=True,
- nullable=False,
- ),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
- ColumnDefinition("policy_id", "string", length=100, nullable=False),
- ColumnDefinition("policy_name", "string", length=128, nullable=False),
- ColumnDefinition("policy_desc", "string", length=512, nullable=True),
- ColumnDefinition("scope_type", "string", length=32, nullable=False),
- ColumnDefinition("scope_id", "string", length=512, nullable=False),
- ColumnDefinition("priority", "integer", nullable=False),
- ColumnDefinition("template_id", "string", length=100, nullable=False),
- ColumnDefinition("template_type", "string", length=512, nullable=False),
- ColumnDefinition("enabled", "boolean", nullable=False, default=True),
- ColumnDefinition("data", "json", nullable=True),
- ColumnDefinition("created_at", "datetime", nullable=False),
- ColumnDefinition("updated_at", "datetime", nullable=False),
- ],
- indexes=[
- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),
- ],
-)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index be586e3a13..ef5321ca47 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -1832,10 +1832,10 @@ async def _build_postgresql_async_engine():
result = await conn.execute(
text(
"SELECT data_type FROM information_schema.columns "
- "WHERE table_catalog = :db AND table_name = 'kv_store' "
- "AND column_name = 'value'"
+ "WHERE table_catalog = :db AND table_schema = :schema "
+ "AND table_name = 'kv_store' AND column_name = 'value'"
),
- {"db": db_name},
+ {"db": db_name, "schema": pg_schema},
)
row = result.fetchone()
if row is None: