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(skill): serialize enterprise skill state across pods and isolate user skills from prebuilt sync
hubenc11b72d39e1d
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsxindex d53b79f078..b2bf96cf18 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx@@ -32,7 +32,7 @@ const SKILLS_FETCH_TIMEOUT_NORMAL_MS = 30_000;const SKILL_RETRIEVAL_RUNNING_POLL_MS = 10_000;const SKILL_RETRIEVAL_IDLE_POLL_MS = 5 * 60_000;const GRAPH_READING_MIN_VISIBLE_MS = 500;-const MY_SKILLS_PAGE_SIZE = 20;+const MY_SKILLS_PAGE_SIZE_DEFAULT = 20;type SkillItem = {name: string;@@ -613,6 +613,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:const [activeTab, setActiveTab] = useState<"my" | "marketplace" | "index" | "graph">("my");const [mySkillsSubTab, setMySkillsSubTab] = useState<"all" | "enabled" | "disabled" | "builtin" | "prebuilt" | "user">("all");const [mySkillsPage, setMySkillsPage] = useState(1);+ const [mySkillsPageSize, setMySkillsPageSize] = useState(MY_SKILLS_PAGE_SIZE_DEFAULT);const [marketplaceSubTab, setMarketplaceSubTab] = useState<"builtin" | "swarmskills" | "online">("builtin");// 企业版:技能源为空时不展示 SwarmSkills 入口(null=未知,加载中先展示)const [enterpriseSourceCount, setEnterpriseSourceCount] = useState<number | null>(null);@@ -1539,15 +1540,20 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:}, [visibleSkills, mySkillsSubTab, installedSkillMap, readOnly]);const mySkillsFiltered = useMemo(() => getMySkillsFiltered(), [getMySkillsFiltered]);- const mySkillsTotalPages = Math.max(1, Math.ceil(mySkillsFiltered.length / MY_SKILLS_PAGE_SIZE));+ const mySkillsTotalPages = Math.max(1, Math.ceil(mySkillsFiltered.length / mySkillsPageSize));const pagedMySkills = useMemo(() => mySkillsFiltered.slice(- (mySkillsPage - 1) * MY_SKILLS_PAGE_SIZE,- mySkillsPage * MY_SKILLS_PAGE_SIZE+ (mySkillsPage - 1) * mySkillsPageSize,+ mySkillsPage * mySkillsPageSize),- [mySkillsFiltered, mySkillsPage]+ [mySkillsFiltered, mySkillsPage, mySkillsPageSize]);+ const handleMySkillsPageSizeChange = (nextSize: number) => {+ setMySkillsPageSize(nextSize);+ setMySkillsPage(1);+ };+useEffect(() => {setMySkillsPage(1);}, [mySkillsSubTab, debouncedSearch, viewMode]);@@ -2511,9 +2517,6 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:className="w-full px-3 py-2 rounded-md bg-panel border border-border text-sm text-text placeholder:text-text-muted"/></div>- <div className="text-xs text-text-muted flex-shrink-0">- {t('skills.totalCount', { count: mySkillsFiltered.length })}- </div></div><div className={`mt-4 flex-1 min-h-0 overflow-y-auto ${viewMode === "grid" ? "flex flex-wrap gap-4 content-start" : "space-y-3"}`}>@@ -2638,6 +2641,9 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:<Paginationpage={mySkillsPage}totalPages={mySkillsTotalPages}+ total={mySkillsFiltered.length}+ pageSize={mySkillsPageSize}+ onPageSizeChange={handleMySkillsPageSizeChange}onPageChange={(page) => setMySkillsPage(page)}className="mt-3"/>diff --git a/jiuwenswarm/channels/web/frontend/src/components/common/Pagination.tsx b/jiuwenswarm/channels/web/frontend/src/components/common/Pagination.tsxindex 84b8175e58..b6f0d7c495 100644--- a/jiuwenswarm/channels/web/frontend/src/components/common/Pagination.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/common/Pagination.tsx@@ -1,7 +1,9 @@/*** 通用分页条:上一页/下一页 + 页码指示 + 可选总数。+ * 支持可选页大小选择器(pageSizeOptions/onPageSizeChange)与跳页输入(onPageChange 到指定页)。* 供「我的技能」列表、企业技能源面板等列表复用。*/+import { useState } from "react";import { useTranslation } from "react-i18next";interface PaginationProps {@@ -9,6 +11,12 @@ interface PaginationProps {totalPages: number;total?: number;onPageChange: (page: number) => void;+ /** 当前页大小;提供时渲染页大小选择器 */+ pageSize?: number;+ /** 页大小变化回调 */+ onPageSizeChange?: (pageSize: number) => void;+ /** 可选的页大小选项,默认 [10, 20, 50] */+ pageSizeOptions?: number[];className?: string;}@@ -17,13 +25,54 @@ export function Pagination({totalPages,total,onPageChange,+ pageSize,+ onPageSizeChange,+ pageSizeOptions = [10, 20, 50],className = "",}: PaginationProps) {const { t } = useTranslation();- if (totalPages <= 1) return null;+ const [jumpValue, setJumpValue] = useState("");++ if (totalPages <= 1 && pageSize === undefined) return null;++ const goToPage = (target: number) => {+ const clamped = Math.max(1, Math.min(totalPages, target));+ if (clamped !== page) onPageChange(clamped);+ setJumpValue("");+ };++ const handleJumpKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key !== "Enter") return;+ const parsed = Number.parseInt(jumpValue, 10);+ if (Number.isNaN(parsed)) {+ setJumpValue("");+ return;+ }+ goToPage(parsed);+ };+return (<div className={`flex items-center justify-end gap-3 text-sm text-text-muted flex-shrink-0 ${className}`}>{total != null && <span>{t("common.pagination.total", { count: total })}</span>}+ {pageSize !== undefined && onPageSizeChange && (+ <label className="flex items-center gap-1.5">+ <span className="whitespace-nowrap">{t("common.pagination.pageSize")}</span>+ <select+ value={pageSize}+ onChange={event => {+ onPageSizeChange(Number.parseInt(event.target.value, 10));+ setJumpValue("");+ }}+ className="px-2 py-1 rounded-md border border-border bg-panel text-sm text-text focus:outline-none"+ >+ {pageSizeOptions.map(size => (+ <option key={size} value={size}>+ {size}+ </option>+ ))}+ </select>+ </label>+ )}<buttontype="button"onClick={() => onPageChange(page - 1)}@@ -33,7 +82,9 @@ export function Pagination({>‹</button>- <span>{page} / {totalPages}</span>+ <span className="whitespace-nowrap">+ {page} / {totalPages}+ </span><buttontype="button"onClick={() => onPageChange(page + 1)}@@ -43,6 +94,30 @@ export function Pagination({>›</button>+ {totalPages > 1 && (+ <label className="flex items-center gap-1.5">+ <span className="whitespace-nowrap">{t("common.pagination.jumpTo")}</span>+ <input+ type="number"+ min={1}+ max={totalPages}+ value={jumpValue}+ onChange={event => setJumpValue(event.target.value)}+ onKeyDown={handleJumpKeyDown}+ onBlur={() => jumpValue !== "" && goToPage(Number.parseInt(jumpValue, 10))}+ className="w-16 px-2 py-1 rounded-md border border-border bg-panel text-sm text-text placeholder:text-text-muted focus:outline-none"+ placeholder={String(totalPages)}+ />+ <button+ type="button"+ onClick={() => goToPage(Number.parseInt(jumpValue, 10))}+ disabled={jumpValue === ""}+ className="px-3 py-1 rounded-md border border-border hover:bg-secondary/50 disabled:text-text-muted disabled:cursor-not-allowed"+ >+ {t("common.pagination.go")}+ </button>+ </label>+ )}</div>);}diff --git a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsxindex c3958fa3ab..51a1632156 100644--- a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx@@ -14,7 +14,7 @@ import { ConfirmDialog } from '../../components/common/ConfirmDialog';import { useToast } from '../../components/common/useToast';import { buildSourcePresentationParams, sourceSkillIdentity, isSourceSkillInstalled } from './installMetadata';-const PAGE_SIZE = 20;+const PAGE_SIZE_DEFAULT = 20;type LoadState = 'idle' | 'loading' | 'success' | 'error' | 'empty';@@ -104,8 +104,8 @@ function isFresh(at: number): boolean {return Date.now() - at < MOUNT_CACHE_TTL_MS;}-function searchCacheKey(sessionId: string, sourceId: string, q: string, page: number): string {- return `${sessionId}|${sourceId}|${q}|${page}`;+function searchCacheKey(sessionId: string, sourceId: string, q: string, page: number, pageSize: number): string {+ return `${sessionId}|${sourceId}|${q}|${page}|${pageSize}`;}/**@@ -139,13 +139,14 @@ export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, iconst [results, setResults] = useState<SkillCandidate[]>([]);const [total, setTotal] = useState(0);const [page, setPage] = useState(1);+ const [pageSize, setPageSize] = useState(PAGE_SIZE_DEFAULT);const [loadState, setLoadState] = useState<LoadState>('idle');const { toast, showToast, clearToast } = useToast();const [installingId, setInstallingId] = useState<string | null>(null);const [updateStatuses, setUpdateStatuses] = useState<Map<string, UpdateStatus>>(new Map());const [pendingConfirm, setPendingConfirm] = useState<SkillCandidate | null>(null);- const totalPages = useMemo(() => Math.max(1, Math.ceil(total / PAGE_SIZE)), [total]);+ const totalPages = useMemo(() => Math.max(1, Math.ceil(total / pageSize)), [total, pageSize]);const withSession = useCallback((params?: Record<string, unknown>) => ({ ...(params || {}), session_id: sessionId }), [sessionId]);@@ -226,7 +227,7 @@ export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, iasync (targetPage: number, options?: { preferCache?: boolean }) => {if (!sourceId) return;const q = query.trim();- const cacheKey = searchCacheKey(sessionId, sourceId, q, targetPage);+ const cacheKey = searchCacheKey(sessionId, sourceId, q, targetPage, pageSize);if (options?.preferCache) {const cached = searchCache.get(cacheKey);if (cached && isFresh(cached.at)) {@@ -251,7 +252,7 @@ export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, isource_id: sourceId,q,page: targetPage,- page_size: PAGE_SIZE,+ page_size: pageSize,}),);if (!data.success) throw new Error(data.error_message || t('skills.source.errors.searchFailed'));@@ -277,7 +278,7 @@ export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, ishowToast('error', error instanceof Error ? error.message : t('skills.source.errors.searchFailed'));}},- [query, sessionId, showToast, sourceId, t, withSession],+ [pageSize, query, sessionId, showToast, sourceId, t, withSession],);useEffect(() => {@@ -312,6 +313,15 @@ export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, i// eslint-disable-next-line react-hooks/exhaustive-deps}, [query, isExternalQuery]);+ const handlePageSizeChange = useCallback(+ (nextSize: number) => {+ setPageSize(nextSize);+ setPage(1);+ if (sourceId) void runSearch(1);+ },+ [runSearch, sourceId],+ );+const handleInstall = useCallback(async (item: SkillCandidate, force = false) => {if (installingId) return;@@ -583,7 +593,17 @@ export function EnterpriseSkillSourcePanel({ sessionId, installedSkillOrigins, i</div>)}- {loadState === 'success' && <Pagination page={page} totalPages={totalPages} total={total} onPageChange={p => void runSearch(p)} className="mt-3" />}+ {loadState === 'success' && (+ <Pagination+ page={page}+ totalPages={totalPages}+ total={total}+ pageSize={pageSize}+ onPageSizeChange={handlePageSizeChange}+ onPageChange={p => void runSearch(p)}+ className="mt-3"+ />+ )}{pendingConfirm && (<ConfirmDialogtitle={t('skills.source.replaceConfirmTitle')}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 6a2077b689..b39bbd7840 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -18,7 +18,10 @@"pagination": {"total": "{{count}} total","prev": "Previous",- "next": "Next"+ "next": "Next",+ "pageSize": "Per page",+ "jumpTo": "Go to",+ "go": "Go"}},"a2ui": {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 83c7ce2c6d..b214d51f9d 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -18,7 +18,10 @@"pagination": {"total": "共 {{count}} 个","prev": "上一页",- "next": "下一页"+ "next": "下一页",+ "pageSize": "每页",+ "jumpTo": "跳至",+ "go": "确定"}},"a2ui": {diff --git a/jiuwenswarm/server/runtime/skill/enterprise_state_lock.py b/jiuwenswarm/server/runtime/skill/enterprise_state_lock.pynew file mode 100644index 0000000000..5f611de17a--- /dev/null+++ b/jiuwenswarm/server/runtime/skill/enterprise_state_lock.py@@ -0,0 +1,67 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Cross-process transaction lock for enterprise workspace Skill state."""++from __future__ import annotations++import os+import threading+from contextlib import contextmanager+from pathlib import Path+from typing import Iterator+from weakref import WeakValueDictionary++import portalocker+++_LOCK_TIMEOUT_SECONDS = 30.0+_LOCKS_META = threading.Lock()+_PROCESS_LOCKS: "WeakValueDictionary[str, threading.RLock]" = WeakValueDictionary()+_TRANSACTION_DEPTH = threading.local()+++def _process_lock_for(state_file: Path) -> tuple[str, threading.RLock]:+ key = os.path.normcase(str(state_file.resolve()))+ with _LOCKS_META:+ lock = _PROCESS_LOCKS.get(key)+ if lock is None:+ lock = threading.RLock()+ _PROCESS_LOCKS[key] = lock+ return key, lock+++@contextmanager+def enterprise_skill_state_lock(state_file: Path) -> Iterator[bool]:+ """Lock one workspace Skill ledger across threads and AgentServer pods.++ The yielded flag is true only for the outermost transaction in the current+ thread. Callers use it to reload the authoritative JSON once, without+ discarding changes made by nested SkillManager helpers.+ """+ key, process_lock = _process_lock_for(state_file)+ with process_lock:+ depths = getattr(_TRANSACTION_DEPTH, "values", None)+ if depths is None:+ depths = {}+ _TRANSACTION_DEPTH.values = depths+ depth = depths.get(key, 0)+ if depth:+ depths[key] = depth + 1+ try:+ yield False+ finally:+ depths[key] -= 1+ return++ state_file.parent.mkdir(parents=True, exist_ok=True)+ lock_file = state_file.with_name(f"{state_file.name}.lock")+ with portalocker.Lock(+ str(lock_file),+ mode="a+",+ timeout=_LOCK_TIMEOUT_SECONDS,+ ):+ depths[key] = 1+ try:+ yield True+ finally:+ depths.pop(key, None)diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.pyindex 26bb59d133..b50576a29c 100644--- a/jiuwenswarm/server/runtime/skill/skill_manager.py+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py@@ -4,11 +4,11 @@from __future__ import annotations-import loggingimport asyncioimport hashlibimport ioimport json+import loggingimport osimport reimport shutil@@ -16,16 +16,18 @@ import sslimport tarfileimport tempfileimport uuid-from contextlib import contextmanagerimport zipfile-from datetime import datetime, date, timezone+from contextlib import contextmanager+from datetime import date, datetime, timezone+from functools import wrapsfrom pathlib import Path, PurePosixPath, PureWindowsPath-from typing import Any, Awaitable, Callable+from typing import Any, Awaitable, Callable, Iteratorfrom urllib.parse import quote, urlparse-import yaml-import urllib3+import httpximport requests+import urllib3+import yamlfrom requests.adapters import HTTPAdapterfrom urllib3.util.ssl_ import create_urllib3_context@@ -59,6 +61,7 @@ from jiuwenswarm.server.runtime.skill.source_registry import (SourceRegistry,SourceRegistryError,)+from jiuwenswarm.server.runtime.skill.enterprise_state_lock import enterprise_skill_state_lockdef _get_ssl_verify() -> bool:@@ -467,6 +470,31 @@ def _handle_copy_error(exc: OSError, dest: Path, logger_prefix: str, src: Path |}+def _state_transactional(method: Callable[..., Any]) -> Callable[..., Any]:+ """Wrap a SkillManager state-mutating method in the workspace lock.++ The outer-most wrapper reloads the authoritative skills_state.json from+ disk before the body runs, so cross-pod AgentServer instances sharing one+ workspace never overwrite each other's writes (last-writer-wins bug for+ enterprise skill state). Nested wrappers reuse the same transaction and do+ not reload, preserving inner helper mutations.+ """++ @wraps(method)+ async def async_wrapper(self: "SkillManager", *args: Any, **kwargs: Any) -> Any:+ with self.state_transaction():+ return await method(self, *args, **kwargs)++ @wraps(method)+ def sync_wrapper(self: "SkillManager", *args: Any, **kwargs: Any) -> Any:+ with self.state_transaction():+ return method(self, *args, **kwargs)++ if asyncio.iscoroutinefunction(method):+ return async_wrapper+ return sync_wrapper++class SkillManager:"""Skill 管理器,对应 skills.* 请求方法."""@@ -930,6 +958,7 @@ class SkillManager:raise ValueError(f"未找到 skill: {name}")+ @_state_transactionalasync def handle_skills_toggle(self, params: dict) -> dict:"""切换已安装本地 skill 的 enabled 状态。@@ -2346,6 +2375,7 @@ class SkillManager:raise SourceRegistryError(exc.code, str(exc)) from excreturn descriptor, body, dict(verification) if verification is not None else None+ @_state_transactionaldef _commit_source_skill_entity(self,skill_dir: Path,@@ -2654,6 +2684,7 @@ class SkillManager:grouped.setdefault(source_id, []).append(record)items: list[dict[str, Any]] = []+ pending_updates: dict[str, dict[str, Any]] = {}checked_at = datetime.now(timezone.utc).isoformat()for source_id, records in grouped.items():try:@@ -2704,8 +2735,11 @@ class SkillManager:items.append({key: value for key, value in public_status.items() if value is not None})- record.update(- {+ installation_id = str(+ record.get("installation_id") or ""+ ).strip()+ if installation_id:+ pending_updates[installation_id] = {"updatable": bool(status.has_update),"latest_version_id": status.latest_version_id,"latest_version": status.latest_version,@@ -2715,7 +2749,6 @@ class SkillManager:"remote_status": status.remote_status,"update_checked_at": checked_at,}- )except Exception as exc: # noqa: BLE001code = exc.code if isinstance(exc, SourceRegistryError) else "update_check_failed"logger.warning("Skill update check failed: source_id=%s error=%s", source_id, exc)@@ -2733,8 +2766,7 @@ class SkillManager:"checked_at": checked_at,})- if grouped:- self._save_state()+ self._commit_skill_update_statuses(pending_updates)return {"success": True, "items": items, "count": len(items)}async def handle_skills_team_skills_hub_info(self, params: dict) -> dict:@@ -3163,12 +3195,54 @@ class SkillManager:"skill": {"name": skill_name, "source": "skillnet"},}+ @_state_transactional+ def _commit_skillnet_entity(+ self,+ skill_dir: Path,+ *,+ skill_name: str,+ force: bool,+ protected_source_types: frozenset[str],+ ) -> dict[str, Any] | None:+ """Commit a downloaded entity without overwriting protected installations."""+ existing = self._find_skill_installation(name=skill_name)+ existing_type = str((existing or {}).get("source_type") or "").strip()+ if existing_type in protected_source_types:+ return {+ "ok": False,+ "detail": f"skill name already installed as {existing_type}: {skill_name}",+ "error_code": "skill_name_conflict",+ }++ dest = _safe_child_path(self._skills_dir, skill_name, "skill")+ if dest.exists():+ if not force:+ return {+ "ok": False,+ "detail": "该技能已安装。",+ "detail_key": "skills.skillNet.errors.skillAlreadyInstalled",+ }+ _safe_rmtree(dest)++ shutil.copytree(skill_dir, dest)+ for mirror_root in self._get_mirror_skills_dirs():+ mirror_dest = _safe_child_path(mirror_root, skill_name, "skill")+ if mirror_dest.exists():+ if not force:+ continue+ _safe_rmtree(mirror_dest)+ mirror_root.mkdir(parents=True, exist_ok=True)+ shutil.copytree(skill_dir, mirror_dest)+ return None+def _skillnet_install_files_sync(self,skill_url: str,force: bool,mirror_url: str | None = None,checksum_sha256: str = "",+ *,+ protected_source_types: frozenset[str] = frozenset(),) -> dict[str, Any]:"""在工作线程中下载并拷贝到 skills 目录;返回 ok / skill_name / meta / skill_url.@@ -3248,25 +3322,14 @@ class SkillManager:except ValueError as exc:_log_rejected_name("skills.skillnet.install", "skill", raw_skill_name, exc)return {"ok": False, "detail": str(exc)}- dest = _safe_child_path(self._skills_dir, skill_name, "skill")- if dest.exists():- if not force:- return {- "ok": False,- "detail": "该技能已安装。",- "detail_key": "skills.skillNet.errors.skillAlreadyInstalled",- }- _safe_rmtree(dest)-- shutil.copytree(skill_dir, dest)- for mirror_root in self._get_mirror_skills_dirs():- mirror_dest = _safe_child_path(mirror_root, skill_name, "skill")- if mirror_dest.exists():- if not force:- continue- _safe_rmtree(mirror_dest)- mirror_root.mkdir(parents=True, exist_ok=True)- shutil.copytree(skill_dir, mirror_dest)+ commit_error = self._commit_skillnet_entity(+ skill_dir,+ skill_name=skill_name,+ force=force,+ protected_source_types=protected_source_types,+ )+ if commit_error is not None:+ return commit_error_safe_rmtree(skill_dir)return {"ok": True,@@ -3308,6 +3371,8 @@ class SkillManager:force: bool = True,mirror_url: str | None = None,checksum_sha256: str = "",+ *,+ protected_source_types: frozenset[str] = frozenset(),) -> dict[str, Any]:"""同步安装 skill(线程安全,可在 ``asyncio.to_thread`` 中调用).@@ -3315,9 +3380,14 @@ class SkillManager:``checksum_sha256`` 非空时校验归档完整性(管理面预置链路)。"""return self._skillnet_install_files_sync(- skill_url, force, mirror_url, checksum_sha256=checksum_sha256+ skill_url,+ force,+ mirror_url,+ checksum_sha256=checksum_sha256,+ protected_source_types=protected_source_types,)+ @_state_transactionalasync def handle_skills_uninstall(self, params: dict) -> dict:"""卸载已安装的 skill.@@ -3586,6 +3656,88 @@ class SkillManager:if dest.exists() and dest.is_dir():_safe_rmtree(dest)+ @_state_transactional+ def _commit_web_skill_install(+ self,+ skill_dir: Path,+ *,+ skill_name: str,+ skill_version: str | None,+ source_url: str,+ ) -> dict[str, Any]:+ """Commit the user Skill entity and ledger record in one transaction."""+ existing = self._find_skill_installation(name=skill_name)+ if existing is not None:+ existing_type = str(existing.get("source_type") or "").strip()+ existing_origin = str(existing.get("origin") or "").strip()+ existing_version = str(existing.get("version") or "").strip()+ if existing_type == "prebuilt":+ return {+ "success": False,+ "installed": False,+ "error_code": "skill_name_conflict",+ "error_message": (+ f"skill `{skill_name}` is prebuilt and cannot be overwritten"+ ),+ }+ if existing_type != "user" or existing_origin != source_url:+ return {+ "success": False,+ "installed": False,+ "error_code": "skill_name_conflict",+ "error_message": f"skill name already installed: {skill_name}",+ }+ if existing_version == str(skill_version or ""):+ return {+ "success": False,+ "installed": False,+ "already_installed": True,+ "error_code": "skill_already_installed",+ "name": skill_name,+ "error_message": (+ f"skill `{skill_name}` already installed with the same version"+ ),+ }++ import_result = self._install_web_skill_dir(skill_dir, skill_name=skill_name)+ if not import_result.get("success"):+ return {+ "success": False,+ "error_code": "install_failed",+ "error_message": str(import_result.get("detail") or "install failed"),+ }+ installed_name = str(+ (import_result.get("skill") or {}).get("name") or skill_name+ ).strip()++ try:+ self.record_skill_installation(+ name=installed_name,+ source_type="user",+ source="web",+ origin=source_url,+ version=str(skill_version or ""),+ )+ except SkillNameConflictError as exc:+ self.remove_skill_directory(installed_name)+ return {+ "success": False,+ "installed": False,+ "error_code": "skill_name_conflict",+ "error_message": str(exc),+ }+ except Exception as exc: # noqa: BLE001+ self.remove_skill_directory(installed_name)+ return {+ "success": False,+ "error_code": "state_write_failed",+ "error_message": str(exc)[:500],+ }+ return {+ "success": True,+ "skill": {"name": installed_name, "version": skill_version},+ }+async def handle_skills_web_install(self, params: dict) -> dict:"""企业 Web 安装兼容入口:下载、校验、落盘并提交 workspace JSON。"""from jiuwenswarm.agents.harness.common.installed_skill import (@@ -3659,73 +3811,12 @@ class SkillManager:}skill_version = str(meta.get("version") or "").strip() or None- existing = self._find_skill_installation(name=skill_name)- if existing is not None:- existing_type = str(existing.get("source_type") or "").strip()- existing_origin = str(existing.get("origin") or "").strip()- existing_version = str(existing.get("version") or "").strip()- if existing_type == "prebuilt":- return {- "success": False,- "installed": False,- "error_code": "skill_name_conflict",- "error_message": (- f"skill `{skill_name}` is prebuilt and cannot be overwritten"- ),- }- if existing_type != "user" or existing_origin != url:- return {- "success": False,- "installed": False,- "error_code": "skill_name_conflict",- "error_message": f"skill name already installed: {skill_name}",- }- if existing_version == str(skill_version or ""):- return {- "success": False,- "installed": False,- "already_installed": True,- "error_code": "skill_already_installed",- "name": skill_name,- "error_message": (- f"skill `{skill_name}` already installed with the same version"- ),- }-- import_result = self._install_web_skill_dir(skill_dir, skill_name=skill_name)- if not import_result.get("success"):- return {- "success": False,- "error_code": "install_failed",- "error_message": str(import_result.get("detail") or "install failed"),- }- skill_name = str((import_result.get("skill") or {}).get("name") or skill_name).strip()-- try:- self.record_skill_installation(- name=skill_name,- source_type="user",- source="web",- origin=url,- version=str(skill_version or ""),- )- except SkillNameConflictError as exc:- self.remove_skill_directory(skill_name)- return {- "success": False,- "installed": False,- "error_code": "skill_name_conflict",- "error_message": str(exc),- }- except Exception as exc: # noqa: BLE001- self.remove_skill_directory(skill_name)- return {- "success": False,- "error_code": "state_write_failed",- "error_message": str(exc)[:500],- }-- return {"success": True, "skill": {"name": skill_name, "version": skill_version}}+ return self._commit_web_skill_install(+ skill_dir,+ skill_name=skill_name,+ skill_version=skill_version,+ source_url=url,+ )async def handle_skills_web_uninstall(self, params: dict) -> dict:"""企业 Web 卸载兼容入口:仅允许删除 workspace 中的 user 安装。"""@@ -5690,6 +5781,25 @@ class SkillManager:# 状态持久化# -----------------------------------------------------------------------+ @contextmanager+ def state_transaction(self) -> Iterator[None]:+ """Reload and mutate enterprise Skill state under one workspace lock.++ Public transaction entry used by the ``_state_transactional`` decorator+ and by user-install / uninstall / whitelist paths that mutate+ ``skills_state.json``. Holds a cross-pod file lock (portalocker) on the+ workspace ledger so concurrent AgentServer pods sharing one workspace+ never lose each other's writes. Non-enterprise or non-persistent+ instances yield immediately (no lock, no reload).+ """+ if not is_enterprise() or not self._persist_skills_state:+ yield+ return+ with enterprise_skill_state_lock(self._state_file) as outermost:+ if outermost:+ self._state = self._load_state()+ yield+def _load_state(self) -> dict[str, Any]:"""加载 skills_state.json,失败时返回默认空状态."""try:@@ -5936,6 +6046,7 @@ class SkillManager:return recordreturn None+ @_state_transactionaldef record_skill_installation(self,*,@@ -6047,6 +6158,7 @@ class SkillManager:self._save_state()return dict(record)+ @_state_transactionaldef remove_skill_installation(self,*,@@ -6068,6 +6180,66 @@ class SkillManager:self._save_state()return True+ @_state_transactional+ def remove_skill_installation_entity(+ self,+ *,+ name: str,+ origin: str | None = None,+ expected_source_type: str,+ ) -> bool:+ """Atomically remove a guarded installation record and its skill entity.++ The record is reloaded and its source type is checked before touching+ disk. This prevents a stale prebuilt synchronizer from deleting a+ same-name user skill that another AgentServer pod has installed.+ """+ record = self._find_skill_installation(name=name, origin=origin)+ if record is None:+ return False+ expected = str(expected_source_type or "").strip()+ if not expected or str(record.get("source_type") or "").strip() != expected:+ return False++ entity_dir = _safe_path_name(+ str(record.get("entity_dir") or record.get("name") or name),+ "skill",+ )+ entity_path = _safe_child_path(self._skills_dir, entity_dir, "skill")+ if entity_path.is_dir():+ _safe_rmtree(entity_path)+ for mirror_root in self._get_mirror_skills_dirs():+ mirror_path = _safe_child_path(mirror_root, entity_dir, "skill")+ if mirror_path.is_dir():+ _safe_rmtree(mirror_path)++ return self.remove_skill_installation(+ name=name,+ origin=origin,+ expected_source_type=expected,+ )++ @_state_transactional+ def _commit_skill_update_statuses(+ self,+ updates: dict[str, dict[str, Any]],+ ) -> None:+ """Merge update-check results into the latest workspace ledger."""+ if not updates:+ return+ changed = False+ for record in self._get_installed_plugins():+ if not isinstance(record, dict):+ continue+ installation_id = str(record.get("installation_id") or "").strip()+ values = updates.get(installation_id)+ if values is None:+ continue+ record.update(values)+ changed = True+ if changed:+ self._save_state()+def list_enabled_skill_names(self) -> list[str]:"""Return enabled, disk-backed skill names for the current workspace."""names: list[str] = []@@ -6136,6 +6308,7 @@ class SkillManager:origins.add(f"clawhub:{child.name}")return origins+ @_state_transactionaldef _register_unmanaged_local_skills(self) -> None:"""Auto-register skills that exist on disk but were never recorded.diff --git a/jiuwenswarm/server/runtime/skill/skill_prebuilt.py b/jiuwenswarm/server/runtime/skill/skill_prebuilt.pyindex b8d85f4e89..110dc1c378 100644--- a/jiuwenswarm/server/runtime/skill/skill_prebuilt.py+++ b/jiuwenswarm/server/runtime/skill/skill_prebuilt.py@@ -440,17 +440,17 @@ class SkillPrebuiltSynchronizer:if name in kept_prebuilt_names:continuetry:- self._remove_installed_dir(name)- removed = self._manager.remove_skill_installation(+ removed = self._manager.remove_skill_installation_entity(name=name,origin=str(row.get("origin") or "") or None,expected_source_type=SOURCE_PREBUILT,)if not removed:logger.warning(- "[SkillPrebuilt] prebuilt record not found in workspace, disk already cleaned: %s",+ "[SkillPrebuilt] prebuilt record no longer matches workspace: %s",name,)+ continueresult.succeeded.append(f"removed:{name}")installed_skills_map.pop(name, None)except Exception as exc: # noqa: BLE001@@ -523,6 +523,7 @@ class SkillPrebuiltSynchronizer:True,None,item.sha256,+ protected_source_types=frozenset({SOURCE_USER}),)except Exception as exc:return {@@ -561,7 +562,7 @@ class SkillPrebuiltSynchronizer:),}- # 同名 user 记录视为"提升"为 prebuilt+ # 预置同步不得改变用户自安装技能的身份或实体。existing_user = Nonefor record in self._manager.list_skill_installations():if (@@ -571,13 +572,12 @@ class SkillPrebuiltSynchronizer:existing_user = recordbreakif existing_user is not None:- self._manager.remove_skill_installation(- name=installed_dir,- expected_source_type=SOURCE_USER,- )- logger.info(- "[SkillPrebuilt] promote user→prebuilt skill_name=%s", installed_dir- )+ return {+ "ok": False,+ "skill_name": installed_dir,+ "error_code": "skill_name_conflict",+ "error_message": f"prebuilt skill conflicts with user skill: {installed_dir}",+ }origin = (f"{item.source_id}:{item.id}"@@ -598,7 +598,6 @@ class SkillPrebuiltSynchronizer:replace_by_name=True,)except SkillNameConflictError as exc:- self._restore_promoted_user(existing_user, installed_dir)if need_download and mode == "url":self._remove_installed_dir(installed_dir)return {@@ -608,7 +607,6 @@ class SkillPrebuiltSynchronizer:"error_message": f"skill name conflict id={item.id} name={installed_dir}: {exc}",}except Exception as exc:- self._restore_promoted_user(existing_user, installed_dir)if need_download and mode == "url":self._remove_installed_dir(installed_dir)return {@@ -622,26 +620,3 @@ class SkillPrebuiltSynchronizer:installed_skills_map.pop(previous_skill_name, None)return {"ok": True, "skill_name": installed_dir, "row": row}-- def _restore_promoted_user(- self, existing_user: dict[str, Any] | None, installed_dir: str- ) -> None:- """恢复"提升 user→prebuilt"失败时被删除的 user 记录,避免技能进入孤儿状态。"""- if not existing_user:- return- try:- self._manager.record_skill_installation(- name=installed_dir,- source_type=SOURCE_USER,- origin=str(existing_user.get("origin") or ""),- source=str(existing_user.get("source") or ""),- version=str(existing_user.get("version") or ""),- )- except Exception as exc: # noqa: BLE001- logger.warning(- "[SkillPrebuilt] rollback user record failed skill_name=%s error=%s",- installed_dir,- exc,- )--diff --git a/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py b/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.pyindex 2e69ded1e8..a2d594f8c9 100644--- a/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py+++ b/tests/unit_tests/agentserver/test_skill_manager_enterprise_state.py@@ -9,6 +9,11 @@ from pathlib import Pathimport pytestfrom jiuwenswarm.server.runtime.skill.skill_manager import SkillManager+from jiuwenswarm.server.runtime.skill.skill_prebuilt import (+ SkillPrebuiltItem,+ SkillPrebuiltSyncResult,+ SkillPrebuiltSynchronizer,+)def _write_skill(workspace: Path, name: str) -> Path:@@ -204,3 +209,201 @@ def test_enterprise_skills_list_does_not_wait_for_marketplace_sync()assert isinstance(payload["skills"], list)+++def test_user_skill_toggle_does_not_overwrite_another_pod_install(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workspace = tmp_path / "tenant"+ builtin_dir = tmp_path / "builtin"+ builtin_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.is_enterprise",+ lambda: True,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.get_builtin_skills_dir",+ lambda: builtin_dir,+ )+ first = SkillManager(workspace_dir=str(workspace))+ first.record_skill_installation(+ name="first-user-skill", source_type="user", origin="skillhub:first"+ )+ stale = SkillManager(workspace_dir=str(workspace))+ another_pod = SkillManager(workspace_dir=str(workspace))+ another_pod.record_skill_installation(+ name="second-user-skill", source_type="user", origin="skillhub:second"+ )++ result = asyncio.run(+ stale.handle_skills_toggle(+ {"name": "first-user-skill", "origin": "skillhub:first", "enabled": False}+ )+ )++ assert result["success"] is True+ persisted = SkillManager(workspace_dir=str(workspace)).list_skill_installations()+ assert {row["name"] for row in persisted} == {+ "first-user-skill",+ "second-user-skill",+ }+++def test_prebuilt_sync_never_promotes_or_replaces_same_name_user_skill(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workspace = tmp_path / "tenant"+ builtin_dir = tmp_path / "builtin"+ builtin_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.is_enterprise",+ lambda: True,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.get_builtin_skills_dir",+ lambda: builtin_dir,+ )+ manager = SkillManager(workspace_dir=str(workspace))+ _write_skill(workspace, "user-skill")+ user_record = manager.record_skill_installation(+ name="user-skill",+ source_type="user",+ source="swarmskillhub",+ origin="swarmskillhub:user-asset",+ source_id="swarmskillhub",+ skill_id="user-asset",+ version_id="user-version",+ version="1.0.0",+ )+ synchronizer = SkillPrebuiltSynchronizer(+ workspace,+ service_id="service-a",+ agent_id="agent-a",+ skill_manager=manager,+ )+ skill_md = workspace / "skills" / "user-skill" / "SKILL.md"+ original_content = skill_md.read_text(encoding="utf-8")+ monkeypatch.setattr(+ manager,+ "_assert_skill_download_url_allowed",+ lambda _url: None,+ )+ monkeypatch.setattr(+ manager,+ "_download_http_archive_bytes_sync",+ lambda _url: _skill_archive("user-skill", "2.0.0"),+ )+ outcome = asyncio.run(+ synchronizer._ensure_prebuilt_installed(+ SkillPrebuiltItem(+ id="prebuilt-asset",+ source="https://skills.example/prebuilt.zip",+ version="2.0.0",+ ),+ {"user-skill": user_record},+ )+ )++ assert outcome["ok"] is False+ assert outcome["error_code"] == "skill_name_conflict"+ assert manager.list_skill_installations() == [user_record]+ assert skill_md.read_text(encoding="utf-8") == original_content+++def test_update_status_commit_preserves_another_pod_install(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workspace = tmp_path / "tenant"+ builtin_dir = tmp_path / "builtin"+ builtin_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.is_enterprise",+ lambda: True,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.get_builtin_skills_dir",+ lambda: builtin_dir,+ )+ first = SkillManager(workspace_dir=str(workspace))+ first_record = first.record_skill_installation(+ name="first-user-skill",+ source_type="user",+ source_id="swarmskillhub",+ skill_id="first",+ version_id="v1",+ )+ stale = SkillManager(workspace_dir=str(workspace))+ another_pod = SkillManager(workspace_dir=str(workspace))+ another_pod.record_skill_installation(+ name="second-user-skill",+ source_type="user",+ source_id="swarmskillhub",+ skill_id="second",+ version_id="v1",+ )++ stale._commit_skill_update_statuses(+ {first_record["installation_id"]: {"updatable": True}}+ )++ persisted = SkillManager(workspace_dir=str(workspace)).list_skill_installations()+ assert {row["name"] for row in persisted} == {+ "first-user-skill",+ "second-user-skill",+ }+ assert next(row for row in persisted if row["name"] == "first-user-skill")[+ "updatable"+ ] is True+++def test_stale_prebuilt_removal_does_not_delete_same_name_user_skill(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workspace = tmp_path / "tenant"+ builtin_dir = tmp_path / "builtin"+ builtin_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.is_enterprise",+ lambda: True,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.skill.skill_manager.get_builtin_skills_dir",+ lambda: builtin_dir,+ )+ manager = SkillManager(workspace_dir=str(workspace))+ skill_dir = _write_skill(workspace, "shared-name")+ user_record = manager.record_skill_installation(+ name="shared-name",+ source_type="user",+ source_id="swarmskillhub",+ skill_id="user-asset",+ version_id="v1",+ )+ synchronizer = SkillPrebuiltSynchronizer(+ workspace,+ service_id="service-a",+ agent_id="agent-a",+ skill_manager=manager,+ )+ stale_prebuilt_row = {+ "name": "shared-name",+ "source_type": "prebuilt",+ "origin": "https://skills.example/old-prebuilt.zip",+ }+ result = SkillPrebuiltSyncResult()++ asyncio.run(+ synchronizer._remove_prebuilt_not_in_template(+ {"shared-name": stale_prebuilt_row},+ set(),+ result,+ )+ )++ assert skill_dir.is_dir()+ assert manager.list_skill_installations() == [user_record]+ assert result.succeeded == []