JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(enterprise): align managed skill authorization flow
huben6e95ff0ac85f
diff --git a/.env.example b/.env.exampleindex 191e138512..7f4750213c 100644--- a/.env.example+++ b/.env.example@@ -79,9 +79,6 @@ GATEWAY_MANAGER_HTTP_URL=http://127.0.0.1:8765# Gateway 日志脱敏开关(true/false,默认 true;读仓库根 .env 或容器注入的环境变量)LOG_MASK_ENABLED=true-# Skill 动态授权开关(true/false,默认 false;声明了 skill_permissions.json 的技能加载时需审批)-# k8s 企业部署经 deploy/enterprise 的 agentserver-env ConfigMap 下发到 AgentServer 容器-SKILL_AUTHORIZATION_ENABLED=false# 设为 false 时仅输出控制台日志,不写本地文件(fluent-bit/vector 采集 stdout 时使用)# LOG_TO_FILE_ENABLED=truediff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.shindex 8dc6fdf2aa..6b68929b1b 100755--- a/deploy/enterprise/global_vars.sh+++ b/deploy/enterprise/global_vars.sh@@ -220,7 +220,6 @@ declare -A DEPLOY_VARS=(["REDIS_MODE"]="standalone"["RENDER_ONLY"]="false"["SECRET_CM_NAME"]="jiuwenclaw-secret-configmap"- ["SKILL_AUTHORIZATION_ENABLED"]="false"["TIMEZONE"]="Asia/Shanghai"["VECTOR_NAME"]="vector-receiver"["VECTOR_IMAGE"]="timberio/vector:0.40.0-alpine"diff --git a/deploy/enterprise/templates/agentserver.template.env b/deploy/enterprise/templates/agentserver.template.envindex f18143a29d..100269c1ce 100644--- a/deploy/enterprise/templates/agentserver.template.env+++ b/deploy/enterprise/templates/agentserver.template.env@@ -16,9 +16,6 @@ EXTENSION_DIRS=<<CLAW_POD_CODE_PATH>>/packages/jiuwenclaw-ee/agentserver/extensi# pod 内代码路径(与 gateway 对齐,便于排查时核对 EXTENSION_DIRS 渲染结果)CLAW_POD_CODE_PATH=<<CLAW_POD_CODE_PATH>>-# Skill 动态授权(默认关闭;开启后声明 skill_permissions.json 的技能加载时需审批)-SKILL_AUTHORIZATION_ENABLED=<<SKILL_AUTHORIZATION_ENABLED>>-# 数据库信息GATEWAY_DB_TYPE=<<DB_TYPE>>GATEWAY_DB_HOST=<<DB_HOST>>diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py b/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.pyindex cd9e8b91bf..f15e6b498b 100644--- a/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py+++ b/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py@@ -27,6 +27,7 @@from __future__ import annotationsimport logging+from collections.abc import Callablefrom typing import Anylogger = logging.getLogger(__name__)@@ -37,8 +38,13 @@ _AGENT_WIRING_MARKER = "_jiuwenswarm_skill_authz_wiring_installed"_CHILD_ASSEMBLED_ATTR = "_jiuwenswarm_skill_authz_scope"-def skill_authorization_enabled() -> bool:- """动态授权总开关;读取失败按关闭处理(fail-closed,对齐 0708)。"""+PermissionConfigProvider = Callable[[], dict[str, Any]]+++def skill_authorization_enabled(+ config_provider: PermissionConfigProvider | None = None,+) -> bool:+ """动态授权总开关;优先读取所属 Agent 的权限模板。"""try:from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (get_effective_permissions_config,@@ -47,7 +53,8 @@ def skill_authorization_enabled() -> bool:is_skill_authorization_enabled,)- return is_skill_authorization_enabled(get_effective_permissions_config())+ provider = config_provider or get_effective_permissions_config+ return is_skill_authorization_enabled(provider())except Exception: # noqa: BLE001logger.warning("[skill_authorization] subagent wiring flag read failed; preserve legacy path",@@ -56,13 +63,15 @@ def skill_authorization_enabled() -> bool:return False-def resolve_main_authorization_session() -> str | None:+def resolve_main_authorization_session(+ config_provider: PermissionConfigProvider | None = None,+) -> str | None:"""仅当功能开启且父 Context 为 main scope 时返回主会话 id(对齐 0708 语义)。子 Agent 任务可能继承父请求的授权 Context;只有 scope=="main" 的父 Context才允许装配委托授权链,杜绝任何形式的授权继承。"""- if not skill_authorization_enabled():+ if not skill_authorization_enabled(config_provider):return Nonetry:from openjiuwen.harness.security.skill_authorization import (@@ -174,6 +183,7 @@ def build_subagent_authorization_rails(skill_use_rail: Any | None = None,engine: Any | None = None,workspace_root: Any | None = None,+ config_provider: PermissionConfigProvider | None = None,) -> tuple[Any, ...]:"""装配产物:给子 Agent 追加的委托 rail 对。@@ -186,7 +196,14 @@ def build_subagent_authorization_rails(main_session_id = str(session_id or "").strip()if not scope or not main_session_id:return ()- if not skill_authorization_enabled():+ effective_config_provider = config_provider+ if effective_config_provider is None:+ from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (+ get_effective_permissions_config,+ )++ effective_config_provider = get_effective_permissions_config+ if not skill_authorization_enabled(effective_config_provider):logger.info("[skill_authorization] subagent wiring skipped scope=%s reason=disabled",scope,@@ -202,6 +219,9 @@ def build_subagent_authorization_rails(from jiuwenswarm.agents.harness.common.rails.subagent_skill_authorization_rail import (SubagentSkillAuthorizationRail,)+ from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (+ merge_session_permissions_overlay,+ )skill_resolver = Noneif skill_use_rail is not None:@@ -216,12 +236,15 @@ def build_subagent_authorization_rails(session_id=main_session_id,engine=engine,skill_resolver=skill_resolver,+ config_provider=effective_config_provider,+ session_config_merger=merge_session_permissions_overlay,)permission_rail = SubagentPermissionRail(agent_scope_id=scope,session_id=main_session_id,engine=engine,workspace_root=workspace_root,+ config_provider=effective_config_provider,)except Exception: # noqa: BLE001logger.warning(@@ -297,6 +320,8 @@ def attach_subagent_authorization(child: Any,agent_scope_id: str,session_id: str,+ *,+ config_provider: PermissionConfigProvider | None = None,) -> bool:"""把委托 rail 对挂到子 Agent 并接管其生命周期清理。@@ -327,6 +352,7 @@ def attach_subagent_authorization(skill_use_rail=_find_child_skill_use_rail(child),engine=engine,workspace_root=_child_workspace_root(child),+ config_provider=config_provider,)if not rails:return False@@ -344,7 +370,11 @@ def attach_subagent_authorization(return True-def install_subagent_authorization_wiring(agent: Any) -> bool:+def install_subagent_authorization_wiring(+ agent: Any,+ *,+ config_provider: PermissionConfigProvider | None = None,+) -> bool:"""包装父 Agent ``create_subagent``:子 Agent 创建时按需装配委托授权链。仅当父 Context 为 main scope(``resolve_main_authorization_session``)@@ -367,7 +397,7 @@ def install_subagent_authorization_wiring(agent: Any) -> bool:) -> Any:child = original_create(subagent_type, subsession_id, *args, **kwargs)try:- main_session_id = resolve_main_authorization_session()+ main_session_id = resolve_main_authorization_session(config_provider)except Exception: # noqa: BLE001logger.warning("[skill_authorization] subagent wiring scope resolve failed",@@ -380,6 +410,7 @@ def install_subagent_authorization_wiring(agent: Any) -> bool:child,str(subsession_id or ""),main_session_id,+ config_provider=config_provider,)except Exception: # noqa: BLE001 — 装配失败不得击穿子 Agent 创建logger.warning(diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 0c74c6705d..5b6219d96a 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -37,6 +37,7 @@"test:artifact-collection": "esbuild src/components/ArtifactsPanel/artifactCollection.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/artifact-collection/artifactCollection.mjs && node --test tests/artifactCollection.test.mjs","test:desktop-save": "esbuild src/utils/desktopSave.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/desktop-save/desktopSave.mjs && node --test tests/desktopSave.test.mjs","test:ask-user-submission": "tsc src/components/InteractionSlot/interactionSubmission.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/ask-user-submission --skipLibCheck --noEmitOnError && node --test tests/askUserSubmission.test.mjs",+ "test:skill-approval-presentation": "tsc src/components/ChatPanel/skillApprovalPresentation.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/skill-approval-presentation --skipLibCheck --noEmitOnError && node --test tests/skillApprovalPresentation.test.mjs","lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0","preview": "vite preview"},diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 1be41d41d7..d97374159b 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -1901,8 +1901,10 @@ function AppContent() {status?: UserAnswerStatus,) => {const currentSessionId = sessionIdRef.current;- if (!currentSessionId || currentSessionId === NEW_CONVERSATION_ID) return;- void sendUserAnswer(currentSessionId, requestId, answers, source, status);+ if (!currentSessionId || currentSessionId === NEW_CONVERSATION_ID) {+ return Promise.resolve();+ }+ return sendUserAnswer(currentSessionId, requestId, answers, source, status);}, [sendUserAnswer]);const handleLoadMoreHistory = useCallback(async () => {diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsxindex 3890a7c98c..fc64fd142d 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx@@ -18,7 +18,7 @@ import { classifyPrompt } from '../InteractionSlot/promptRouting';import { isValidSkillApprovalCard, SkillApprovalCard } from './SkillApprovalCard';interface InlineQuestionCardProps {- onSubmit: (requestId: string, answers: UserAnswer[], source?: string) => void;+ onSubmit: (requestId: string, answers: UserAnswer[], source?: string) => Promise<void>;}// 后端会给带选项的问题末尾追加一个「自定义输入」选项(interrupt_helpers._build_multi_questions)。@@ -168,7 +168,7 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {}if (skillApprovalCard) {- return <SkillApprovalCard onSubmit={onSubmit} card={skillApprovalCard} />;+ return <SkillApprovalCard key={pendingQuestion.request_id} onSubmit={onSubmit} card={skillApprovalCard} />;}const borderColor = isEvolutiondiff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsxindex a745300e50..c75c2b429b 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsx@@ -17,15 +17,27 @@* (与后端 `_build_interactive_input_from_answers` 对齐)。*/-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';+import { webRequest } from '../../services/webClient';import { useChatStore } from '../../stores';import type { SkillApprovalAction, SkillApprovalCardPayload } from '../../types';+import { shouldUnlockPendingApproval } from '../InteractionSlot/interactionSubmission';+import {+ buildSkillSourceDisplayNameMap,+ resolveSkillSourceDisplayName,+ shouldShowSkillTrustBadge,+ type SkillSourceDisplayNames,+} from './skillApprovalPresentation';interface SkillApprovalCardProps {- onSubmit: (requestId: string, answers: { selected_options: string[]; action?: SkillApprovalAction }[], source?: string) => void;+ onSubmit: (+ requestId: string,+ answers: { selected_options: string[]; action?: SkillApprovalAction }[],+ source?: string,+ ) => Promise<void>;card: SkillApprovalCardPayload | null;}@@ -36,6 +48,25 @@ const ACTION_WIRE_LABELS: Record<SkillApprovalAction, string> = {continue_without_overlay: '仅加载不授权',};+const sourceDisplayNameRequests = new Map<string, Promise<SkillSourceDisplayNames>>();++function fetchSkillSourceDisplayNames(sessionId: string): Promise<SkillSourceDisplayNames> {+ const cached = sourceDisplayNameRequests.get(sessionId);+ if (cached) return cached;++ const request = webRequest<{+ success?: boolean;+ providers?: Array<{ source_id?: unknown; display_name?: unknown }>;+ }>('skills.source.providers', { session_id: sessionId })+ .then(response => buildSkillSourceDisplayNameMap(response.success === false ? [] : response.providers))+ .catch(() => {+ sourceDisplayNameRequests.delete(sessionId);+ return new Map<string, string>();+ });+ sourceDisplayNameRequests.set(sessionId, request);+ return request;+}+/** 来源路径截断:只保留末尾两段,完整路径交给 title 悬停。 */function truncateSource(source: string): string {const parts = source.split(/[\\/]/).filter(Boolean);@@ -73,6 +104,21 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {const activeSessionId = useChatStore(s => s.activeSessionId);const pendingQuestion = useChatStore(s => s.runtimes[activeSessionId ?? '']?.pendingQuestion ?? null);const [submitted, setSubmitted] = useState(false);+ const [sourceDisplayName, setSourceDisplayName] = useState(card?.source ?? '');++ useEffect(() => {+ const sourceId = card?.source.trim() ?? '';+ setSourceDisplayName(sourceId);+ if (!sourceId || !activeSessionId || card?.trust === 'builtin') return undefined;++ let active = true;+ void fetchSkillSourceDisplayNames(activeSessionId).then(displayNames => {+ if (active) setSourceDisplayName(resolveSkillSourceDisplayName(sourceId, displayNames));+ });+ return () => {+ active = false;+ };+ }, [activeSessionId, card?.source, card?.trust]);const question = pendingQuestion?.questions[0];const availableActions = useMemo((): SkillApprovalAction[] => {@@ -86,23 +132,32 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {}, [card, question]);const handleAction = useCallback(- (action: SkillApprovalAction) => {+ async (action: SkillApprovalAction) => {if (!pendingQuestion || submitted) return;+ const requestId = pendingQuestion.request_id;+ const sessionId = activeSessionId;setSubmitted(true);- onSubmit(pendingQuestion.request_id, [{ selected_options: [ACTION_WIRE_LABELS[action]], action }], pendingQuestion.source);- const sid = useChatStore.getState().activeSessionId;- if (sid) {- useChatStore.getState().setPendingQuestion(sid, null);+ await onSubmit(+ requestId,+ [{ selected_options: [ACTION_WIRE_LABELS[action]], action }],+ pendingQuestion.source,+ );+ const state = useChatStore.getState();+ const currentRequestId = sessionId+ ? state.getRuntime(sessionId)?.pendingQuestion?.request_id+ : null;+ if (shouldUnlockPendingApproval(currentRequestId, requestId)) {+ setSubmitted(false);}},- [pendingQuestion, submitted, onSubmit],+ [activeSessionId, pendingQuestion, submitted, onSubmit],);if (!pendingQuestion) {return null;}- const trustLabel = card?.trust === 'builtin' ? t('chatUi.skillApproval.trustBuiltin') : t('chatUi.skillApproval.trustOther');+ const showTrustBadge = shouldShowSkillTrustBadge(card?.trust);const versionLabel = card?.version || t('chatUi.skillApproval.versionLocal');const cachedDecisionLabel = card?.cached_decision === 'session' ? t('chatUi.skillApproval.cachedSession') : t('chatUi.skillApproval.cachedLocal');@@ -160,15 +215,15 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {{t('chatUi.skillApproval.title')}{card ? `:${card.skill_name}` : ''}</span>- {card && (+ {card && showTrustBadge && (<spanclassName="text-[10px] px-1.5 py-0.5 rounded"style={{- color: card.trust === 'builtin' ? 'var(--color-feedback-success)' : 'var(--color-brand-secondary)',- border: `1px solid ${card.trust === 'builtin' ? 'var(--color-feedback-success)' : 'var(--color-brand-secondary)'}`,+ color: 'var(--color-feedback-success)',+ border: '1px solid var(--color-feedback-success)',}}>- {trustLabel}+ {t('chatUi.skillApproval.trustBuiltin')}</span>)}</div>@@ -178,8 +233,8 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {<>{/* 身份信息 */}<div className="text-xs leading-relaxed" style={{ color: 'var(--color-text-secondary)' }}>- <div title={card.source}>- {t('chatUi.skillApproval.source')}:<code>{truncateSource(card.source)}</code>({trustLabel}) {t('chatUi.skillApproval.version')}:+ <div title={sourceDisplayName === card.source ? card.source : `${sourceDisplayName} (${card.source})`}>+ {t('chatUi.skillApproval.source')}:<code>{truncateSource(sourceDisplayName || card.source)}</code> {t('chatUi.skillApproval.version')}:{versionLabel}</div><div className="text-[10px]" style={{ color: 'var(--color-text-secondary)', opacity: 0.75 }}>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex a90fc8ef37..b32d22894a 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -83,7 +83,7 @@ interface ChatPanelProps {answers: UserAnswer[],source?: string,status?: UserAnswerStatus,- ) => void;+ ) => Promise<void>;onExportShare?: () => void | Promise<void>;isExportingShare?: boolean;canExportShare?: boolean;diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.tsnew file mode 100644index 0000000000..30e1a0c059--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.ts@@ -0,0 +1,29 @@+export type SkillSourceDisplayNames = ReadonlyMap<string, string>;++type SkillSourceProviderSummary = {+ source_id?: unknown;+ display_name?: unknown;+};++export function buildSkillSourceDisplayNameMap(+ providers: readonly SkillSourceProviderSummary[] | undefined,+): SkillSourceDisplayNames {+ const displayNames = new Map<string, string>();+ for (const provider of providers ?? []) {+ const sourceId = typeof provider.source_id === 'string' ? provider.source_id.trim() : '';+ const displayName = typeof provider.display_name === 'string' ? provider.display_name.trim() : '';+ if (sourceId && displayName) displayNames.set(sourceId, displayName);+ }+ return displayNames;+}++export function resolveSkillSourceDisplayName(+ sourceId: string,+ displayNames: SkillSourceDisplayNames,+): string {+ return displayNames.get(sourceId) || sourceId;+}++export function shouldShowSkillTrustBadge(trust: string | undefined): boolean {+ return trust === 'builtin';+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.ts b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.tsindex 68cea4c89f..8a762424f1 100644--- a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.ts@@ -30,3 +30,11 @@ export function buildEmptyAskUserAnswers(questions: Pick<Question, 'question'>[]custom_input: '',}));}++/** Re-enable an approval card when its request is still pending after submission. */+export function shouldUnlockPendingApproval(+ pendingRequestId: string | null | undefined,+ submittedRequestId: string,+): boolean {+ return pendingRequestId === submittedRequestId;+}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 4b8ec4d681..89bf8b2108 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -2317,7 +2317,6 @@"skillApproval": {"title": "Skill load approval","trustBuiltin": "builtin",- "trustOther": "unofficial","versionLocal": "local (no version)","source": "Source","version": "Version",@@ -2333,7 +2332,7 @@"approveSession": "Allow for session","approveSessionDesc": "Approval cached for this session; revoked when the skill ends","continueWithout": "Continue without extra permissions",- "continueWithoutDesc": "Load the skill under existing permissions"+ "continueWithoutDesc": "Load the skill without granting additional permissions"}},"share": {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex f9acad7b73..d8752942c6 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -2304,7 +2304,6 @@"skillApproval": {"title": "Skill 加载审批","trustBuiltin": "内置",- "trustOther": "非官方","versionLocal": "本地(无版本)","source": "来源","version": "版本",@@ -2320,7 +2319,7 @@"approveSession": "会话内允许","approveSessionDesc": "会话内保留审批记录,Skill 结束后失活","continueWithout": "仅加载不授权",- "continueWithoutDesc": "仅加载 Skill,不授予额外权限(按原有权限运行)"+ "continueWithoutDesc": "仅加载 Skill,不授予额外权限"}},"share": {diff --git a/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjs b/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjsindex 98270dad69..cae685e644 100644--- a/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjs@@ -5,6 +5,7 @@ import {buildEmptyAskUserAnswers,hasAskUserInput,resolveAskUserStatus,+ shouldUnlockPendingApproval,} from '../node_modules/.cache/ask-user-submission/components/InteractionSlot/interactionSubmission.js';test('preserves explicit answered even when answers are empty', () => {@@ -36,3 +37,9 @@ test('whole-interaction cancellation creates only empty answer shells', () => {{ question: 'Second?', selected_options: [], custom_input: '' },]);});++test('failed approval submission unlocks only the same pending request', () => {+ assert.equal(shouldUnlockPendingApproval('approval-1', 'approval-1'), true);+ assert.equal(shouldUnlockPendingApproval(null, 'approval-1'), false);+ assert.equal(shouldUnlockPendingApproval('approval-2', 'approval-1'), false);+});diff --git a/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjs b/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjsnew file mode 100644index 0000000000..4172851b51--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjs@@ -0,0 +1,33 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ buildSkillSourceDisplayNameMap,+ resolveSkillSourceDisplayName,+ shouldShowSkillTrustBadge,+} from '../node_modules/.cache/skill-approval-presentation/components/ChatPanel/skillApprovalPresentation.js';++test('registered source display name is used without changing its source id', () => {+ const displayNames = buildSkillSourceDisplayNameMap([+ { source_id: 'customer-source', display_name: 'Customer Skill Center' },+ ]);++ assert.equal(+ resolveSkillSourceDisplayName('customer-source', displayNames),+ 'Customer Skill Center',+ );+ assert.equal(resolveSkillSourceDisplayName('unknown-source', displayNames), 'unknown-source');+});++test('blank source display name falls back to the stable source id', () => {+ const displayNames = buildSkillSourceDisplayNameMap([+ { source_id: 'customer-source', display_name: ' ' },+ ]);++ assert.equal(resolveSkillSourceDisplayName('customer-source', displayNames), 'customer-source');+});++test('only builtin skills display a trust badge', () => {+ assert.equal(shouldShowSkillTrustBadge('builtin'), true);+ assert.equal(shouldShowSkillTrustBadge('other'), false);+});diff --git a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.pyindex c906befc97..189d03001c 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py@@ -81,6 +81,7 @@ _WEB_FULL_PAYLOAD_EVENT_TYPES = frozenset("context.usage","context.compression_state","chat.ask_user_question",+ "chat.ask_user_question_expired","chat.subtask_update","chat.symphony_status","chat.notice",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 5251034788..46100a641b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -2112,6 +2112,7 @@ class JiuWenSwarmDeepAdapter:self._startup_config_base: dict[str, Any] | None = Noneself._model_config_source: str = "config.yaml"self._enterprise_config: Any = None+ self._enterprise_config_resource_id: str | None = Noneself._config_cache: dict[str, Any] = {}self._filesystem_rail: SysOperationRail | None = Noneself._progressive_tool_rail: ProgressiveToolRail | None = None@@ -2433,6 +2434,17 @@ class JiuWenSwarmDeepAdapter:sid = str(session_id or "").strip()return sid or "default"+ @staticmethod+ def _enterprise_resource_id_from_request(request: AgentRequest | None) -> str:+ """Return the authenticated Agent resource id carried by a request."""+ if request is None:+ return ""+ from jiuwenswarm.common.request_identity import web_routing_identity++ metadata = request.metadata if isinstance(request.metadata, dict) else None+ identity = web_routing_identity(metadata)+ return str(identity.get("bot_id") or "").strip()+def copy_tenant_env_bindings_from(self, source: "JiuWenSwarmDeepAdapter") -> None:"""Copy tenant tip namespace bindings from another adapter instance."""self._env_agent_id = getattr(source, "_env_agent_id", "default")@@ -2698,6 +2710,33 @@ class JiuWenSwarmDeepAdapter:lock = self._session_adapter_locks.setdefault(sid, asyncio.Lock())async with lock:existing = self._session_adapters.get(sid)+ requested_resource_id = self._enterprise_resource_id_from_request(request)+ existing_resource_id = str(+ getattr(existing, "_enterprise_config_resource_id", None) or ""+ ).strip()+ enterprise_resource_changed = bool(+ requested_resource_id+ and existing_resource_id != requested_resource_id+ )+ if (+ existing is not None+ and is_enterprise()+ and enterprise_resource_changed+ ):+ logger.info(+ "[JiuWenSwarmDeepAdapter] rebuilding session adapter for enterprise "+ "identity: session_id=%s previous_resource_id=%s resource_id=%s",+ sid,+ existing_resource_id or "<unbound>",+ requested_resource_id,+ )+ await existing.cleanup()+ self._drop_session_adapter_cache_entry(+ sid,+ remove_lock=False,+ remove_runtime_state=False,+ )+ existing = Noneif existing is not None:await self._reload_session_adapter_if_stale(sid, existing)self._touch_session_adapter(sid)@@ -4911,6 +4950,7 @@ class JiuWenSwarmDeepAdapter:"""if not is_enterprise():self._enterprise_config = None+ self._enterprise_config_resource_id = Nonereturntry:from jiuwenswarm.server.runtime.enterprise_config import (@@ -4928,6 +4968,9 @@ class JiuWenSwarmDeepAdapter:DEFAULT_AGENT_LOAD_SLOTS,)self._enterprise_config = loaded+ self._enterprise_config_resource_id = (+ self._enterprise_resource_id_from_request(request) or None+ )self._agent_permissions_body = resolve_permissions_body_from_enterprise(loaded)if loaded is not None and self._skill_manager is not None:try:@@ -5949,7 +5992,10 @@ class JiuWenSwarmDeepAdapter:install_subagent_authorization_wiring,)- install_subagent_authorization_wiring(self._instance)+ install_subagent_authorization_wiring(+ self._instance,+ config_provider=self._resolve_skill_authorization_base_config,+ )except Exception:logger.warning("[JiuWenSwarmDeepAdapter] subagent authorization wiring failed",@@ -6892,7 +6938,7 @@ class JiuWenSwarmDeepAdapter:prebuilt_dirs_provider=self._prebuilt_skill_dirs_snapshot,builtin_dirs_provider=lambda: [get_builtin_skills_dir()],skill_identity_refresher=self._refresh_skill_identity,- config_provider=get_effective_permissions_config,+ config_provider=self._resolve_skill_authorization_base_config,session_config_merger=lambda config, session_id: (merge_session_permissions_overlay(config,@@ -8279,6 +8325,14 @@ class JiuWenSwarmDeepAdapter:return get_base_permissions_config()return get_effective_permissions_config(session_id=session_id)+ def _resolve_skill_authorization_base_config(self) -> dict[str, Any]:+ """Return this Agent's permission baseline without relying on ContextVar propagation.++ An empty explicit session id keeps session overlays out of the provider result;+ ``SkillAuthorizationRail`` merges the target session overlay separately.+ """+ return self._resolve_permission_config_for_agent(session_id="")+def _build_permission_rail_for_agent(self,config: dict[str, Any] | None = None,diff --git a/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py b/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.pyindex 757a706493..8df231fce7 100644--- a/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py+++ b/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+from types import SimpleNamespaceimport pytest@@ -170,3 +171,50 @@ async def test_session_child_reuses_authoritative_config_snapshot() -> None:assert await adapter._get_or_create_session_adapter("sess_a") is childassert calls == [tenant_config]+++async def test_enterprise_request_rebuilds_session_child_created_without_identity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A requestless helper must not leave the live session on YAML permissions."""+ monkeypatch.setattr(interface_deep_module, "is_enterprise", lambda: True)+ parent = JiuWenSwarmDeepAdapter()++ class FakeChild:+ def __init__(self, resource_id: str | None = None) -> None:+ self._enterprise_config_resource_id = resource_id+ self.cleaned = False+ self.created_with = None++ async def cleanup(self) -> None:+ self.cleaned = True++ async def create_instance(self, config=None, **_kwargs) -> None:+ self.created_with = config++ async def start_interaction(self, session_id=None) -> None:+ del session_id++ stale = FakeChild()+ fresh = FakeChild()+ parent._session_adapters = {"sess_a": stale}+ parent._new_session_scoped_adapter = lambda _sid: fresh++ async def _reload_noop(_sid, _child) -> None:+ return None++ parent._reload_session_adapter_if_stale = _reload_noop+ parent._touch_session_adapter = lambda _sid: None+ request = SimpleNamespace(+ metadata={"routing": {"bot_id": "agent-resource-1"}},+ )++ result = await parent._get_or_create_session_adapter(+ "sess_a",+ request=request,+ )++ assert result is fresh+ assert stale.cleaned is True+ assert fresh.created_with["request"] is requestdiff --git a/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.py b/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.pyindex 196b340582..c7407c186e 100644--- a/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.py+++ b/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.py@@ -97,6 +97,37 @@ async def test_refresh_enterprise_config_restores_cache_when_load_fails(assert len(adapter._enterprise_config.mcp) == 1+def test_skill_authorization_rail_uses_agent_template_without_request_context(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep++ monkeypatch.setattr(+ interface_deep,+ "get_effective_permissions_config",+ lambda **_kwargs: {+ "enabled": True,+ "skill_authorization": {"enabled": False},+ "defaults": {"*": "allow"},+ },+ )+ adapter = object.__new__(JiuWenSwarmDeepAdapter)+ adapter._agent_permissions_body = {+ "enabled": True,+ "skill_authorization": {"enabled": True},+ "defaults": {"*": "ask"},+ }+ adapter._enterprise_config = None+ adapter._permission_rail = None+ adapter._skill_rail = None++ rail = adapter._build_skill_authorization_rail()++ assert rail is not None+ assert rail._feature_enabled() is True+ assert rail._base_effective_config("session-1")["defaults"] == {"*": "ask"}++@pytest.mark.asyncioasync def test_load_enterprise_config_keeps_cache_when_gateway_raises(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit_tests/agentserver/test_subagent_skill_authorization_config.py b/tests/unit_tests/agentserver/test_subagent_skill_authorization_config.pynew file mode 100644index 0000000000..fa0c3cc5f0--- /dev/null+++ b/tests/unit_tests/agentserver/test_subagent_skill_authorization_config.py@@ -0,0 +1,76 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Subagent Skill authorization must use the owning Agent's permission template."""++from __future__ import annotations++from typing import Any++import pytest++from openjiuwen.harness.security.skill_authorization import (+ reset_skill_authorization_context,+ setup_skill_authorization_context,+)++from jiuwenswarm.agents.harness.common.rails.permissions import config_loader+from jiuwenswarm.agents.harness.common.tools.subagent_executor.authorization import (+ install_subagent_authorization_wiring,+)+++class _ChildAgent:+ def __init__(self) -> None:+ self._initialized = False+ self.rails: list[Any] = []++ def add_rail(self, rail: Any) -> None:+ self.rails.append(rail)++ def find_rails_by_type(self, _rail_types: tuple[type, ...]) -> list[Any]:+ return []+++class _ParentAgent:+ def create_subagent(+ self,+ _subagent_type: str,+ _subsession_id: str,+ *_args: Any,+ **_kwargs: Any,+ ) -> _ChildAgent:+ return _ChildAgent()+++def test_subagent_wiring_uses_injected_agent_permission_template(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A management template must enable both child authorization rails."""+ monkeypatch.setattr(+ config_loader,+ "get_effective_permissions_config",+ lambda: {+ "enabled": True,+ "skill_authorization": {"enabled": False},+ },+ )+ parent = _ParentAgent()++ def template_provider() -> dict[str, Any]:+ return {+ "enabled": True,+ "skill_authorization": {"enabled": True},+ }++ token = setup_skill_authorization_context("session-1", "main")+ try:+ assert install_subagent_authorization_wiring(+ parent,+ config_provider=template_provider,+ )+ child = parent.create_subagent("general", "child-1")+ finally:+ reset_skill_authorization_context(token)++ assert len(child.rails) == 2+ assert child.rails[0]._feature_enabled() is True+ assert child.rails[1]._enabled() is Truediff --git a/tests/unit_tests/channel/test_web_channel_symphony_status.py b/tests/unit_tests/channel/test_web_channel_symphony_status.pyindex c5b6a4e0d2..ea729fbf3a 100644--- a/tests/unit_tests/channel/test_web_channel_symphony_status.py+++ b/tests/unit_tests/channel/test_web_channel_symphony_status.py@@ -391,6 +391,33 @@ async def test_web_channel_routes_rpc_response_by_request_ws_id():await channel.unregister_ws(other_client)+def test_web_channel_preserves_ask_user_question_expired_payload():+ payload = {+ "event_type": "chat.ask_user_question_expired",+ "request_id": "approval-1",+ "source": "subagent_skill_load",+ "agent_scope_id": "child-agent",+ "reason": "timeout",+ }+ msg = Message(+ id="transport-1",+ type="event",+ channel_id="web",+ session_id="sess-skill",+ params={},+ timestamp=0.0,+ ok=True,+ payload=payload,+ )++ assert WebChannel._build_event_payload(+ msg, "chat.ask_user_question_expired"+ ) == {+ **payload,+ "session_id": "sess-skill",+ }++@pytest.mark.asyncioasync def test_web_channel_routes_event_by_request_ws_id_before_session_bucket():channel = WebChannel(WebChannelConfig(enabled=True), RobotMessageRouter())