JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(web): 企业用户面直接承载上下文选择
whqf288307292c5
diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsxindex dd2657df18..ec593e3e90 100644--- a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx@@ -1,83 +1,201 @@-import { type ReactNode, useEffect, useState } from 'react';+import { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';import { isEnterpriseMode } from './edition';-import { EnterpriseContext, type EnterpriseContextSnapshot, type EnterpriseContextValue } from './services/enterpriseContext';-import { getRuntimeScope } from './services/runtimeScope';+import {+ EnterpriseContext,+ type EnterpriseAgent,+ type EnterpriseContextSnapshot,+ type EnterpriseContextValue,+ type EnterpriseGateway,+ type EnterpriseOrg,+ type EnterpriseUser,+} from './services/enterpriseContext';+import { parseRuntimeScope, setRuntimeScope } from './services/runtimeScope';const ACCESS_KEY = 'openjiuwen_access_token';-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';+const REFRESH_KEY = 'openjiuwen_refresh_token';-function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null;-}+type EntryPhase = 'loading' | 'ready' | 'empty' | 'error' | 'redirecting';-function isContextSnapshot(value: unknown): value is EnterpriseContextSnapshot {- if (!isRecord(value) || !isRecord(value.user) || !isRecord(value.org) || !isRecord(value.gateway)) {- return false;+class EnterpriseApiError extends Error {+ constructor(+ readonly status: number,+ message: string,+ ) {+ super(message);+ this.name = 'EnterpriseApiError';}- 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 hasManagerRuntimeContext(): boolean {- const scope = getRuntimeScope();- return Boolean(scope.userId && scope.groupId && scope.botId && scope.gatewayId);+interface ManagerResponse<T> {+ code: number;+ message?: string;+ data: T;+}++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);+ 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;+}++function accessToken(): string | null {+ return typeof localStorage === 'undefined' ? null : localStorage.getItem(ACCESS_KEY);+}++function authHeaders(): HeadersInit {+ const token = accessToken();+ return token ? { Authorization: `Bearer ${token}` } : {};}-function canEnterEnterpriseUserWeb(): boolean {- if (typeof localStorage === 'undefined') {- return false;+function requestMessage(body: unknown, fallback: string): string {+ if (body && typeof body === 'object') {+ const value = body as Record<string, unknown>;+ if (typeof value.detail === 'string' && value.detail.trim()) return value.detail;+ if (typeof value.message === 'string' && value.message.trim()) return value.message;}- return Boolean(localStorage.getItem(ACCESS_KEY)) && hasManagerRuntimeContext();+ return fallback;}-export function EnterpriseEntry({ children }: { children: ReactNode }) {- const [context, setContext] = useState<EnterpriseContextSnapshot | null>(null);+async function requestJson<T>(path: string): Promise<T> {+ let response: Response;+ try {+ response = await fetch(path, { headers: authHeaders() });+ } catch (error) {+ throw new EnterpriseApiError(0, `网络请求失败:${error instanceof Error ? error.message : String(error)}`);+ }- useEffect(() => {- if (!isEnterpriseMode() || typeof window.addEventListener !== 'function' || window.parent === window) {- return;+ let body: unknown = null;+ try {+ body = await response.json();+ } catch {+ // The status code below remains the source of truth for a non-JSON error.+ }+ if (!response.ok) {+ throw new EnterpriseApiError(response.status, requestMessage(body, `HTTP ${response.status}`));+ }+ return body as T;+}++async function loadUser(): Promise<EnterpriseUser> {+ return requestJson<EnterpriseUser>('/idp/v1/auth/me');+}++async function loadOrgs(): Promise<EnterpriseOrg[]> {+ const result = await requestJson<{ orgs: EnterpriseOrg[] }>('/idp/v1/auth/me/orgs');+ return result.orgs ?? [];+}++async function loadGateways(): Promise<EnterpriseGateway[]> {+ const result = await requestJson<ManagerResponse<{ gateways: EnterpriseGateway[] }>>('/manager-api/v1/user-console/gateways');+ if (result.code !== 200) throw new EnterpriseApiError(result.code, result.message || '加载组网失败');+ return result.data?.gateways ?? [];+}++async function loadAgents(groupId: string, gatewayId: string): Promise<EnterpriseAgent[]> {+ 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 EnterpriseApiError(result.code, result.message || '加载 Agent 失败');+ return result.data?.agents ?? [];+}++async function resolveFirstContext(candidates: ContextCandidate[], preferredBotId?: string): Promise<ResolvedContext | null> {+ let firstError: unknown = null;+ for (const candidate of candidates) {+ try {+ const agents = await loadAgents(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 EnterpriseApiError && error.status === 401) throw error;+ firstError ??= error;}+ }+ if (firstError) throw firstError;+ return null;+}- 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);- };+function entryPath(): string {+ return window.location.pathname.startsWith('/chat') ? '/chat/' : '/';+}- window.addEventListener('message', handleMessage);- window.parent.postMessage({ type: CONTEXT_READY_MESSAGE }, window.location.origin);- return () => window.removeEventListener('message', handleMessage);- }, []);+function contextUrl(userId: string, resolved: ResolvedContext): string {+ const query = new URLSearchParams({+ user_id: userId,+ group_id: resolved.org.group_id,+ bot_id: resolved.selectedBot,+ gateway_id: resolved.gateway.jiuwenclaw_id,+ });+ return `${entryPath()}?${query.toString()}`;+}- if (!isEnterpriseMode() || canEnterEnterpriseUserWeb()) {- if (!context) return <>{children}</>;+function activateContext(userId: string, resolved: ResolvedContext, navigate: boolean): void {+ setRuntimeScope({+ userId,+ groupId: resolved.org.group_id,+ botId: resolved.selectedBot,+ gatewayId: resolved.gateway.jiuwenclaw_id,+ });+ const nextUrl = contextUrl(userId, resolved);+ if (navigate) window.location.replace(nextUrl);+ else window.history.replaceState({}, '', nextUrl);+}- 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 clearLogin(): void {+ if (typeof localStorage !== 'undefined') {+ localStorage.removeItem(ACCESS_KEY);+ localStorage.removeItem(REFRESH_KEY);+ }+ if (typeof document !== 'undefined') {+ document.cookie = `${ACCESS_KEY}=; Path=/; Max-Age=0; SameSite=Strict`;}+}++function redirectToLogin(): void {+ clearLogin();+ window.location.replace('/auth');+}+function errorText(error: unknown): string {+ return error instanceof Error && error.message ? error.message : '加载企业用户上下文失败';+}++function EntryStatus({ phase, error, onLogout }: { phase: EntryPhase; error: string; onLogout: () => void }) {+ const empty = phase === 'empty';+ const failed = phase === 'error';return (<div className="enterprise-entry"><div className="enterprise-entry__glow" />@@ -86,9 +204,159 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {JIUWEN<span>CLAW</span></div><div className="enterprise-entry__eyebrow">ENTERPRISE WORKSPACE</div>- <h1>请从 Manager Web 进入</h1>- <p>企业模式由 Manager Web 统一完成登录及组网、组织和 Bot 选择。</p>+ <h1>{empty ? '暂无可用 Agent' : failed ? '加载失败' : phase === 'redirecting' ? '正在前往登录页' : '正在加载工作空间'}</h1>+ <p>{empty ? '当前账号没有可用的组织、组网和 Agent 组合,请联系管理员完成授权。' : failed ? error : '正在校验账号权限并选择一个可用 Agent。'}</p>+ {(empty || failed) && (+ <button type="button" className="enterprise-entry__button" onClick={onLogout}>+ 返回登录页+ </button>+ )}</div></div>);}++export function EnterpriseEntry({ children }: { children: ReactNode }) {+ const enterprise = isEnterpriseMode();+ const [phase, setPhase] = useState<EntryPhase>(() => (enterprise && !accessToken() ? 'redirecting' : 'loading'));+ const [context, setContext] = useState<EnterpriseContextSnapshot | null>(null);+ const [error, setError] = useState('');+ const [contextError, setContextError] = useState('');+ const [contextSwitching, setContextSwitching] = useState(false);++ const logout = useCallback(() => {+ void (async () => {+ const refreshToken = typeof localStorage === 'undefined' ? null : localStorage.getItem(REFRESH_KEY);+ if (refreshToken) {+ try {+ await fetch('/idp/v1/auth/logout', {+ method: 'POST',+ headers: { ...authHeaders(), 'Content-Type': 'application/json' },+ body: JSON.stringify({ refresh_token: refreshToken }),+ });+ } catch {+ // Local logout must still complete when the identity service is unavailable.+ }+ }+ redirectToLogin();+ })();+ }, []);++ useEffect(() => {+ if (!enterprise) return;+ if (!accessToken()) {+ redirectToLogin();+ return;+ }++ let cancelled = false;+ const bootstrap = async () => {+ try {+ const preferred = parseRuntimeScope(window.location.search);+ const [user, orgs, gateways] = await Promise.all([loadUser(), loadOrgs(), loadGateways()]);+ const resolved = await resolveFirstContext(orderedContextCandidates(gateways, orgs, preferred.gatewayId, preferred.groupId), preferred.botId);+ if (cancelled) return;+ if (!resolved) {+ 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,+ });+ setPhase('ready');+ } catch (bootstrapError) {+ if (cancelled) return;+ if (bootstrapError instanceof EnterpriseApiError && bootstrapError.status === 401) {+ redirectToLogin();+ return;+ }+ setError(errorText(bootstrapError));+ setPhase('error');+ }+ };+ void bootstrap();+ return () => {+ cancelled = true;+ };+ }, [enterprise]);++ const switchContext = useCallback(+ async (candidates: ContextCandidate[], preferredBotId?: string, missingMessage = '所选范围内暂无可用 Agent') => {+ if (!context || contextSwitching) return;+ setContextSwitching(true);+ setContextError('');+ try {+ const resolved = await resolveFirstContext(candidates, preferredBotId);+ if (!resolved) {+ setContextError(missingMessage);+ return;+ }+ activateContext(context.user.user_id, resolved, true);+ } catch (switchError) {+ if (switchError instanceof EnterpriseApiError && switchError.status === 401) {+ redirectToLogin();+ return;+ }+ setContextError(errorText(switchError));+ } finally {+ setContextSwitching(false);+ }+ },+ [context, contextSwitching],+ );++ 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) return;+ const gateways = movePreferredFirst([...context.gateways], item => item.jiuwenclaw_id === context.gateway.jiuwenclaw_id);+ void switchContext(+ gateways.map(gateway => ({ gateway, org })),+ undefined,+ '该组织暂无可用 Agent',+ );+ },+ onGatewayChange: gatewayId => {+ const gateway = context.gateways.find(item => item.jiuwenclaw_id === gatewayId);+ if (!gateway) 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 (!selected || botId === context.selectedBot) return;+ activateContext(+ context.user.user_id,+ {+ gateway: context.gateway,+ org: context.org,+ agents: context.agents,+ selectedBot: botId,+ },+ true,+ );+ },+ onLogout: logout,+ };+ }, [context, contextError, contextSwitching, logout, switchContext]);++ if (!enterprise) return <>{children}</>;+ if (phase !== 'ready' || !contextValue) return <EntryStatus phase={phase} error={error} onLogout={logout} />;+ return <EnterpriseContext.Provider value={contextValue}>{children}</EnterpriseContext.Provider>;+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.cssindex d8f8757215..5fe674a5e4 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css@@ -342,11 +342,13 @@.enterprise-context-popover label { display: block; margin-top: 10px; color: var(--color-text-secondary); font-size: 11px; }.enterprise-context-popover select { display: block; box-sizing: border-box; width: 100%; margin-top: 5px; padding: 7px; border: 1px solid var(--color-border-default); border-radius: 6px; background: var(--color-surface-card); color: var(--color-text-primary); font-size: 12px; }-/* 企业版用户面:与主侧栏统一的克制弹层样式。 */.enterprise-context-popover { 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 label { margin-top: 8px; font-size: 11px; }.enterprise-context-popover select { height: 32px; margin-top: 4px; padding: 0 28px 0 9px; appearance: auto; border-radius: 7px; background: var(--color-surface-card); font-size: 12px; }+.enterprise-context-popover select:disabled { cursor: wait; opacity: .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; }.enterprise-context-popover__logout:hover { background: color-mix(in srgb, var(--color-feedback-danger) 8%, transparent); border-color: var(--color-feedback-danger); }diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsxindex 63d59a7e88..8fa381c889 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx@@ -279,7 +279,7 @@ export function SessionSidebar({</div><label>组织(group_id)- <select value={enterprise.org.group_id} onChange={event => enterprise.onOrgChange(event.target.value)}>+ <select value={enterprise.org.group_id} disabled={enterprise.contextSwitching} 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}@@ -289,7 +289,11 @@ export function SessionSidebar({</label><label>组网(gateway_id)- <select value={enterprise.gateway.jiuwenclaw_id} onChange={event => enterprise.onGatewayChange(event.target.value)}>+ <select+ value={enterprise.gateway.jiuwenclaw_id}+ disabled={enterprise.contextSwitching}+ 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}@@ -299,7 +303,7 @@ export function SessionSidebar({</label><label>Agent(bot_id)- <select value={enterprise.selectedBot} onChange={event => enterprise.onBotChange(event.target.value)}>+ <select value={enterprise.selectedBot} disabled={enterprise.contextSwitching} 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}@@ -307,6 +311,8 @@ export function SessionSidebar({))}</select></label>+ {enterprise.contextSwitching && <div className="enterprise-context-popover__status">正在切换...</div>}+ {enterprise.contextError && <div className="enterprise-context-popover__error">{enterprise.contextError}</div>}<button type="button" className="enterprise-context-popover__logout" onClick={enterprise.onLogout}>注销登录</button>diff --git a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsxindex c197a4152c..1a8a67969d 100644--- a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx+++ b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx@@ -1,16 +1,27 @@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 = {+ jiuwenclaw_id: string;+ jiuwenclaw_name: string;+ gateway_endpoint: string | null;+};+export type EnterpriseAgent = { template_id: string; template_name: string; resource_id?: string };+export type EnterpriseContextSnapshot = {- user: { user_id: string; display_name: string };- org: { group_id: string; name: string };- orgs: { group_id: string; name: string }[];- gateway: { jiuwenclaw_id: string; jiuwenclaw_name: string; gateway_endpoint: string | null };- gateways: { jiuwenclaw_id: string; jiuwenclaw_name: string; gateway_endpoint: string | null }[];- agents: { template_id: string; template_name: string; resource_id?: string }[];+ user: EnterpriseUser;+ org: EnterpriseOrg;+ orgs: EnterpriseOrg[];+ gateway: EnterpriseGateway;+ gateways: EnterpriseGateway[];+ agents: EnterpriseAgent[];selectedBot: string;};export type EnterpriseContextValue = EnterpriseContextSnapshot & {+ contextError: string;+ contextSwitching: boolean;onOrgChange: (id: string) => void;onGatewayChange: (id: string) => void;onBotChange: (id: string) => void;diff --git a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjsindex a35178d406..6f31bde52b 100644--- a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs@@ -18,14 +18,14 @@ globalThis.localStorage = {globalThis.window = {__JIUWEN_USER_WEB_MODE__: 'personal',history: { replaceState() {} },- location: { pathname: '/', search: '' },+ location: { pathname: '/', search: '', replace() {} },};-const { EnterpriseEntry } = await import('../node_modules/.cache/user-web-entry/EnterpriseEntry.mjs');+const { EnterpriseEntry, chooseAgent, orderedContextCandidates } = 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')));+ return renderToStaticMarkup(React.createElement(EnterpriseEntry, null, React.createElement('div', { id: 'user-web-content' }, 'user web content')));}function resetBrowserState() {@@ -37,27 +37,60 @@ test('personal mode renders the standalone User Web without enterprise authenticresetBrowserState();const html = renderEntry('personal');- assert.match(html, /personal content/);- assert.doesNotMatch(html, /ENTERPRISE WORKSPACE|请从 Manager Web 进入/);+ assert.match(html, /user web content/);+ assert.doesNotMatch(html, /ENTERPRISE WORKSPACE/);});-test('enterprise mode rejects direct access without Manager Web context', () => {+test('enterprise mode redirects unauthenticated users instead of rendering User Web', () => {resetBrowserState();const html = renderEntry('enterprise');assert.match(html, /ENTERPRISE WORKSPACE/);- assert.match(html, /请从 Manager Web 进入/);- assert.doesNotMatch(html, /personal content/);- assert.doesNotMatch(html, /用户名|密码|登录工作空间/);+ assert.match(html, /正在前往登录页/);+ assert.doesNotMatch(html, /user web content/);});-test('enterprise mode renders the embedded User Web with Manager authentication and scope', () => {+test('enterprise mode 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';const html = renderEntry('enterprise');- assert.match(html, /personal content/);- assert.doesNotMatch(html, /请从 Manager Web 进入/);+ assert.match(html, /正在加载工作空间/);+ assert.doesNotMatch(html, /user web content/);+});++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 },+ ];+ 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'],+ ],+ );+});++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);});