JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(web): 技能面板体验优化
hubene56f5e48292e
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 993138e859..a1d60cbd07 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -15,6 +15,7 @@"test:presentation-preview": "esbuild src/components/ArtifactsPanel/pptxPresentationParser.ts src/components/ArtifactsPanel/pptxPreviewModel.ts src/components/ArtifactsPanel/ooxmlArchiveLimits.ts src/components/ArtifactsPanel/filePreviewModel.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/presentation-preview && node --test tests/presentationPreview.test.mjs","test:tool-result-lifecycle": "tsc src/stores/toolResultLifecycle.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/tool-result-lifecycle --skipLibCheck --noEmitOnError && node --test tests/toolResultLifecycle.test.mjs","test:team-panel-state": "tsc src/features/teamPanelStateNormalize.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/team-panel-state --skipLibCheck --noEmitOnError && node --test tests/teamPanelState.test.mjs",+ "test:skill-panel-state": "tsc src/features/mainNavigationState.ts src/components/SkillPanel/skillListRequest.ts src/features/EnterpriseSkillSourcePanel/installMetadata.ts src/features/EnterpriseSkillSourcePanel/sourceAvailability.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/skill-panel-state --skipLibCheck --noEmitOnError && node --test tests/skillPanelState.test.mjs","test:create-conversation-session": "tsc src/multi-session/state/createConversationSession.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/create-conversation-session --skipLibCheck --noEmitOnError && node --test tests/createConversationSession.test.mjs","test:cron-wake-offset": "tsc src/components/CronPanel/cronWakeOffset.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/cron-wake-offset --skipLibCheck --noEmitOnError && node --test tests/cronWakeOffset.test.mjs","test:cron-project-display": "tsc src/components/CronPanel/cronProjectDisplay.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/cron-project-display --skipLibCheck --noEmitOnError && node --test tests/cronProjectDisplay.test.mjs",diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex b33069bd86..5d824fbf4c 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -62,6 +62,12 @@ import {useCronStore,} from './stores';import { useChatRoute } from './multi-session/routing/useChatRoute';+import {+ MAIN_NAV_STORAGE_KEY,+ parseStoredMainNav,+ resolveMainNavAfterRoute,+ type MainNavKey,+} from './features/mainNavigationState';import { ConversationSidebar, type NewConversationOptions } from './multi-session/sidebar/ConversationSidebar';import { DeleteDialog } from './multi-session/dialogs/Dialogs';import {@@ -108,8 +114,6 @@ function shouldPreviewModelSetupGuide(): boolean {return PREVIEW_MODEL_SETUP_GUIDE;}-type MainNavKey = 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'history' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';-type LoadedHistoryPage = {pageIdx: number;totalPages: number;@@ -273,6 +277,10 @@ const HISTORY_PRELOAD_MAX_WAIT_MS = 1500;function AppContent() {const { t, i18n } = useTranslation();const { route, navigate } = useChatRoute();+ const routeKey = route.kind === 'chat-session'+ ? `chat-session:${route.sessionId}`+ : route.kind;+ const previousRouteKeyRef = useRef(routeKey);const tRef = useRef(t);// 优先使用存储的会话 ID,避免每次刷新创建新会话const [sessionId, setSessionId] = useState<string>(() => {@@ -284,7 +292,18 @@ function AppContent() {const cronJobPullSyncEnabled = enterpriseMode && getWebTransport() === 'http';useCronJobSync(cronJobPullSyncEnabled);const enterpriseBlockedNav = new Set<MainNavKey>(ENTERPRISE_HIDDEN_NAV_ITEMS);- const [activeNav, setActiveNav] = useState<MainNavKey>('chat');+ const [activeNav, setActiveNav] = useState<MainNavKey>(() => {+ let stored: string | null = null;+ try {+ stored = window.sessionStorage.getItem(MAIN_NAV_STORAGE_KEY);+ } catch {+ // Storage may be unavailable in private/locked-down browser contexts.+ }+ return parseStoredMainNav(stored, {+ blocked: enterpriseMode ? ENTERPRISE_HIDDEN_NAV_ITEMS : [],+ updaterEnabled: FEATURE_APP_UPDATER_UI,+ });+ });const [serverConfig, setServerConfig] = useState<Record<string, unknown> | null>(null);const [configError, setConfigError] = useState<string | null>(null);const [initialDataLoaded, setInitialDataLoaded] = useState(false);@@ -301,8 +320,8 @@ function AppContent() {const [proactiveToastMessage, setProactiveToastMessage] = useState('');const [securityAlertVisible, setSecurityAlertVisible] = useState(false);const [securityAlertContent, setSecurityAlertContent] = useState('');- const [hasVisitedSkills, setHasVisitedSkills] = useState(false);- const [hasVisitedChannels, setHasVisitedChannels] = useState(false);+ const [hasVisitedSkills, setHasVisitedSkills] = useState(activeNav === 'skills');+ const [hasVisitedChannels, setHasVisitedChannels] = useState(activeNav === 'channels');const [sidebarMorePanelOpen, setSidebarMorePanelOpen] = useState(false);const [modelSetupGuideStep, setModelSetupGuideStep] = useState<ModelSetupGuideStep | null>(null);const [modelSetupGuideManual, setModelSetupGuideManual] = useState(false);@@ -320,6 +339,14 @@ function AppContent() {tRef.current = t;}, [t]);+ useEffect(() => {+ try {+ window.sessionStorage.setItem(MAIN_NAV_STORAGE_KEY, activeNav);+ } catch {+ // Keep navigation functional when storage is unavailable.+ }+ }, [activeNav]);+useEffect(() => {if (activeNav !== 'configpanel') {setConfigInitialExpandGroup(null);@@ -344,7 +371,10 @@ function AppContent() {useEffect(() => {const handler = (e: Event) => {const nav = (e as CustomEvent<MainNavKey>).detail;- if (nav && !(enterpriseMode && enterpriseBlockedNav.has(nav))) setActiveNav(nav);+ if (!nav || (enterpriseMode && enterpriseBlockedNav.has(nav))) return;+ setActiveNav(nav);+ if (nav === 'skills') setHasVisitedSkills(true);+ if (nav === 'channels') setHasVisitedChannels(true);};window.addEventListener('jiuwen:nav', handler);return () => window.removeEventListener('jiuwen:nav', handler);@@ -419,10 +449,16 @@ function AppContent() {} = useTeamPanelState();useEffect(() => {+ const previousRouteKey = previousRouteKeyRef.current;+ previousRouteKeyRef.current = routeKey;+ setActiveNav(current => resolveMainNavAfterRoute(current, {+ previousRouteKey,+ routeKey,+ routeKind: route.kind,+ }));if (route.kind === 'chat-session') {sessionIdRef.current = route.sessionId;setSessionId(route.sessionId);- setActiveNav('chat');} else if (route.kind === 'chat-new') {if (window.location.pathname !== '/chat/new') navigate({ kind: 'chat-new' }, { replace: true });if (preserveSelectedProjectOnChatNewRef.current) {@@ -432,10 +468,9 @@ function AppContent() {}sessionIdRef.current = 'new';setSessionId('new');- setActiveNav('chat');setTeamAreaExpanded(false);}- }, [navigate, route, setTeamAreaExpanded]);+ }, [navigate, route, routeKey, setTeamAreaExpanded]);useEffect(() => {ensureSessionRuntimes(sessionId);diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsxindex a53ebbd331..df50648fb7 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx@@ -24,9 +24,7 @@ import { webRequest } from '../../services/webClient';import { useEnterpriseContext } from '../../services/enterpriseContext';import { isClickOutside } from './clickOutside';import { EditableCombobox } from './EditableCombobox';--type MainNavKey =- 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'history' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';+import type { MainNavKey } from '../../features/mainNavigationState';interface SessionSidebarProps {activeNav: MainNavKey;diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsxindex cab7811dd3..d53b79f078 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx@@ -11,11 +11,15 @@ import { SourceManagerModal } from "../../features/SourceManagerModal";import { SkillNetSearchModal } from "../../features/SkillNetSearchModal";import { ClawHubSearchModal } from "../../features/ClawHubSearchModal";import { TeamSkillsHubModal } from "../../features/TeamSkillsHubModal";-import { EnterpriseSkillSourcePanel } from "../../features/EnterpriseSkillSourcePanel";+import { EnterpriseSkillSourcePanel, fetchEnterpriseSkillSources } from "../../features/EnterpriseSkillSourcePanel";+import { resolveEnterpriseSourceCount } from "../../features/EnterpriseSkillSourcePanel/sourceAvailability";+import { skillPresentationName } from "../../features/EnterpriseSkillSourcePanel/installMetadata";import { Pagination } from "../common/Pagination";+import { ConfirmDialog } from "../common/ConfirmDialog";import { OnlineSkillSearchPanel } from "../../features/OnlineSkillSearchPanel";import { SkillEvolutionModal } from "../../features/SkillEvolutionModal";import { normalizeSkillNetUrl } from "../../utils/skillNetUrl";+import { buildSkillListParams, LatestSkillListRequest, shouldFetchSkillList } from "./skillListRequest";import { getSkillAvatar } from "../../utils/skillAvatar";import { SkillGraphPanel, type SkillGraphPanelHandle } from "../SkillGraphPanel";import { MarkdownRenderer } from "../MarkdownRenderer";@@ -610,6 +614,8 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:const [mySkillsSubTab, setMySkillsSubTab] = useState<"all" | "enabled" | "disabled" | "builtin" | "prebuilt" | "user">("all");const [mySkillsPage, setMySkillsPage] = useState(1);const [marketplaceSubTab, setMarketplaceSubTab] = useState<"builtin" | "swarmskills" | "online">("builtin");+ // 企业版:技能源为空时不展示 SwarmSkills 入口(null=未知,加载中先展示)+ const [enterpriseSourceCount, setEnterpriseSourceCount] = useState<number | null>(null);const [searchTrigger, setSearchTrigger] = useState(0);const [skills, setSkills] = useState<SkillItem[]>([]);const [plugins, setPlugins] = useState<InstalledPluginItem[]>([]);@@ -617,7 +623,9 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:const [search, setSearch] = useState("");const [debouncedSearch, setDebouncedSearch] = useState("");const searchDebounceRef = useRef<number | null>(null);- const prevIsActiveRef = useRef(isActive);+ const previousListContextRef = useRef<string | null>(null);+ const previousListSessionRef = useRef(sessionId);+ const skillListRequestsRef = useRef(new LatestSkillListRequest());/** 首次列表加载成功后置 true:刷新失败(如瞬态 SCOPE_FULL_TIMEOUT)保留旧列表,不清空页面 */const skillsLoadedRef = useRef(false);const [selectedSkill, setSelectedSkill] = useState<SkillDetail | null>(null);@@ -625,6 +633,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:const [detailState, setDetailState] = useState<LoadState>("idle");const [actionTarget, setActionTarget] = useState<string | null>(null);const [message, setMessage] = useState<string | null>(null);+ const [pendingUninstall, setPendingUninstall] = useState<{ name: string; displayName: string; origin?: string } | null>(null);const [messageType, setMessageType] = useState<"success" | "error" | "loading" | null>(null);const messageTimerRef = useRef<number | null>(null);const retrievalPollRef = useRef<number | null>(null);@@ -643,6 +652,21 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:const [retrievalShowExistingIndexFailureNotice, setRetrievalShowExistingIndexFailureNotice] = useState(false);const [retrievalLoading, setRetrievalLoading] = useState<"idle" | "status" | "tree" | "build" | "cancel">("idle");+ // 企业版:加载技能源数量,为空时隐藏 SwarmSkills 入口+ useEffect(() => {+ if (!readOnly) return;+ let cancelled = false;+ setEnterpriseSourceCount(null);+ void fetchEnterpriseSkillSources(sessionId).then((sources) => {+ if (!cancelled) {+ setEnterpriseSourceCount(current => resolveEnterpriseSourceCount(current, sources));+ }+ });+ return () => {+ cancelled = true;+ };+ }, [readOnly, sessionId]);+useEffect(() => {return () => {if (messageTimerRef.current !== null) {@@ -743,6 +767,11 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:[installedSkillMap, skills]);+ const enterpriseInstalledOrigins = useMemo(+ () => new Set(skills.filter(skill => skill.installed === true && skill.origin).map(skill => skill.origin!)),+ [skills],+ );+/** 已安装技能的来源 URL(规范化),与 SkillNet 搜索结果的 skill_url 匹配 */const installedSkillOrigins = useMemo(() => {const set = new Set<string>();@@ -828,6 +857,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:}, []);const fetchSkills = useCallback(async (refreshMarketplaces = false) => {+ const requestId = skillListRequestsRef.current.begin();setListState("loading");try {const data = await webRequest<{@@ -835,16 +865,14 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:plugins?: InstalledPluginItem[];}>("skills.list",- {- with_installed: true,- ...(refreshMarketplaces ? { refresh_marketplaces: true } : {}),- },+ buildSkillListParams(sessionId, refreshMarketplaces),{timeoutMs: refreshMarketplaces? SKILLS_FETCH_TIMEOUT_REFRESH_MS: SKILLS_FETCH_TIMEOUT_NORMAL_MS,});+ if (!skillListRequestsRef.current.isLatest(requestId)) return;setSkills((data.skills || []).map(normalizeSkillItem));setPlugins(data.plugins || []);skillsLoadedRef.current = true;@@ -855,10 +883,11 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:}} catch (error) {console.error(error);+ if (!skillListRequestsRef.current.isLatest(requestId)) return;// 已有成功数据时保留旧列表(stale-while-error),避免页签切换期间瞬态失败清空整个页面setListState(skillsLoadedRef.current ? "success" : "error");}- }, [fetchMarketplaces, readOnly, withSession]);+ }, [fetchMarketplaces, readOnly, sessionId]);const fetchSkillDetail = useCallback(async (skillName: string, origin?: string) => {@@ -939,23 +968,34 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:}}, [i18n.language, withSession]);- // 当左边栏切换到技能页面时,或切换到"我的技能"页签时,调用 list 接口+ // 首次挂载、重新进入技能页、切回「我的技能」或切其子页签时刷新一次列表。+ // 用 context 去重,避免首次挂载时两个 effect 同时发出 skills.list。useEffect(() => {- const prevIsActive = prevIsActiveRef.current;-- // 场景1:从其他页面切换到技能页面(isActive 变为 true)- if (isActive && !prevIsActive) {- fetchSkills();+ const previousContext = previousListContextRef.current;+ const sessionChanged = previousListSessionRef.current !== sessionId;+ const context = !isActive+ ? "inactive"+ : activeTab === "my"+ ? `my:${mySkillsSubTab}`+ : activeTab;+ if (sessionChanged) {+ skillListRequestsRef.current.begin();+ skillsLoadedRef.current = false;+ setSkills([]);+ setPlugins([]);}-- // 场景2:在技能页面内切换到"我的技能"页签(isActive 保持 true,activeTab 变化)- if (isActive && prevIsActive && activeTab === "my") {- fetchSkills();+ if (shouldFetchSkillList({+ isActive,+ activeTab,+ previousContext,+ currentContext: context,+ sessionChanged,+ })) {+ void fetchSkills();}-- // 更新 ref- prevIsActiveRef.current = isActive;- }, [isActive, activeTab, fetchSkills]);+ previousListContextRef.current = context;+ previousListSessionRef.current = sessionId;+ }, [isActive, activeTab, mySkillsSubTab, fetchSkills, sessionId]);useEffect(() => {if (readOnly) return;@@ -1260,43 +1300,46 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:}}, [fetchSkills, fetchSkillDetail, t, withSession]);- const handleUninstall = useCallback(- async (pluginName: string, origin?: string) => {- if (!pluginName) return;- const confirmed = window.confirm(t('skills.uninstallConfirm', { pluginName }));- if (!confirmed) return;+ const handleUninstall = useCallback((pluginName: string, origin?: string) => {+ if (!pluginName) return;+ const skill = skills.find(item => origin ? item.origin === origin : item.name === pluginName);+ const displayName = skill ? skillPresentationName(skill) : pluginName;+ setPendingUninstall({ name: pluginName, displayName, origin });+ }, [skills]);- setActionTarget(pluginName);- setMessage(null);- setMessageType(null);- try {- // 企业版 skills.uninstall 被网关拦截,卸载用户自装技能须走 skills.enterprise.uninstall- const data = await webRequest<{- success: boolean;- detail?: string;- message?: string;- error_message?: string;- }>(readOnly ? "skills.enterprise.uninstall" : "skills.uninstall", withSession({- name: pluginName,- // 传 origin 让后端按来源精确定位目录与记录,避免重名技能误删另一个- ...(origin ? { origin } : {}),- }));- if (!data.success) {- throw new Error(data.detail || data.message || data.error_message || t('skills.errors.uninstallFailed'));- }- showMessage("success", t('skills.messages.uninstalled', { pluginName }));- await fetchSkills();- handleBackToList();- } catch (error) {- console.error(error);- const errorMessage = error instanceof Error ? error.message : String(error);- showMessage("error", errorMessage || t('skills.errors.uninstallFailedHint'));- } finally {- setActionTarget(null);+ const confirmUninstall = useCallback(async () => {+ if (!pendingUninstall) return;+ const { name, displayName, origin } = pendingUninstall;+ setPendingUninstall(null);+ setActionTarget(name);+ setMessage(null);+ setMessageType(null);+ try {+ // 企业版 skills.uninstall 被网关拦截,卸载用户自装技能须走 skills.enterprise.uninstall+ const data = await webRequest<{+ success: boolean;+ detail?: string;+ message?: string;+ error_message?: string;+ }>(readOnly ? "skills.enterprise.uninstall" : "skills.uninstall", withSession({+ name,+ // 传 origin 让后端按来源精确定位目录与记录,避免重名技能误删另一个+ ...(origin ? { origin } : {}),+ }));+ if (!data.success) {+ throw new Error(data.detail || data.message || data.error_message || t('skills.errors.uninstallFailed'));}- },- [fetchSkills, handleBackToList, readOnly, t, withSession]- );+ showMessage("success", t('skills.messages.uninstalled', { pluginName: displayName }));+ await fetchSkills();+ handleBackToList();+ } catch (error) {+ console.error(error);+ const errorMessage = error instanceof Error ? error.message : String(error);+ showMessage("error", errorMessage || t('skills.errors.uninstallFailedHint'));+ } finally {+ setActionTarget(null);+ }+ }, [pendingUninstall, fetchSkills, handleBackToList, readOnly, t, withSession]);const renderActionButton = (skill: SkillItem) => {if (isAdministratorManagedSkill(skill)) {@@ -1649,6 +1692,16 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:);return (<>+ {pendingUninstall && (+ <ConfirmDialog+ title={t('skills.uninstallConfirmTitle')}+ message={t('skills.uninstallConfirm', { pluginName: pendingUninstall.displayName })}+ confirmLabel={t('skills.actions.uninstall')}+ onConfirm={() => void confirmUninstall()}+ onCancel={() => setPendingUninstall(null)}+ loading={actionTarget === pendingUninstall.name}+ />+ )}{message && messageType === "success" && (<div className="fixed top-4 right-4 z-[9999] rounded-[4px] text-sm text-text shadow-lg flex items-center gap-3 px-4" style={{ backgroundColor: "var(--color-feedback-success-toast)", width: "564px", height: "40px" }}><span className="w-4 h-4 rounded-full bg-[var(--color-feedback-success-indicator)] flex items-center justify-center flex-shrink-0">@@ -2068,20 +2121,22 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:{t('skills.marketplaceTabs.builtin')}</button>)}- <button- onClick={() => {- setMarketplaceSubTab("swarmskills");- setDebouncedSearch(search);- setSearchTrigger((prev) => prev + 1);- }}- className={`px-4 text-sm font-medium ${- marketplaceSubTab === "swarmskills"- ? "rounded-[8px] bg-secondary h-8 text-text"- : "text-text-muted hover:text-text"- }`}- >- {t('skills.swarmskills.title')}- </button>+ {enterpriseSourceCount !== 0 && (+ <button+ onClick={() => {+ setMarketplaceSubTab("swarmskills");+ setDebouncedSearch(search);+ setSearchTrigger((prev) => prev + 1);+ }}+ className={`px-4 text-sm font-medium ${+ marketplaceSubTab === "swarmskills"+ ? "rounded-[8px] bg-secondary h-8 text-text"+ : "text-text-muted hover:text-text"+ }`}+ >+ {t('skills.swarmskills.title')}+ </button>+ )}{!readOnly && (<buttononClick={() => {@@ -2221,11 +2276,11 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:{readOnly ? (<EnterpriseSkillSourcePanelsessionId={sessionId}+ installedSkillOrigins={enterpriseInstalledOrigins}+ installedStateLoaded={skillsLoadedRef.current}viewMode={viewMode}externalSearchQuery={debouncedSearch}- onInstalled={() => {- void fetchSkills();- }}+ onInstalled={() => fetchSkills()}/>) : (<TeamSkillsHubModal@@ -2356,8 +2411,12 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:<div className="text-sm font-medium text-text mb-2">{t('skills.contentPreview')}</div>- <div className="text-sm text-text whitespace-pre-wrap bg-secondary border border-border rounded-md p-3">- {selectedSkill.content || t('skills.noContent')}+ <div className="text-sm text-text bg-secondary border border-border rounded-md p-3">+ {selectedSkill.content ? (+ <MarkdownRenderer content={selectedSkill.content} className="chat-markdown text-sm" />+ ) : (+ t('skills.noContent')+ )}</div></div></div>diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/skillListRequest.ts b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/skillListRequest.tsnew file mode 100644index 0000000000..04650a5c82--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/skillListRequest.ts@@ -0,0 +1,38 @@+export function buildSkillListParams(sessionId: string, refreshMarketplaces: boolean): Record<string, string | boolean> {+ return {+ session_id: sessionId,+ with_installed: true,+ ...(refreshMarketplaces ? { refresh_marketplaces: true } : {}),+ };+}++export class LatestSkillListRequest {+ private current = 0;++ begin(): number {+ this.current += 1;+ return this.current;+ }++ isLatest(requestId: number): boolean {+ return requestId === this.current;+ }+}++type SkillListFetchState = {+ isActive: boolean;+ activeTab: string;+ previousContext: string | null;+ currentContext: string;+ sessionChanged: boolean;+};++export function shouldFetchSkillList(state: SkillListFetchState): boolean {+ if (!state.isActive) return false;+ return (+ state.previousContext === null ||+ state.previousContext === 'inactive' ||+ state.sessionChanged ||+ (state.activeTab === 'my' && state.previousContext !== state.currentContext)+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/common/ConfirmDialog.tsx b/jiuwenswarm/channels/web/frontend/src/components/common/ConfirmDialog.tsxindex 5367a44630..5353106b83 100644--- a/jiuwenswarm/channels/web/frontend/src/components/common/ConfirmDialog.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/common/ConfirmDialog.tsx@@ -39,7 +39,7 @@ export function ConfirmDialog({<buttononClick={onConfirm}disabled={loading}- className="px-6 py-1.5 rounded-full text-sm font-medium bg-primary text-text-inverse hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"+ className="rounded-full bg-accent px-6 py-1.5 text-sm font-medium text-accent-foreground hover:bg-accent-hover disabled:cursor-not-allowed disabled:opacity-60">{confirmLabel || t("common.confirm")}</button>diff --git a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsxindex cc978f6753..c3958fa3ab 100644--- a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx@@ -12,10 +12,11 @@ import { getSkillAvatar } from '../../utils/skillAvatar';import { Pagination } from '../../components/common/Pagination';import { ConfirmDialog } from '../../components/common/ConfirmDialog';import { useToast } from '../../components/common/useToast';+import { buildSourcePresentationParams, sourceSkillIdentity, isSourceSkillInstalled } from './installMetadata';const PAGE_SIZE = 20;-type LoadState = 'idle' | 'loading' | 'success' | 'error';+type LoadState = 'idle' | 'loading' | 'success' | 'error' | 'empty';type SourceDescriptor = {source_id: string;@@ -59,6 +60,8 @@ type UpdateStatus = {interface EnterpriseSkillSourcePanelProps {sessionId: string;+ installedSkillOrigins?: ReadonlySet<string>;+ installedStateLoaded?: boolean;viewMode?: 'list' | 'grid';/** 外层搜索框传入的关键词;提供时隐藏面板内置搜索框,关键词变化自动搜索 */externalSearchQuery?: string;@@ -105,7 +108,30 @@ function searchCacheKey(sessionId: string, sourceId: string, q: string, page: nureturn `${sessionId}|${sourceId}|${q}|${page}`;}-export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', externalSearchQuery, onInstalled }: EnterpriseSkillSourcePanelProps) {+/**+ * 拉取当前可用技能源(模块级缓存,供 SkillPanel 判断"无源时隐藏入口")。+ * 请求失败时回退缓存快照;仍无缓存返回 null,避免把瞬态故障误判成“确认无源”。+ */+export async function fetchEnterpriseSkillSources(sessionId: string): Promise<SourceDescriptor[] | null> {+ const cached = providersCache.get(sessionId);+ if (cached && isFresh(cached.at)) return cached.sources;+ try {+ const data = await webRequest<{+ success: boolean;+ providers?: SourceDescriptor[];+ }>('skills.source.providers', { session_id: sessionId });+ if (!data.success) return providersCache.get(sessionId)?.sources ?? null;+ const enabled = (data.providers || []).filter(+ item => item.enabled !== false && (item.capabilities || []).includes('search'),+ );+ providersCache.set(sessionId, { at: Date.now(), sources: enabled });+ return enabled;+ } catch {+ return providersCache.get(sessionId)?.sources ?? null;+ }+}++export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, installedStateLoaded = false, viewMode = 'list', externalSearchQuery, onInstalled }: EnterpriseSkillSourcePanelProps) {const { t } = useTranslation();const [sources, setSources] = useState<SourceDescriptor[]>([]);const [sourceId, setSourceId] = useState('');@@ -130,7 +156,7 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exterif (cancelled) return;setSources(enabled);if (enabled.length > 0) setSourceId(enabled[0].source_id);- else setLoadState('error');+ else setLoadState('empty');};const cached = providersCache.get(sessionId);if (cached && isFresh(cached.at)) {@@ -166,13 +192,13 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exter};}, [sessionId, showToast, t, withSession]);- // 2) 已安装技能的更新状态(按 source_id:name 作为已装判定;挂载走缓存,安装/更新后强制刷新)+ // 2) 使用来源与技能 ID 匹配更新状态,市场名称与包内名称可以不同。const loadUpdates = useCallback(async (targetSourceId: string, force = false) => {if (!targetSourceId) return;const cacheKey = `${sessionId}|${targetSourceId}`;const applyItems = (items: UpdateStatus[]) => {- setUpdateStatuses(new Map(items.map(item => [`${item.source_id}:${item.name}`, item])));+ setUpdateStatuses(new Map(items.map(item => [sourceSkillIdentity(item), item])));};const cached = updatesCache.get(cacheKey);if (!force && cached && isFresh(cached.at)) {@@ -195,11 +221,6 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exter[sessionId, withSession],);- useEffect(() => {- if (!sourceId) return;- void loadUpdates(sourceId);- }, [sourceId, loadUpdates]);-// 3) 搜索(preferCache 仅用于挂载/来源切换的自动加载;失败时回退缓存快照不清空列表)const runSearch = useCallback(async (targetPage: number, options?: { preferCache?: boolean }) => {@@ -260,10 +281,18 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exter);useEffect(() => {- if (sourceId) {- setPage(1);- void runSearch(1, { preferCache: true });- }+ if (!sourceId) return;+ let cancelled = false;+ setPage(1);+ void (async () => {+ // 串行:先主内容搜索,再补更新状态徽章,避免挂载/来源切换时 search 与+ // updates.check 并发请求,打满后端 scope 队列(SCOPE_FULL_TIMEOUT)。+ await runSearch(1, { preferCache: true });+ if (!cancelled) void loadUpdates(sourceId);+ })();+ return () => {+ cancelled = true;+ };// sourceId 变化时触发;内部模式 query 变化由搜索按钮/回车触发,外部模式由下面 query effect 触发// eslint-disable-next-line react-hooks/exhaustive-deps}, [sourceId]);@@ -300,8 +329,7 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', extersource_id: item.source_id || sourceId,skill_id: item.skill_id,version_id: item.version_id,- // 市场展示名透传落盘,安装后「我的技能」与技能广场同名显示- ...(item.display_name ? { display_name: item.display_name } : {}),+ ...buildSourcePresentationParams(item),force,}),);@@ -352,12 +380,13 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exterskill_id: item.skill_id,target_version_id: targetVersionId,expected_current_version_id: status.current_version_id,+ ...buildSourcePresentationParams(item, status.latest_version || item.version),}),);if (!data.success) throw new Error(data.error_message || t('skills.source.errors.updateFailed'));setUpdateStatuses(previous => {const next = new Map(previous);- next.set(`${item.source_id}:${item.name}`, {+ next.set(sourceSkillIdentity(item, sourceId), {...status,current_version_id: targetVersionId,latest_version_id: targetVersionId,@@ -379,8 +408,9 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exter);const renderAction = (item: SkillCandidate) => {- const status = updateStatuses.get(`${item.source_id}:${item.name}`);- const isInstalled = Boolean(status);+ const identity = sourceSkillIdentity(item, sourceId);+ const status = updateStatuses.get(identity);+ const isInstalled = isSourceSkillInstalled(identity, installedSkillOrigins, installedStateLoaded, Boolean(status));const isInstalling = installingId === itemKey(item, sourceId);if (isInstalled && status?.has_update) {return (@@ -419,7 +449,7 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exterconst avatar = getSkillAvatar(item.name);const displayName = item.display_name || item.name;const tags = (item.labels || []).map(labelText).filter(Boolean).slice(0, 4);- const status = updateStatuses.get(`${item.source_id}:${item.name}`);+ const status = updateStatuses.get(sourceSkillIdentity(item, sourceId));return (<divkey={`${item.source_id}:${item.name}:${item.version_id}`}@@ -529,12 +559,23 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', exter>{loadState === 'loading' ? t('common.loading') : t('skills.teamskillshub.search')}</button>+ <button+ type="button"+ onClick={() => sourceId && void loadUpdates(sourceId, true)}+ disabled={!sourceId}+ className={`px-4 py-1.5 rounded-2xl text-sm border border-gray-400 hover:border-gray-600 hover:bg-secondary/50 ${+ !sourceId ? 'text-text-muted cursor-not-allowed' : 'text-text'+ }`}+ >+ {t('skills.source.checkUpdates')}+ </button></>)}</div>)}{loadState === 'loading' && <div className="flex items-center justify-center flex-1 text-text-muted">{t('common.loading')}</div>}+ {loadState === 'empty' && <div className="mt-4 text-sm text-text-muted">{t('skills.source.noSources')}</div>}{loadState === 'error' && <div className="mt-4 text-sm text-text-muted">{t('skills.source.errors.searchFailed')}</div>}{loadState === 'success' && (<div className={`mt-4 flex-1 min-h-0 overflow-y-auto ${viewMode === 'grid' ? 'flex flex-wrap gap-4 content-start' : 'space-y-3'}`}>diff --git a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/installMetadata.ts b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/installMetadata.tsnew file mode 100644index 0000000000..cb5f619943--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/installMetadata.ts@@ -0,0 +1,29 @@+type SourcePresentation = {+ display_name?: string;+ version?: string;+ owner_display_name?: string;+};++export function sourceSkillIdentity(item: { source_id?: string; skill_id?: string }, fallbackSourceId = ''): string {+ return item.skill_id ? `${item.source_id || fallbackSourceId}:${item.skill_id}` : '';+}++export function isSourceSkillInstalled(identity: string, origins: ReadonlySet<string> | undefined, loaded: boolean, hasUpdateStatus: boolean): boolean {+ if (!identity) return false;+ return loaded ? Boolean(origins?.has(identity)) : Boolean(origins?.has(identity)) || hasUpdateStatus;+}++export function skillPresentationName(item: { name: string; market_display_name?: string; display_name?: string }): string {+ return item.market_display_name || item.display_name || item.name;+}++export function buildSourcePresentationParams(item: SourcePresentation, targetVersion?: string): Record<string, string> {+ const displayName = String(item.display_name || '').trim();+ const version = String(targetVersion || item.version || '').trim();+ const author = String(item.owner_display_name || '').trim();+ return {+ ...(displayName ? { display_name: displayName } : {}),+ ...(version ? { version } : {}),+ ...(author ? { author } : {}),+ };+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/sourceAvailability.ts b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/sourceAvailability.tsnew file mode 100644index 0000000000..ce46fbbcec--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/sourceAvailability.ts@@ -0,0 +1,7 @@+/**+ * `null` 表示技能源探测失败或结果未知,不能等同于管理员确认配置了零个源。+ * 保留旧值可避免一次瞬态失败把 SwarmSkills 入口永久隐藏。+ */+export function resolveEnterpriseSourceCount(current: number | null, sources: readonly unknown[] | null): number | null {+ return sources === null ? current : sources.length;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.ts b/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.tsnew file mode 100644index 0000000000..e55fcc76b6--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.ts@@ -0,0 +1,52 @@+export type MainNavKey =+ | 'chat'+ | 'skills'+ | 'agents'+ | 'teams'+ | 'sessions'+ | 'history'+ | 'cron'+ | 'channels'+ | 'extensions'+ | 'configpanel'+ | 'browserpanel'+ | 'updatepanel'+ | 'a2aingress';++export const MAIN_NAV_STORAGE_KEY = 'jiuwenswarm.active-main-nav';++const MAIN_NAV_KEYS = new Set<MainNavKey>([+ 'chat',+ 'skills',+ 'agents',+ 'teams',+ 'sessions',+ 'history',+ 'cron',+ 'channels',+ 'extensions',+ 'configpanel',+ 'browserpanel',+ 'updatepanel',+ 'a2aingress',+]);++export function parseStoredMainNav(raw: string | null, options: { blocked?: readonly MainNavKey[]; updaterEnabled?: boolean } = {}): MainNavKey {+ const nav = String(raw || '').trim() as MainNavKey;+ if (!MAIN_NAV_KEYS.has(nav)) return 'chat';+ if (options.blocked?.includes(nav)) return 'chat';+ if (nav === 'updatepanel' && options.updaterEnabled === false) return 'chat';+ return nav;+}++type MainNavRouteState = {+ previousRouteKey: string;+ routeKey: string;+ routeKind: 'chat-new' | 'chat-session' | 'not-found';+};++/** 首次挂载不覆盖已恢复的面板;用户真正切换会话路由时回到工作页。 */+export function resolveMainNavAfterRoute(current: MainNavKey, route: MainNavRouteState): MainNavKey {+ if (route.routeKind === 'not-found') return 'chat';+ return route.previousRouteKey === route.routeKey ? current : 'chat';+}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 8270d3b2ab..6a2077b689 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -1736,6 +1736,8 @@"updatedAt": "Updated","searchPlaceholder": "Search skills","noResults": "No matching skills",+ "noSources": "No skill sources available. Contact your administrator.",+ "checkUpdates": "Check updates","prev": "Previous","next": "Next","replaceConfirm": "Skill {{name}} is already installed. Overwrite?",@@ -2130,6 +2132,7 @@"marketplacesDefault": "Default marketplace: anthropics","installPrompt": "Enter plugin spec (plugin@marketplace)","importPrompt": "Enter a local skill path on the server (SKILL.md or directory)",+ "uninstallConfirmTitle": "Uninstall","uninstallConfirm": "Uninstall {{pluginName}}?","messages": {"installing": "Installing: {{name}}...",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 2f340f3485..83c7ce2c6d 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -1723,6 +1723,8 @@"updatedAt": "更新时间","searchPlaceholder": "搜索技能名称或描述","noResults": "暂无匹配的技能",+ "noSources": "暂无可用技能源,请联系管理员配置",+ "checkUpdates": "检查更新","prev": "上一页","next": "下一页","replaceConfirm": "技能 {{name}} 已安装,是否覆盖重装?",@@ -2117,6 +2119,7 @@"marketplacesDefault": "默认 marketplace: anthropics","installPrompt": "请输入插件规格 (plugin@marketplace)","importPrompt": "请输入服务端本地 skill 路径(SKILL.md 或目录)",+ "uninstallConfirmTitle": "卸载确认","uninstallConfirm": "确认卸载 {{pluginName}} ?","messages": {"installing": "安装中:{{name}}...",diff --git a/jiuwenswarm/channels/web/frontend/tests/skillPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/skillPanelState.test.mjsnew file mode 100644index 0000000000..5a38773321--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/skillPanelState.test.mjs@@ -0,0 +1,130 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { MAIN_NAV_STORAGE_KEY, parseStoredMainNav, resolveMainNavAfterRoute } from '../node_modules/.cache/skill-panel-state/features/mainNavigationState.js';+import {+ buildSkillListParams,+ LatestSkillListRequest,+ shouldFetchSkillList,+} from '../node_modules/.cache/skill-panel-state/components/SkillPanel/skillListRequest.js';+import {+ buildSourcePresentationParams,+ sourceSkillIdentity,+ isSourceSkillInstalled,+ skillPresentationName,+} from '../node_modules/.cache/skill-panel-state/features/EnterpriseSkillSourcePanel/installMetadata.js';+import { resolveEnterpriseSourceCount } from '../node_modules/.cache/skill-panel-state/features/EnterpriseSkillSourcePanel/sourceAvailability.js';++test('restores the skills navigation after a same-tab refresh', () => {+ assert.equal(MAIN_NAV_STORAGE_KEY, 'jiuwenswarm.active-main-nav');+ assert.equal(parseStoredMainNav('skills'), 'skills');+});++test('rejects stale or unavailable persisted navigation values', () => {+ assert.equal(parseStoredMainNav('not-a-panel'), 'chat');+ assert.equal(parseStoredMainNav('configpanel', { blocked: ['configpanel'] }), 'chat');+ assert.equal(parseStoredMainNav('updatepanel', { updaterEnabled: false }), 'chat');+});++test('initial chat route preserves restored skills, while real route changes return to work', () => {+ assert.equal(+ resolveMainNavAfterRoute('skills', {+ previousRouteKey: 'chat-session:session-1',+ routeKey: 'chat-session:session-1',+ routeKind: 'chat-session',+ }),+ 'skills',+ );+ assert.equal(+ resolveMainNavAfterRoute('skills', {+ previousRouteKey: 'chat-session:session-1',+ routeKey: 'chat-session:session-2',+ routeKind: 'chat-session',+ }),+ 'chat',+ );+ assert.equal(+ resolveMainNavAfterRoute('skills', {+ previousRouteKey: 'not-found:/bad',+ routeKey: 'not-found:/bad',+ routeKind: 'not-found',+ }),+ 'chat',+ );+});++test('skills.list is always bound to the active session', () => {+ assert.deepEqual(buildSkillListParams('session-42', false), {+ session_id: 'session-42',+ with_installed: true,+ });+ assert.deepEqual(buildSkillListParams('session-42', true), {+ session_id: 'session-42',+ with_installed: true,+ refresh_marketplaces: true,+ });+});++test('an older skills.list response cannot overwrite the newest request', () => {+ const requests = new LatestSkillListRequest();+ const first = requests.begin();+ const second = requests.begin();++ assert.equal(requests.isLatest(first), false);+ assert.equal(requests.isLatest(second), true);+});++test('skill list loading is deduplicated on mount and refreshed on re-entry', () => {+ const base = {+ isActive: true,+ activeTab: 'my',+ currentContext: 'my:user',+ sessionChanged: false,+ };+ assert.equal(shouldFetchSkillList({ ...base, previousContext: null }), true);+ assert.equal(shouldFetchSkillList({ ...base, previousContext: 'my:user' }), false);+ assert.equal(shouldFetchSkillList({ ...base, previousContext: 'inactive' }), true);+ assert.equal(shouldFetchSkillList({ ...base, isActive: false, previousContext: 'my:prebuilt' }), false);+});++test('install and update requests carry marketplace presentation metadata', () => {+ const item = {+ display_name: 'Enterprise Architecture',+ version: '1.0.0',+ owner_display_name: 'Architecture Team',+ };++ assert.deepEqual(buildSourcePresentationParams(item), {+ display_name: 'Enterprise Architecture',+ version: '1.0.0',+ author: 'Architecture Team',+ });+ assert.deepEqual(buildSourcePresentationParams(item, '1.1.0'), {+ display_name: 'Enterprise Architecture',+ version: '1.1.0',+ author: 'Architecture Team',+ });+});++test('a transient source discovery failure does not hide the enterprise marketplace', () => {+ assert.equal(resolveEnterpriseSourceCount(null, null), null);+ assert.equal(resolveEnterpriseSourceCount(2, null), 2);+ assert.equal(resolveEnterpriseSourceCount(null, []), 0);+ assert.equal(resolveEnterpriseSourceCount(null, [{ source_id: 'hub' }]), 1);+});++test('marketplace installation survives different market and package names and failed update checks', () => {+ const market = { source_id: 'customer', skill_id: 'asset-1', name: '中文技能' };+ const installed = { source_id: 'customer', skill_id: 'asset-1', name: 'english-internal-name' };+ assert.equal(sourceSkillIdentity(market), sourceSkillIdentity(installed));+ assert.equal(isSourceSkillInstalled(sourceSkillIdentity(market), new Set(['customer:asset-1']), true, false), true);+ assert.equal(isSourceSkillInstalled(sourceSkillIdentity(market), new Set(), true, true), false);+ assert.equal(isSourceSkillInstalled('other:asset-1', new Set(['customer:asset-1']), true, false), false);+});++test('uninstall presentation uses the Chinese market name while preserving the internal name', () => {+ const skill = { name: 'english-internal-name', market_display_name: '中文技能' };+ assert.equal(skillPresentationName(skill), '中文技能');+ assert.equal(skill.name, 'english-internal-name');+ assert.equal(skillPresentationName({ name: 'legacy-name' }), 'legacy-name');+});diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.pyindex 22a7f0b1c1..4a7620fb37 100644--- a/jiuwenswarm/server/runtime/skill/skill_manager.py+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py@@ -92,6 +92,9 @@ def enabled_skills_from_environ() -> str | None:_SKILLNET_DOWNLOAD_TIMEOUT: int = int(os.environ.get("SKILLNET_DOWNLOAD_TIMEOUT", "60"))_SKILLNET_MAX_RETRIES: int = int(os.environ.get("SKILLNET_MAX_RETRIES", "3"))+_MARKETPLACE_GIT_TIMEOUT_SECONDS: float = float(+ os.environ.get("MARKETPLACE_GIT_TIMEOUT", "30")+)# SkillNet 异步安装 job 必须跨 SkillManager 实例共享:skills.* 无状态 RPC 在# AgentManager 缓存未命中时会临时 new JiuWenSwarm(),install 与 install_status# 可能落到不同实例;若 job 仅存实例内存会误报「安装会话已过期」。@@ -724,13 +727,16 @@ class SkillManager:params:refresh_marketplaces: bool (可选, 默认 False)- 为 True 时,先对已配置 marketplace 执行 clone/pull,再扫描列表。+ 个人版为 True 时,先对已配置 marketplace 执行 clone/pull,再扫描列表;+ 企业版不消费 marketplace,忽略该参数。with_installed: bool (可选, 默认 False)为 True 时,同一次响应中附带 plugins(与 skills.installed 一致),避免网关串行处理两次 RPC 导致列表刷新超时或排队过久。"""refresh_marketplaces = bool(params.get("refresh_marketplaces", False))- if refresh_marketplaces:+ # 企业版不消费 marketplace 扫描结果(下方 marketplace 恒为 []),+ # 跳过同步,避免无意义的 git clone/pull 拖慢列表请求(超时/502)。+ if refresh_marketplaces and not is_enterprise():await self._sync_marketplace_repos()# 每次列举前,把手动拷入 skills 目录、尚未登记的本地技能补登记为 local,# 使其无需重启 server、刷新"我的技能"即可显示(与导入本地技能一致)。@@ -2353,6 +2359,7 @@ class SkillManager:fingerprint: str | None = None,verification: dict[str, Any] | None = None,market_display_name: str = "",+ author: str = "",) -> dict[str, Any]:"""Atomically replace the entity, then commit the JSON installation record."""existing_ref = self._find_installation_by_skill_ref(source_id, skill_id)@@ -2403,6 +2410,7 @@ class SkillManager:verification=verification,entity_dir=entity_dir,market_display_name=market_display_name,+ author=author,)except Exception:if dest.exists():@@ -2430,6 +2438,8 @@ class SkillManager:force = bool(params.get("force", False))# 市场展示名(技能广场卡片名)透传落盘,让「我的技能」与技能广场同名显示market_display_name = str(params.get("display_name") or "").strip()[:200]+ market_version = str(params.get("version") or "").strip()[:100]+ market_author = str(params.get("author") or "").strip()[:200]try:descriptor, body, verification = await self._fetch_verified_source_artifact(source_id=source_id,@@ -2452,11 +2462,19 @@ class SkillManager:skill_name = _safe_path_name(str(metadata.get("name") or skill_dir.name), "skill")+ descriptor_metadata = dict(descriptor.metadata or {})version = str(- metadata.get("version")- or descriptor.metadata.get("version")+ descriptor_metadata.get("version")+ or market_version+ or metadata.get("version")or version_id).strip()+ author = str(+ descriptor_metadata.get("author")+ or descriptor_metadata.get("publisher_name")+ or descriptor_metadata.get("owner_display_name")+ or market_author+ ).strip()[:200]record = self._commit_source_skill_entity(skill_dir,skill_name=skill_name,@@ -2468,12 +2486,13 @@ class SkillManager:fingerprint=descriptor.fingerprint,verification=verification,market_display_name=market_display_name,+ author=author,)skill_payload: dict[str, Any] = {}for key in ("installation_id", "name", "declared_name", "source_type","source_id", "skill_id", "version_id", "version", "enabled",- "installed", "removable", "consistency",+ "installed", "removable", "consistency", "author",):value = record.get(key)if value is not None:@@ -3250,7 +3269,13 @@ class SkillManager:# 优先用 origin 精确定位目录(ClawHub 目录名 = slug,可由 origin 直推)dest = Nonename = ""- if raw_origin:+ if installation is not None and installation.get("entity_dir"):+ name = _safe_path_name(str(installation.get("name") or raw_name), "skill")+ entity_path = _safe_child_path(self._skills_dir, str(installation["entity_dir"]), "skill")+ if not entity_path.is_dir():+ return {"success": False, "detail": f"未找到 skill: {name}"}+ dest = entity_path+ if dest is None and raw_origin:dest = self._resolve_local_skill_dir_by_origin(raw_origin)# origin 命中时 name 用于 builtin 校验/记录回退name = raw_name@@ -3650,7 +3675,15 @@ class SkillManager:"error_message": "service_id and agent_id are required",}- installation = self._find_skill_installation(name=name)+ origin = str(params.get("origin") or "").strip()+ if origin:+ matches = [+ record for record in self.list_skill_installations()+ if str(record.get("origin") or "").strip() == origin+ ]+ installation = matches[0] if len(matches) == 1 else None+ else:+ installation = self._find_skill_installation(name=name)if installation is None:return {"success": False,@@ -3664,6 +3697,7 @@ class SkillManager:"error_message": f"skill `{name}` is prebuilt and cannot be uninstalled",}+ name = str(installation.get("name") or "").strip()result = await self.handle_skills_uninstall({"name": name, "origin": str(installation.get("origin") or "")})@@ -5282,6 +5316,16 @@ class SkillManager:async def _git_clone(self, url: str, dest: Path) -> str | None:"""浅克隆 git 仓库,返回 commit hash 或 None."""dest.parent.mkdir(parents=True, exist_ok=True)+ if dest.exists():+ return await self._git_get_commit(dest)+ staging = dest.with_name(f".{dest.name}.clone-{uuid.uuid4().hex}")++ def cleanup_partial_clone() -> None:+ if not staging.exists():+ return+ if not _safe_rmtree(staging):+ logger.warning("清理未完成的 git clone 目录失败: %s", staging)+try:proc = await asyncio.create_subprocess_exec("git",@@ -5289,16 +5333,41 @@ class SkillManager:"--depth","1",url,- str(dest),+ str(staging),stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)- _, stderr = await proc.communicate()+ try:+ _, stderr = await asyncio.wait_for(+ proc.communicate(),+ timeout=_MARKETPLACE_GIT_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ if proc.returncode is None:+ proc.kill()+ await proc.communicate()+ logger.error(+ "git clone 超时(%.1fs): %s",+ _MARKETPLACE_GIT_TIMEOUT_SECONDS,+ url,+ )+ cleanup_partial_clone()+ return Noneif proc.returncode != 0:logger.error("git clone 失败: %s", stderr.decode(errors="replace"))+ cleanup_partial_clone()return None+ try:+ staging.rename(dest)+ except OSError:+ # 另一个并发 clone 已率先发布时,只清理本请求独占的暂存目录。+ if dest.exists():+ cleanup_partial_clone()+ return await self._git_get_commit(dest)+ raisereturn await self._git_get_commit(dest)except Exception as exc:+ cleanup_partial_clone()logger.error("git clone 异常: %s", exc)return None@@ -5314,7 +5383,21 @@ class SkillManager:stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)- _, stderr = await proc.communicate()+ try:+ _, stderr = await asyncio.wait_for(+ proc.communicate(),+ timeout=_MARKETPLACE_GIT_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ if proc.returncode is None:+ proc.kill()+ await proc.communicate()+ logger.warning(+ "git pull 超时(%.1fs): %s",+ _MARKETPLACE_GIT_TIMEOUT_SECONDS,+ repo_path,+ )+ return Noneif proc.returncode != 0:logger.warning("git pull 失败: %s", stderr.decode(errors="replace"))return None@@ -5744,6 +5827,7 @@ class SkillManager:"sync_status","consistency","market_display_name",+ "author",):if key in dto:payload[key] = dto[key]@@ -5788,6 +5872,7 @@ class SkillManager:verification: dict[str, Any] | None = None,entity_dir: str | None = None,market_display_name: str | None = None,+ author: str | None = None,replace_by_name: bool = False,) -> dict[str, Any]:"""Create or update one managed installation in workspace JSON."""@@ -5858,6 +5943,7 @@ class SkillManager:("version_id", version_id),("fingerprint", fingerprint),("market_display_name", market_display_name),+ ("author", author),):normalized = str(value or "").strip()if normalized:diff --git a/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.py b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.pyindex 45c29ae998..e5df04ce34 100644--- a/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.py+++ b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.py@@ -282,6 +282,17 @@ class SwarmSkillHubProvider(SkillSourceProvider):download_url = _text(data.get("download_url"))if not download_url:raise RuntimeError("SwarmSkillHub 未返回 download_url")+ metadata: dict[str, Any] = {}+ for key in (+ "display_name",+ "short_desc",+ "version",+ "author",+ "publisher_name",+ "owner_display_name",+ ):+ if key in data and data[key] is not None:+ metadata[key] = data[key]return ArtifactDescriptor(artifact_ref=ArtifactRef(skill_ref=skill_ref, version_id=version_id),download_url=download_url,@@ -300,9 +311,5 @@ class SwarmSkillHubProvider(SkillSourceProvider):key_id=_text(data.get("key_id") or data.get("keyId")) or None,fingerprint=_text(data.get("fingerprint")) or None,content_length=_int_or_none(data.get("content_length")),- metadata={- key: data[key]- for key in ("display_name", "short_desc", "version")- if key in data and data[key] is not None- },+ metadata=metadata,)diff --git a/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py b/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.pyindex 6825afc78a..2e69ded1e8 100644--- a/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py+++ b/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py@@ -150,3 +150,57 @@ def test_enterprise_web_install_and_uninstall_use_workspace_state(assert removed == {"success": True, "name": "user-skill"}assert not (workspace / "skills" / "user-skill").exists()assert manager.list_skill_installations() == []+++def test_enterprise_uninstall_uses_origin_and_persisted_entity_directory(tmp_path: Path) -> None:+ manager = SkillManager(workspace_dir=str(tmp_path), service_id="svc", agent_id="agent")+ skill_dir = _write_skill(tmp_path, "package-directory")+ manager.record_skill_installation(+ name="internal-name", source_type="user", origin="customhub:asset-1",+ source="customhub", entity_dir="package-directory", market_display_name="中文技能",+ )+ # 模拟刷新后重建管理器,市场名、登记名、磁盘目录名彼此不同。+ restored = SkillManager(workspace_dir=str(tmp_path), service_id="svc", agent_id="agent")+ result = asyncio.run(restored.handle_skills_web_uninstall(+ {"name": "中文技能", "origin": "customhub:asset-1"}+ ))+ assert result == {"success": True, "name": "internal-name"}+ assert not skill_dir.exists()+ assert restored.list_skill_installations() == []+++def test_enterprise_uninstall_does_not_fall_back_from_unknown_origin(tmp_path: Path) -> None:+ manager = SkillManager(workspace_dir=str(tmp_path), service_id="svc", agent_id="agent")+ skill_dir = _write_skill(tmp_path, "user-skill")+ manager.record_skill_installation(name="user-skill", source_type="user", origin="customhub:asset-1")+ result = asyncio.run(manager.handle_skills_web_uninstall(+ {"name": "user-skill", "origin": "customhub:missing"}+ ))+ assert result["success"] is False+ assert skill_dir.exists()+++def test_enterprise_skills_list_does_not_wait_for_marketplace_sync(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Removing the enterprise guard must make this request time out."""+ manager = SkillManager(workspace_dir=str(tmp_path / "tenant"))++ async def never_finishes() -> None:+ await asyncio.Event().wait()++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.is_enterprise",+ lambda: True,+ )+ monkeypatch.setattr(manager, "_sync_marketplace_repos", never_finishes)++ payload = asyncio.run(+ asyncio.wait_for(+ manager.handle_skills_list({"refresh_marketplaces": True}),+ timeout=0.1,+ )+ )++ assert isinstance(payload["skills"], list)diff --git a/tests/unit_tests/agentserver/test_skill_manager_marketplace_sync.py b/tests/unit_tests/agentserver/test_skill_manager_marketplace_sync.pynew file mode 100644index 0000000000..597527577c--- /dev/null+++ b/tests/unit_tests/agentserver/test_skill_manager_marketplace_sync.py@@ -0,0 +1,123 @@+from __future__ import annotations++import asyncio+import sys+from pathlib import Path++import pytest++from jiuwenswarm.server.runtime.skill import skill_manager as skill_manager_module+from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager++[email protected]("method_name", ["_git_clone", "_git_pull"])+def test_marketplace_git_operation_times_out_and_reaps_process(+ method_name: str,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Removing the internal timeout must leave the call stuck past the deadline."""+ manager = SkillManager(workspace_dir=str(tmp_path / "workspace"))+ clone_path = tmp_path / "clone"+ repository_path = tmp_path / "repository"+ if method_name == "_git_pull":+ repository_path.mkdir()+ (repository_path / "keep-me").write_text("existing repository", encoding="utf-8")++ async def exercise() -> tuple[str | None, list[asyncio.subprocess.Process]]:+ original_create_subprocess_exec = asyncio.create_subprocess_exec+ processes: list[asyncio.subprocess.Process] = []++ async def start_hanging_process(*args, **kwargs):+ if method_name == "_git_clone":+ process_dest = Path(args[-1])+ process_dest.mkdir()+ (process_dest / "partial").write_text("incomplete clone", encoding="utf-8")+ process = await original_create_subprocess_exec(+ sys.executable,+ "-c",+ "import time; time.sleep(60)",+ stdout=kwargs.get("stdout"),+ stderr=kwargs.get("stderr"),+ )+ processes.append(process)+ return process++ monkeypatch.setattr(+ skill_manager_module,+ "_MARKETPLACE_GIT_TIMEOUT_SECONDS",+ 0.05,+ raising=False,+ )+ monkeypatch.setattr(+ skill_manager_module.asyncio,+ "create_subprocess_exec",+ start_hanging_process,+ )++ method = getattr(manager, method_name)+ operation = (+ method("https://example.invalid/marketplace.git", clone_path)+ if method_name == "_git_clone"+ else method(repository_path)+ )+ try:+ result = await asyncio.wait_for(operation, timeout=0.5)+ finally:+ for process in processes:+ if process.returncode is None:+ process.kill()+ await process.communicate()+ return result, processes++ result, processes = asyncio.run(exercise())++ assert result is None+ assert processes+ assert all(process.returncode is not None for process in processes)+ if method_name == "_git_clone":+ assert not clone_path.exists()+ assert not list(tmp_path.glob(".clone.clone-*"))+ else:+ assert (repository_path / "keep-me").read_text(encoding="utf-8") == "existing repository"+++def test_concurrent_marketplace_clones_do_not_delete_each_others_destination(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manager = SkillManager(workspace_dir=str(tmp_path / "workspace"))+ clone_path = tmp_path / "clone"++ class SuccessfulClone:+ returncode: int | None = None++ async def communicate(self):+ await asyncio.sleep(0.05)+ self.returncode = 0+ return b"", b""++ async def start_clone(*args, **_kwargs):+ process_dest = Path(args[-1])+ process_dest.mkdir()+ (process_dest / ".git").mkdir()+ return SuccessfulClone()++ async def get_commit(repo_path: Path) -> str | None:+ return "commit-123" if (repo_path / ".git").is_dir() else None++ monkeypatch.setattr(skill_manager_module.asyncio, "create_subprocess_exec", start_clone)+ monkeypatch.setattr(manager, "_git_get_commit", get_commit)++ async def exercise() -> list[str | None]:+ return await asyncio.gather(+ manager._git_clone("https://example.invalid/marketplace.git", clone_path),+ manager._git_clone("https://example.invalid/marketplace.git", clone_path),+ )++ results = asyncio.run(exercise())++ assert clone_path.is_dir()+ assert (clone_path / ".git").is_dir()+ assert not list(tmp_path.glob(".clone.clone-*"))+ assert results == ["commit-123", "commit-123"]diff --git a/tests/unit_tests/agentserver/test_swarm_hub_extension.py b/tests/unit_tests/agentserver/test_swarm_hub_extension.pyindex 1f9a8cb234..7cf06baf6c 100644--- a/tests/unit_tests/agentserver/test_swarm_hub_extension.py+++ b/tests/unit_tests/agentserver/test_swarm_hub_extension.py@@ -1,5 +1,8 @@from __future__ import annotations+import io+import zipfile+import pytestfrom jiuwenswarm.extensions.registry import ExtensionRegistry@@ -47,6 +50,35 @@ class _CustomVerifyProvider(SkillSourceProvider):return {"verified": True, "artifact_sha256": "custom-sha"}+class _MarketplaceMetadataProvider(SkillSourceProvider):+ source_id = "hub-market"+ provider_type = "customhub"+ display_name = "Marketplace"+ capabilities = frozenset({"get_artifact"})++ async def search(self, request: SkillSearchRequest, context) -> SkillSearchResult:+ return SkillSearchResult(items=())++ async def get_artifact(self, skill_ref: SkillRef, version_id: str, context) -> ArtifactDescriptor:+ return ArtifactDescriptor(+ artifact_ref=ArtifactRef(skill_ref=skill_ref, version_id=version_id),+ download_url="https://example.com/enterprise-architecture.zip",+ metadata={"version": "1.0.0"} if version_id == "version-456" else {},+ )++ async def download_artifact(self, descriptor, download_policy=None) -> bytes:+ stream = io.BytesIO()+ with zipfile.ZipFile(stream, "w") as archive:+ archive.writestr(+ "enterprise-architecture/SKILL.md",+ "---\nname: enterprise-architecture\nversion: 0.1\n---\n# Enterprise Architecture\n",+ )+ return stream.getvalue()++ async def verify_artifact(self, descriptor, content):+ return {"verified": True}++@pytest.mark.asyncio@@ -88,3 +120,93 @@ async def test_install_path_uses_provider_download_and_verify_overrides(tmp_pathassert content == b"zip-bytes"+async def test_source_install_keeps_marketplace_version_and_author_in_list_and_detail(+ tmp_path, monkeypatch+):+ monkeypatch.setattr(ExtensionRegistry, "_instance", None)+ manager = SkillManager(workspace_dir=str(tmp_path))+ registry = SourceRegistry()+ registry.register(+ SourceConfig(+ source_id="hub-market",+ provider_type="customhub",+ capabilities=frozenset({"get_artifact"}),+ download_policy=DownloadPolicy(allowed_hosts=("example.com",)),+ ),+ _MarketplaceMetadataProvider(),+ )+ manager._source_registry = registry++ result = await manager.handle_skills_source_install(+ {+ "source_id": "hub-market",+ "skill_id": "skill-123",+ "version_id": "version-456",+ "version": "1.0.0",+ "author": "Architecture Team",+ "display_name": "Enterprise Architecture",+ }+ )++ assert result["success"] is True+ listed = await manager.handle_skills_list({"with_installed": True})+ skill = next(item for item in listed["skills"] if item["name"] == "enterprise-architecture")+ detail = await manager.handle_skills_get(+ {"name": "enterprise-architecture", "origin": "hub-market:skill-123"}+ )+ assert skill["version"] == "1.0.0"+ assert skill["author"] == "Architecture Team"+ assert detail["version"] == "1.0.0"+ assert detail["author"] == "Architecture Team"+++async def test_source_update_keeps_target_marketplace_version_and_author_in_list_and_detail(+ tmp_path, monkeypatch+):+ monkeypatch.setattr(ExtensionRegistry, "_instance", None)+ manager = SkillManager(workspace_dir=str(tmp_path))+ registry = SourceRegistry()+ registry.register(+ SourceConfig(+ source_id="hub-market",+ provider_type="customhub",+ capabilities=frozenset({"get_artifact"}),+ download_policy=DownloadPolicy(allowed_hosts=("example.com",)),+ ),+ _MarketplaceMetadataProvider(),+ )+ manager._source_registry = registry+ installed = await manager.handle_skills_source_install(+ {+ "source_id": "hub-market",+ "skill_id": "skill-123",+ "version_id": "version-456",+ "version": "1.0.0",+ "author": "Architecture Team",+ }+ )+ assert installed["success"] is True++ updated = await manager.handle_skills_update(+ {+ "source_id": "hub-market",+ "skill_id": "skill-123",+ "target_version_id": "version-789",+ "expected_current_version_id": "version-456",+ "version": "1.1.0",+ "author": "Architecture Team v2",+ }+ )++ assert updated["success"] is True+ listed = await manager.handle_skills_list({"with_installed": True})+ skill = next(item for item in listed["skills"] if item["name"] == "enterprise-architecture")+ detail = await manager.handle_skills_get(+ {"name": "enterprise-architecture", "origin": "hub-market:skill-123"}+ )+ assert skill["version"] == "1.1.0"+ assert skill["author"] == "Architecture Team v2"+ assert detail["version"] == "1.1.0"+ assert detail["author"] == "Architecture Team v2"