skillsSection.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. import { createElement } from "react";
  2. import { renderToStaticMarkup } from "react-dom/server";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. const capturedButtons: Array<Record<string, unknown>> = [];
  5. const capturedSwitches: Array<Record<string, unknown>> = [];
  6. const openInFileManagerMock = vi.fn(async () => ({ success: true }));
  7. const onCreateTaskMock = vi.fn();
  8. const activateTabByPathMock = vi.fn();
  9. const startDraftMock = vi.fn();
  10. const setPendingComposerPrefillMock = vi.fn();
  11. const invalidateDraftRuntimeMock = vi.fn();
  12. const mockSkillsServiceList = vi.fn(async () => ({
  13. skills: [],
  14. capability: { userScopeAvailable: true },
  15. diagnostics: [],
  16. }));
  17. const mockSkillsServiceSetEnabled = vi.fn(async () => {});
  18. let useStateCallCount = 0;
  19. let mockSkillsState: unknown = [];
  20. let mockCapabilityState: unknown = null;
  21. let mockLoadedSkillTargetKeyState = "remote:ssh:dev:/tmp/workspace";
  22. let mockSelectedSkillState: unknown = null;
  23. let mockDiagnosticsState: unknown = [];
  24. let mockDiagnosticsOpenState = false;
  25. let activeWorkspacePath: string | null = "/tmp/workspace";
  26. let activeWorkspaceIdentity: string | undefined = "remote:ssh:dev:/tmp/workspace";
  27. let activeRemoteSessionId: string | undefined;
  28. let activeRemoteTarget: unknown;
  29. let activeScopeFilter: "user" | "workspace" = "workspace";
  30. vi.mock("react", async () => {
  31. const actual = await vi.importActual<typeof import("react")>("react");
  32. return {
  33. ...actual,
  34. useState: (initialValue: unknown) => {
  35. useStateCallCount += 1;
  36. if (useStateCallCount === 1) {
  37. return [mockSkillsState, vi.fn()] as const;
  38. }
  39. if (useStateCallCount === 2) {
  40. return [mockCapabilityState ?? initialValue, vi.fn()] as const;
  41. }
  42. if (useStateCallCount === 3) {
  43. return [mockLoadedSkillTargetKeyState, vi.fn()] as const;
  44. }
  45. if (useStateCallCount === 6) {
  46. return [mockSelectedSkillState, vi.fn()] as const;
  47. }
  48. if (useStateCallCount === 7) {
  49. return [mockDiagnosticsState, vi.fn()] as const;
  50. }
  51. if (useStateCallCount === 8) {
  52. return [mockDiagnosticsOpenState, vi.fn()] as const;
  53. }
  54. return [initialValue, vi.fn()] as const;
  55. },
  56. };
  57. });
  58. vi.mock("lucide-react", () => ({
  59. AlertTriangle: (props: Record<string, unknown>) => createElement("svg", props),
  60. ChevronDown: (props: Record<string, unknown>) => createElement("svg", props),
  61. ChevronDownIcon: (props: Record<string, unknown>) => createElement("svg", props),
  62. ChevronRight: (props: Record<string, unknown>) => createElement("svg", props),
  63. ChevronUpIcon: (props: Record<string, unknown>) => createElement("svg", props),
  64. CheckIcon: (props: Record<string, unknown>) => createElement("svg", props),
  65. Download: (props: Record<string, unknown>) => createElement("svg", props),
  66. ExternalLink: (props: Record<string, unknown>) => createElement("svg", props),
  67. Folder: (props: Record<string, unknown>) => createElement("svg", props),
  68. Import: (props: Record<string, unknown>) => createElement("svg", props),
  69. SquareArrowRightEnter: (props: Record<string, unknown>) => createElement("svg", props),
  70. LayersPlus: (props: Record<string, unknown>) => createElement("svg", props),
  71. Loader2: (props: Record<string, unknown>) => createElement("svg", props),
  72. Loader2Icon: (props: Record<string, unknown>) => createElement("svg", props),
  73. MinusIcon: (props: Record<string, unknown>) => createElement("svg", props),
  74. MoreHorizontal: (props: Record<string, unknown>) => createElement("svg", props),
  75. Plus: (props: Record<string, unknown>) => createElement("svg", props),
  76. RefreshCcw: (props: Record<string, unknown>) => createElement("svg", props),
  77. Cable: (props: Record<string, unknown>) => createElement("svg", props),
  78. Search: (props: Record<string, unknown>) => createElement("svg", props),
  79. Settings2: (props: Record<string, unknown>) => createElement("svg", props),
  80. Trash2: (props: Record<string, unknown>) => createElement("svg", props),
  81. UploadCloud: (props: Record<string, unknown>) => createElement("svg", props),
  82. UserRound: (props: Record<string, unknown>) => createElement("svg", props),
  83. WandSparkles: (props: Record<string, unknown>) => createElement("svg", props),
  84. }));
  85. vi.mock("@/components/ui/button.js", () => ({
  86. Button: ({ children, ...props }: { children: unknown; [key: string]: unknown }) => {
  87. capturedButtons.push({ children, ...props });
  88. return createElement("button", props, children);
  89. },
  90. }));
  91. vi.mock("@/ControlHintTooltip.js", () => ({
  92. ControlHintTooltip: ({ children }: { children: unknown }) => children,
  93. }));
  94. vi.mock("@/components/ui/input.js", () => ({
  95. Input: (props: Record<string, unknown>) => createElement("input", props),
  96. }));
  97. vi.mock("@/components/ui/progress.js", () => ({
  98. Progress: (props: Record<string, unknown>) => createElement("progress", props),
  99. }));
  100. vi.mock("@/components/ui/dialog.js", () => ({
  101. Dialog: ({ open, children }: { open: boolean; children: unknown }) =>
  102. open ? createElement("div", { "data-dialog-open": true }, children) : null,
  103. DialogContent: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  104. createElement("div", props, children),
  105. DialogFooter: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  106. createElement("div", props, children),
  107. DialogHeader: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  108. createElement("div", props, children),
  109. DialogTitle: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  110. createElement("h2", props, children),
  111. }));
  112. vi.mock("@/components/ui/switch.js", () => ({
  113. Switch: (props: Record<string, unknown>) => {
  114. capturedSwitches.push(props);
  115. return createElement("input", { type: "checkbox", ...props });
  116. },
  117. }));
  118. vi.mock("@/i18n/IntlProvider.js", () => ({
  119. useZCodeIntl: () => ({
  120. intl: {
  121. formatMessage: ({ id }: { id: string }, values?: Record<string, string | number>) => {
  122. const messages: Record<string, string> = {
  123. "settings.skills.description": "Manage workspace and user skills.",
  124. "common.refresh": "Refresh",
  125. "settings.resourceActions.import": "Import",
  126. "settings.resourceActions.export": "Export",
  127. "settings.resourceActions.more": "More actions",
  128. "settings.create.action": "New",
  129. "settings.skills.create.open": "New Skill",
  130. "settings.skills.import.open": "Import skills from external agents",
  131. "settings.skills.remoteContext": `Current remote workspace: ${values?.target ?? ""}`,
  132. "settings.skills.remoteSync.open": "Sync Skill",
  133. "settings.skills.import.title": "Import external agent skills",
  134. "settings.skills.import.description": "Scan reusable skills.",
  135. "settings.skills.import.scanning": "Scanning importable skills...",
  136. "settings.skills.import.empty": "No importable skills found.",
  137. "settings.skills.import.summary": `Found ${values?.count ?? 0} importable skills`,
  138. "settings.skills.import.selectAll": "Select all",
  139. "settings.skills.import.clearAll": "Clear all",
  140. "settings.skills.import.selectionCount": `${values?.selected ?? 0}/${values?.total ?? 0} selected`,
  141. "settings.skills.import.start": "Import selected skills",
  142. "settings.skills.import.targetLabel": "Import target",
  143. "settings.skills.import.target.global": "Import to Global",
  144. "settings.skills.import.target.project": "Import to Project",
  145. "settings.skills.import.modeLabel": "Import mode",
  146. "settings.skills.import.modeHelp": "Import mode help",
  147. "settings.skills.import.mode.copy": "Copy",
  148. "settings.skills.import.mode.symlink": "Symlink",
  149. "settings.skills.import.mode.copy.description": "Copy mode",
  150. "settings.skills.import.mode.symlink.description": "Symlink mode",
  151. "settings.skills.import.importing": "Importing skills into ZCode",
  152. "settings.skills.import.imported": "Imported",
  153. "settings.skills.import.skipped": "Skipped",
  154. "settings.skills.import.failed": "Failed",
  155. "settings.skills.import.completeDescription": "The skills list has been refreshed.",
  156. "settings.skills.import.finish": "Done",
  157. "settings.skills.refresh": "Refresh",
  158. "settings.skills.refreshing": "Refreshing...",
  159. "settings.skills.searchPlaceholder": "Search skills...",
  160. "settings.skills.filter.label": "Source Filter",
  161. "appHeader.openInFileManagerFailed": "Failed to open folder",
  162. "settings.skills.agent.claude": "Claude",
  163. "settings.skills.agent.agents": "Codex",
  164. "settings.skills.agent.opencode": "OpenCode",
  165. "settings.skills.agent.gemini": "Gemini",
  166. "settings.modelProvider.testModel.agentName.zcode_agent": "ZCode Agent",
  167. "settings.skills.empty": "No skills found",
  168. "settings.skills.noDescription": "No description",
  169. "settings.skills.detail.description": "Description",
  170. "settings.skills.detail.path": "File path",
  171. "settings.skills.detail.openPath": "Open",
  172. "settings.skills.detail.scope": "Scope",
  173. "settings.skills.detail.status": "Status",
  174. "settings.skills.detail.version": "Version",
  175. "settings.skills.detail.slug": "Slug",
  176. "settings.skills.detail.ownerId": "Owner ID",
  177. "settings.skills.detail.publishedAt": "Published at",
  178. "settings.skills.detail.enabled": "Enabled",
  179. "settings.skills.detail.disabled": "Disabled",
  180. "settings.skills.scope.personal": "Personal",
  181. "settings.skills.scope.plugin": "Plugin",
  182. "settings.skills.scope.workspaceFallback": "Project",
  183. "settings.skills.diagnostics.summary":
  184. `Skill diagnostics: ${values?.errorCount ?? 0} error(s), ` +
  185. `${values?.warningCount ?? 0} warning(s)`,
  186. "settings.skills.diagnostics.expand": "Expand diagnostics",
  187. "settings.skills.diagnostics.collapse": "Collapse diagnostics",
  188. "settings.skills.diagnostics.code.skill_missing_frontmatter": "Missing YAML frontmatter",
  189. "settings.skills.diagnostics.code.skill_invalid_name": "Invalid skill name",
  190. "settings.skills.diagnostics.code.skill_unknown_frontmatter": "Unknown frontmatter key",
  191. "settings.skills.copyToCommon": "Copy to Common",
  192. "settings.skills.removeFromCommon": "Remove from Common",
  193. "settingsSync.action.skip": "Not now",
  194. "settingsSync.action.rescan": "Scan again",
  195. "settingsSync.agent.zcode": "ZCode Agent",
  196. "settingsSync.agent.claudeCode": "Claude Code",
  197. "settingsSync.agent.codexCli": "Codex CLI",
  198. "settingsSync.agent.openCode": "OpenCode",
  199. "settingsSync.agent.agents": "Shared .agents",
  200. "settingsSync.category.skills": "Skills",
  201. "settingsSync.category.skills.description": "Copy local skills",
  202. "settingsSync.category.default.description": "Importable settings.",
  203. "onboarding.agentSettings.categoryToggleAllAria": "Toggle category",
  204. };
  205. return messages[id] ?? id;
  206. },
  207. },
  208. }),
  209. }));
  210. vi.mock("@/store/TabStoreProvider.js", () => ({
  211. useTabStore: (selector: (state: Record<string, unknown>) => unknown) => {
  212. const activeWorkspaceTab = {
  213. id: `workspace:${activeWorkspacePath ?? ""}`,
  214. kind: "workspace",
  215. label: "workspace",
  216. workspacePath: activeWorkspacePath,
  217. workspaceIdentity: activeWorkspaceIdentity,
  218. remoteSessionId: activeRemoteSessionId,
  219. remoteTarget: activeRemoteTarget,
  220. };
  221. return selector({
  222. // Bugfix: useWorkspaceServices 会通过 tabs/activeTabId 识别远程 workspace,
  223. // 测试桩也要保持 TabStoreState 的最小真实形态,否则会在渲染阶段先于断言崩溃。
  224. activeTabId: activeWorkspaceTab.id,
  225. activeWorkspacePath: activeWorkspaceTab.workspacePath,
  226. activeWorkspaceIdentity: activeWorkspaceTab.workspaceIdentity,
  227. tabs: [activeWorkspaceTab],
  228. activateTabByPath: activateTabByPathMock,
  229. });
  230. },
  231. }));
  232. vi.mock("@/store/zcodeSessionStore.js", () => ({
  233. useZCodeSessionStore: Object.assign(
  234. (selector: (state: Record<string, unknown>) => unknown) =>
  235. selector({
  236. getWorkspaceState: () => ({
  237. selectedProvider: "claude",
  238. activeTaskId: null,
  239. }),
  240. startDraft: startDraftMock,
  241. setPendingComposerPrefill: setPendingComposerPrefillMock,
  242. invalidateDraftRuntime: invalidateDraftRuntimeMock,
  243. }),
  244. {
  245. getState: () => ({
  246. getWorkspaceState: () => ({
  247. selectedProvider: "claude",
  248. activeTaskId: null,
  249. }),
  250. startDraft: startDraftMock,
  251. setPendingComposerPrefill: setPendingComposerPrefillMock,
  252. invalidateDraftRuntime: invalidateDraftRuntimeMock,
  253. }),
  254. },
  255. ),
  256. }));
  257. vi.mock("@/hooks/usePlatform.js", () => ({
  258. usePlatform: () => ({
  259. openInFileManager: openInFileManagerMock,
  260. }),
  261. }));
  262. vi.mock("@/components/ui/toast.js", () => ({
  263. toast: vi.fn(),
  264. }));
  265. vi.mock("@/hooks/useServices.js", () => ({
  266. useServices: () => ({
  267. skillsService: {
  268. list: mockSkillsServiceList,
  269. setEnabled: mockSkillsServiceSetEnabled,
  270. },
  271. skillSyncService: {
  272. listLocalUserSkillCandidates: vi.fn(async () => ({
  273. candidates: [],
  274. maxArchiveBytes: 0,
  275. })),
  276. listRemoteUserSkillStatuses: vi.fn(async () => ({ statuses: [] })),
  277. exportSkillsArchive: vi.fn(async () => ({
  278. archive: new Uint8Array(),
  279. archiveBytes: 0,
  280. skills: [],
  281. })),
  282. checkRemoteUserSkillWriteAccess: vi.fn(async () => ({
  283. ok: true,
  284. path: "/home/dev/.zcode/skills",
  285. })),
  286. importSkillsArchive: vi.fn(async () => ({ results: [] })),
  287. },
  288. mcpSyncService: {},
  289. settingsSyncService: {
  290. detect: vi.fn(async () => ({ agents: [] })),
  291. importSelected: vi.fn(async () => ({
  292. successCount: 0,
  293. skippedCount: 0,
  294. failedCount: 0,
  295. taskResults: [],
  296. })),
  297. },
  298. }),
  299. }));
  300. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  301. useWorkspaceServicesResolution: () => ({
  302. services: {
  303. pluginManagementService: {},
  304. skillsService: {
  305. list: mockSkillsServiceList,
  306. setEnabled: mockSkillsServiceSetEnabled,
  307. },
  308. skillSyncService: {
  309. listLocalUserSkillCandidates: vi.fn(async () => ({
  310. candidates: [],
  311. maxArchiveBytes: 0,
  312. })),
  313. listRemoteUserSkillStatuses: vi.fn(async () => ({ statuses: [] })),
  314. exportSkillsArchive: vi.fn(async () => ({
  315. archive: new Uint8Array(),
  316. archiveBytes: 0,
  317. skills: [],
  318. })),
  319. checkRemoteUserSkillWriteAccess: vi.fn(async () => ({
  320. ok: true,
  321. path: "/home/dev/.zcode/skills",
  322. })),
  323. importSkillsArchive: vi.fn(async () => ({ results: [] })),
  324. },
  325. },
  326. remoteSessionId: activeRemoteSessionId ?? null,
  327. isRemoteTarget: Boolean(activeWorkspaceIdentity || activeRemoteSessionId || activeRemoteTarget),
  328. connectionKind: activeWorkspaceIdentity ? "remote-ready" : "local-ready",
  329. rpcReady: true,
  330. }),
  331. useWorkspaceServices: () => ({
  332. zcodeTaskService: {
  333. createTask: vi.fn(async () => ({
  334. taskId: "task-1",
  335. provider: "claude",
  336. initialSlashCommands: [],
  337. })),
  338. },
  339. }),
  340. useBaseWorkspaceServices: () => ({
  341. skillSyncService: {
  342. listLocalUserSkillCandidates: vi.fn(async () => ({
  343. candidates: [],
  344. maxArchiveBytes: 0,
  345. })),
  346. listRemoteUserSkillStatuses: vi.fn(async () => ({ statuses: [] })),
  347. exportSkillsArchive: vi.fn(async () => ({
  348. archive: new Uint8Array(),
  349. archiveBytes: 0,
  350. skills: [],
  351. })),
  352. checkRemoteUserSkillWriteAccess: vi.fn(async () => ({
  353. ok: true,
  354. path: "/home/dev/.zcode/skills",
  355. })),
  356. importSkillsArchive: vi.fn(async () => ({ results: [] })),
  357. },
  358. mcpSyncService: {},
  359. }),
  360. }));
  361. vi.mock("@/lib/providerCliIcon.js", () => ({
  362. renderProviderCliIcon: () => createElement("span", null, "icon"),
  363. }));
  364. async function renderSkillsSection() {
  365. useStateCallCount = 0;
  366. mockLoadedSkillTargetKeyState = activeWorkspaceIdentity?.trim() || activeWorkspacePath || "";
  367. const { SkillsSection } = await import("../src/settings/SkillsSection.js");
  368. return renderToStaticMarkup(
  369. createElement(SkillsSection, {
  370. workspacePath: activeWorkspacePath,
  371. workspaceIdentity: activeWorkspaceIdentity,
  372. remoteSessionId: activeRemoteSessionId,
  373. remoteTarget: activeRemoteTarget,
  374. scopeFilter: activeScopeFilter,
  375. searchQuery: "",
  376. onCreateTask: onCreateTaskMock,
  377. }),
  378. );
  379. }
  380. function findButton(label: string) {
  381. return capturedButtons.find(
  382. (button) => button.children === label || button["aria-label"] === label,
  383. );
  384. }
  385. function findLinkButtonByLabel(label: string) {
  386. return capturedButtons.find(
  387. (button) =>
  388. button.variant === "link" && (button.children === label || button["aria-label"] === label),
  389. );
  390. }
  391. function findCreateSkillButton() {
  392. return capturedButtons.find(
  393. (button) => button["aria-label"] === "New" && typeof button.onClick === "function",
  394. );
  395. }
  396. describe("SkillsSection", () => {
  397. beforeEach(() => {
  398. capturedButtons.length = 0;
  399. capturedSwitches.length = 0;
  400. activateTabByPathMock.mockClear();
  401. onCreateTaskMock.mockClear();
  402. startDraftMock.mockClear();
  403. setPendingComposerPrefillMock.mockClear();
  404. invalidateDraftRuntimeMock.mockClear();
  405. openInFileManagerMock.mockClear();
  406. mockSkillsServiceList.mockClear();
  407. mockSkillsServiceList.mockResolvedValue({
  408. skills: [],
  409. capability: { userScopeAvailable: true },
  410. diagnostics: [],
  411. });
  412. mockSkillsServiceSetEnabled.mockClear();
  413. mockCapabilityState = null;
  414. mockSkillsState = [];
  415. mockLoadedSkillTargetKeyState = "remote:ssh:dev:/tmp/workspace";
  416. mockSelectedSkillState = null;
  417. mockDiagnosticsState = [];
  418. mockDiagnosticsOpenState = false;
  419. activeWorkspacePath = "/tmp/workspace";
  420. activeWorkspaceIdentity = "remote:ssh:dev:/tmp/workspace";
  421. activeRemoteSessionId = undefined;
  422. activeRemoteTarget = undefined;
  423. activeScopeFilter = "workspace";
  424. useStateCallCount = 0;
  425. });
  426. afterEach(() => {
  427. vi.resetModules();
  428. });
  429. it("顶部展示统一刷新按钮", async () => {
  430. await renderSkillsSection();
  431. expect(findButton("Refresh")).toBeTruthy();
  432. });
  433. it("顶部展示包含导入能力的更多操作菜单", async () => {
  434. mockCapabilityState = { userScopeAvailable: true };
  435. await renderSkillsSection();
  436. expect(findButton("More actions")).toBeTruthy();
  437. });
  438. it("connected SSH workspace shows remote skill sync entry", async () => {
  439. activeWorkspacePath = "/home/alice/project";
  440. activeWorkspaceIdentity = "ssh://alice@dev.example.com/home/alice/project";
  441. activeRemoteSessionId = "remote-session-1";
  442. activeRemoteTarget = {
  443. kind: "ssh",
  444. host: "dev.example.com",
  445. username: "alice",
  446. port: 22,
  447. };
  448. const html = await renderSkillsSection();
  449. expect(html).toContain("dev.example.com");
  450. expect(findButton("Sync Skill")).toBeTruthy();
  451. });
  452. it("connected WSL workspace shows remote skill sync entry", async () => {
  453. activeWorkspacePath = "/home/alice/project";
  454. activeWorkspaceIdentity = "remote:wsl:Ubuntu:/home/alice/project";
  455. activeRemoteSessionId = "remote-session-wsl";
  456. activeRemoteTarget = {
  457. kind: "wsl",
  458. distro: "Ubuntu",
  459. user: "alice",
  460. };
  461. const html = await renderSkillsSection();
  462. expect(html).toContain("WSL");
  463. expect(html).toContain("Ubuntu");
  464. expect(findButton("Sync Skill")).toBeTruthy();
  465. });
  466. it("技能详情弹窗会展示完整长描述和路径", async () => {
  467. const skill = {
  468. id: "skill-1",
  469. name: "feishu-drive",
  470. description:
  471. "飞书云空间文件管理 Skill。上传/下载/移动/搜索文件、创建文件夹、获取元数据等。当需要管理飞书云空间中的文件和文件夹时使用此 Skill。",
  472. body: "",
  473. path: "/Users/dev/.agents/skills/feishu-drive-1.0.0/SKILL.md",
  474. scope: "user",
  475. enabled: true,
  476. metadata: {
  477. slug: "feishu-drive",
  478. version: "1.0.0",
  479. ownerId: "owner-1",
  480. publishedAt: 1770965769673,
  481. },
  482. };
  483. mockCapabilityState = { userScopeAvailable: true };
  484. mockSkillsState = [skill];
  485. mockSelectedSkillState = skill;
  486. const html = await renderSkillsSection();
  487. expect(html).not.toContain(">Skill Details<");
  488. expect(html).not.toContain(">Source<");
  489. expect(html).toContain("feishu-drive");
  490. expect(html).toContain(
  491. "飞书云空间文件管理 Skill。上传/下载/移动/搜索文件、创建文件夹、获取元数据等。当需要管理飞书云空间中的文件和文件夹时使用此 Skill。",
  492. );
  493. expect(html).toContain(">Version<");
  494. expect(html).toContain(">1.0.0<");
  495. expect(html).toContain(">feishu-drive<");
  496. expect(html).toContain(">owner-1<");
  497. expect(html).toContain("2026-02-13T06:56:09.673Z");
  498. expect(html).toContain("/Users/dev/.agents/skills/feishu-drive-1.0.0/SKILL.md");
  499. expect(html).toContain(">Enabled<");
  500. expect(html).toContain('aria-label="Open"');
  501. expect(html).not.toContain("Copy to Common");
  502. expect(html).not.toContain("Remove from Common");
  503. });
  504. it("技能详情弹窗的文件路径可以打开", async () => {
  505. const skill = {
  506. id: "skill-1",
  507. name: "feishu-drive",
  508. description: "drive",
  509. body: "",
  510. path: "/Users/dev/.agents/skills/feishu-drive-1.0.0/SKILL.md",
  511. scope: "user",
  512. enabled: true,
  513. };
  514. mockCapabilityState = { userScopeAvailable: true };
  515. mockSkillsState = [skill];
  516. mockSelectedSkillState = skill;
  517. await renderSkillsSection();
  518. const openPathButton = findLinkButtonByLabel("Open");
  519. expect(openPathButton).toBeTruthy();
  520. (openPathButton?.onClick as () => void)?.();
  521. await new Promise((resolve) => setTimeout(resolve, 0));
  522. expect(openInFileManagerMock).toHaveBeenCalledWith(
  523. "/Users/dev/.agents/skills/feishu-drive-1.0.0/SKILL.md",
  524. );
  525. });
  526. it("新建技能通过 Root 标准链路创建带结构化 skill-creator mention 的草稿", async () => {
  527. mockSkillsState = [
  528. {
  529. id: "glm:skill-creator@official",
  530. name: "skill-creator",
  531. description: "Create skills",
  532. body: "",
  533. path: "/tmp/workspace/.zcode/skills/skill-creator/SKILL.md",
  534. scope: "workspace",
  535. enabled: true,
  536. },
  537. ];
  538. await renderSkillsSection();
  539. const createButton = findCreateSkillButton();
  540. expect(createButton).toBeTruthy();
  541. (createButton?.onClick as (event: { defaultPrevented: boolean }) => void)?.({
  542. defaultPrevented: false,
  543. });
  544. const markdown = "[$skill-creator](/tmp/workspace/.zcode/skills/skill-creator/SKILL.md)";
  545. expect(onCreateTaskMock).toHaveBeenCalledTimes(1);
  546. expect(onCreateTaskMock).toHaveBeenCalledWith({
  547. provider: "glm",
  548. initialPrompt: `${markdown} `,
  549. initialPromptMention: {
  550. id: "skill:glm:skill-creator@official",
  551. category: "skills",
  552. label: "skill-creator",
  553. value: "skill-creator",
  554. markdown,
  555. description: "Create skills",
  556. data: {
  557. path: "/tmp/workspace/.zcode/skills/skill-creator/SKILL.md",
  558. scope: "workspace",
  559. },
  560. },
  561. });
  562. expect(startDraftMock).not.toHaveBeenCalled();
  563. expect(activateTabByPathMock).not.toHaveBeenCalled();
  564. });
  565. it("有诊断时顶部 banner 按严重级别统计,展开后列出具体条目", async () => {
  566. mockCapabilityState = { userScopeAvailable: true };
  567. mockDiagnosticsState = [
  568. {
  569. code: "skill_missing_frontmatter",
  570. severity: "error",
  571. message: "缺少 frontmatter",
  572. path: "/tmp/workspace/.zcode/skills/bad/SKILL.md",
  573. },
  574. {
  575. code: "skill_unknown_frontmatter",
  576. severity: "warning",
  577. message: "未识别字段: foo",
  578. path: "/tmp/workspace/.zcode/skills/other/SKILL.md",
  579. skillName: "other",
  580. },
  581. ];
  582. mockDiagnosticsOpenState = true;
  583. const html = await renderSkillsSection();
  584. expect(html).toContain("Skill diagnostics: 1 error(s), 1 warning(s)");
  585. expect(html).not.toContain("skill(s) failed to load");
  586. expect(html).toContain("Missing YAML frontmatter");
  587. expect(html).toContain("Unknown frontmatter key");
  588. expect(html).toContain("缺少 frontmatter");
  589. expect(html).toContain("/tmp/workspace/.zcode/skills/bad/SKILL.md");
  590. });
  591. it("Plugin 只展示当前 scope 且名称后不重复 scope 标签", async () => {
  592. mockCapabilityState = { userScopeAvailable: true };
  593. mockSkillsState = [
  594. {
  595. id: "skill-1",
  596. name: "repo-review",
  597. description: "review repo",
  598. body: "",
  599. path: "/tmp/workspace/.zcode/skills/repo-review/SKILL.md",
  600. scope: "workspace",
  601. enabled: true,
  602. },
  603. {
  604. id: "skill-2",
  605. name: "global-skill",
  606. description: "user skill",
  607. body: "",
  608. path: "/Users/dev/.zcode/skills/global-skill/SKILL.md",
  609. scope: "user",
  610. enabled: true,
  611. },
  612. ];
  613. const html = await renderSkillsSection();
  614. expect(html).toContain("repo-review");
  615. expect(html).not.toContain("global-skill");
  616. expect(html).not.toContain("data-skill-scope");
  617. });
  618. it("设置页切换技能开关后会刷新同一远程工作区的聊天补全技能缓存", async () => {
  619. const skill = {
  620. id: "skill-1",
  621. name: "lark-approval",
  622. description: "approval",
  623. body: "",
  624. path: "/root/.zcode/skills/lark-approval/SKILL.md",
  625. scope: "user" as const,
  626. enabled: true,
  627. };
  628. mockCapabilityState = { userScopeAvailable: true };
  629. mockSkillsState = [skill];
  630. activeScopeFilter = "user";
  631. mockSkillsServiceList.mockResolvedValue({
  632. skills: [{ ...skill, enabled: false }],
  633. capability: { userScopeAvailable: true },
  634. diagnostics: [],
  635. });
  636. const { useSkillStore } = await import("../src/store/skillStore.js");
  637. useSkillStore.setState({
  638. workspacePath: "/tmp/workspace",
  639. workspaceIdentity: "remote:ssh:dev:/tmp/workspace",
  640. loadedWorkspacePath: "/tmp/workspace",
  641. loadedWorkspaceIdentity: "remote:ssh:dev:/tmp/workspace",
  642. provider: "glm",
  643. loadedProvider: "glm",
  644. skills: [skill],
  645. capability: { userScopeAvailable: true },
  646. loading: false,
  647. error: null,
  648. });
  649. await renderSkillsSection();
  650. (capturedSwitches[0]?.onCheckedChange as (checked: boolean) => void)?.(false);
  651. await vi.waitFor(() => {
  652. expect(mockSkillsServiceSetEnabled).toHaveBeenCalledWith({
  653. workspacePath: "/tmp/workspace",
  654. workspaceIdentity: "remote:ssh:dev:/tmp/workspace",
  655. provider: "glm",
  656. scope: "user",
  657. skillId: "skill-1",
  658. enabled: false,
  659. });
  660. // 修复原因:protocol-v4 草稿没有 legacy draftSessionId,切换技能仍必须失效预热运行态。
  661. expect(invalidateDraftRuntimeMock).toHaveBeenCalledWith(
  662. "/tmp/workspace",
  663. "remote:ssh:dev:/tmp/workspace",
  664. );
  665. expect(useSkillStore.getState().skills[0]?.enabled).toBe(false);
  666. });
  667. });
  668. it("远程设置页切换技能开关不会刷新其他本地工作区的聊天补全缓存", async () => {
  669. const remoteSkill = {
  670. id: "skill-1",
  671. name: "lark-approval",
  672. description: "approval",
  673. body: "",
  674. path: "/root/.zcode/skills/lark-approval/SKILL.md",
  675. scope: "user" as const,
  676. enabled: true,
  677. };
  678. const localSkill = {
  679. id: "local-skill-1",
  680. name: "local-helper",
  681. description: "local",
  682. body: "",
  683. path: "/Users/alice/.zcode/skills/local-helper/SKILL.md",
  684. scope: "user" as const,
  685. enabled: true,
  686. };
  687. mockCapabilityState = { userScopeAvailable: true };
  688. mockSkillsState = [remoteSkill];
  689. activeScopeFilter = "user";
  690. mockSkillsServiceList.mockResolvedValue({
  691. skills: [{ ...remoteSkill, enabled: false }],
  692. capability: { userScopeAvailable: true },
  693. diagnostics: [],
  694. });
  695. const { useSkillStore } = await import("../src/store/skillStore.js");
  696. useSkillStore.setState({
  697. workspacePath: "/Users/alice/local-project",
  698. workspaceIdentity: null,
  699. loadedWorkspacePath: "/Users/alice/local-project",
  700. loadedWorkspaceIdentity: null,
  701. provider: "glm",
  702. loadedProvider: "glm",
  703. skills: [localSkill],
  704. capability: { userScopeAvailable: true },
  705. loading: false,
  706. error: null,
  707. });
  708. await renderSkillsSection();
  709. (capturedSwitches[0]?.onCheckedChange as (checked: boolean) => void)?.(false);
  710. await vi.waitFor(() => {
  711. expect(mockSkillsServiceSetEnabled).toHaveBeenCalled();
  712. });
  713. expect(useSkillStore.getState().workspacePath).toBe("/Users/alice/local-project");
  714. expect(useSkillStore.getState().skills).toEqual([localSkill]);
  715. });
  716. });