skillStore.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { create } from "zustand";
  2. import {
  3. normalizeAgentProviderToZCodeAgent,
  4. ZCODE_AGENT_PROVIDER,
  5. type ZCodeProvider,
  6. type SkillSummary,
  7. type SkillsCapability,
  8. } from "@zcode/shared";
  9. import type { ISkillsService } from "@zcode/services";
  10. import { shouldExposeE2EStoreBridge } from "@/lib/e2eStoreBridge.js";
  11. import { logger } from "@/logger.js";
  12. interface SkillStoreState {
  13. workspacePath: string | null;
  14. workspaceIdentity: string | null;
  15. loadedWorkspacePath: string | null;
  16. loadedWorkspaceIdentity: string | null;
  17. provider: ZCodeProvider;
  18. loadedProvider: ZCodeProvider | null;
  19. skills: SkillSummary[];
  20. capability: SkillsCapability | null;
  21. loading: boolean;
  22. error: string | null;
  23. initialize: (
  24. workspacePath: string,
  25. providerOrSkillsService: ZCodeProvider | ISkillsService,
  26. maybeSkillsService?: ISkillsService,
  27. workspaceIdentity?: string,
  28. ) => Promise<void>;
  29. refresh: (skillsService: ISkillsService, workspaceIdentity?: string) => Promise<void>;
  30. setEnabled: (
  31. skillId: string,
  32. providerOrEnabled: ZCodeProvider | boolean,
  33. scopeOrSkillsService: SkillSummary["scope"] | ISkillsService,
  34. enabledOrSkillsService?: boolean | ISkillsService,
  35. maybeSkillsService?: ISkillsService,
  36. workspaceIdentity?: string,
  37. ) => Promise<void>;
  38. }
  39. const inFlightSkillLoads = new Map<string, ReturnType<ISkillsService["list"]>>();
  40. function getSkillLoadKey(
  41. workspacePath: string,
  42. provider: ZCodeProvider,
  43. workspaceIdentity?: string,
  44. ): string {
  45. return `${workspaceIdentity?.trim() || workspacePath}::${provider}`;
  46. }
  47. function loadSkillsOnce(
  48. workspacePath: string,
  49. provider: ZCodeProvider,
  50. skillsService: ISkillsService,
  51. workspaceIdentity?: string,
  52. options: { bypassCache?: boolean } = {},
  53. ): ReturnType<ISkillsService["list"]> {
  54. const key = getSkillLoadKey(workspacePath, provider, workspaceIdentity);
  55. if (!options.bypassCache) {
  56. const current = inFlightSkillLoads.get(key);
  57. if (current) {
  58. return current;
  59. }
  60. }
  61. // 复制/移除技能到通用目录后 refresh 必须拿到最新结果。
  62. // 若复用 in-flight Promise 会返回旧扫描结果,导致 chat mention 看不到新加的技能。
  63. const request = skillsService.list({ workspacePath, workspaceIdentity, provider }).finally(() => {
  64. // 仅在自己是当前活跃 in-flight 时清理,避免覆盖其他并发请求。
  65. if (inFlightSkillLoads.get(key) === request) {
  66. inFlightSkillLoads.delete(key);
  67. }
  68. });
  69. inFlightSkillLoads.set(key, request);
  70. return request;
  71. }
  72. export const useSkillStore = create<SkillStoreState>((set, get) => ({
  73. workspacePath: null,
  74. workspaceIdentity: null,
  75. loadedWorkspacePath: null,
  76. loadedWorkspaceIdentity: null,
  77. provider: ZCODE_AGENT_PROVIDER,
  78. loadedProvider: null,
  79. skills: [],
  80. capability: null,
  81. loading: false,
  82. error: null,
  83. async initialize(
  84. workspacePath: string,
  85. providerOrSkillsService: ZCodeProvider | ISkillsService,
  86. maybeSkillsService?: ISkillsService,
  87. workspaceIdentity?: string,
  88. ) {
  89. const currentState = get();
  90. const hasProvider = typeof providerOrSkillsService === "string";
  91. const provider = normalizeAgentProviderToZCodeAgent(
  92. hasProvider ? providerOrSkillsService : ZCODE_AGENT_PROVIDER,
  93. );
  94. const skillsService = hasProvider ? maybeSkillsService : providerOrSkillsService;
  95. const normalizedWorkspaceIdentity = workspaceIdentity?.trim() || null;
  96. if (!skillsService) {
  97. set({
  98. workspacePath,
  99. workspaceIdentity: normalizedWorkspaceIdentity,
  100. provider,
  101. loading: false,
  102. error: "skillsService is required",
  103. loadedWorkspacePath: workspacePath,
  104. loadedWorkspaceIdentity: normalizedWorkspaceIdentity,
  105. loadedProvider: provider,
  106. });
  107. return;
  108. }
  109. const hasCachedSkills =
  110. currentState.skills.length > 0 &&
  111. currentState.loadedWorkspacePath === workspacePath &&
  112. currentState.loadedWorkspaceIdentity === normalizedWorkspaceIdentity &&
  113. currentState.loadedProvider === provider;
  114. // 切换 agent 筛选时会触发 initialize。
  115. // 之前总是 loading=true,会先清空成“加载中”再渲染结果,导致列表闪烁。
  116. // 这里改成“只有同一 workspace+provider 的缓存才允许复用”,避免上一套技能误显示到当前会话里。
  117. set({
  118. workspacePath,
  119. workspaceIdentity: normalizedWorkspaceIdentity,
  120. provider,
  121. skills: hasCachedSkills ? currentState.skills : [],
  122. capability: hasCachedSkills ? currentState.capability : null,
  123. loading: !hasCachedSkills,
  124. error: null,
  125. });
  126. try {
  127. // 聊天输入区会同时挂载多个技能消费者(例如 $ mention 与 / 面板)。
  128. // 之前它们首屏会并发触发相同的 list 请求,进而把服务层镜像同步竞争放大成用户可见报错。
  129. // 这里先按 workspace+provider 去重,同一轮只复用一个请求结果。
  130. const result = await loadSkillsOnce(
  131. workspacePath,
  132. provider,
  133. skillsService,
  134. normalizedWorkspaceIdentity ?? undefined,
  135. );
  136. set({
  137. skills: result.skills,
  138. capability: result.capability,
  139. loading: false,
  140. loadedWorkspacePath: workspacePath,
  141. loadedWorkspaceIdentity: normalizedWorkspaceIdentity,
  142. loadedProvider: provider,
  143. });
  144. } catch (error) {
  145. logger.error("[skills] initialize failed", {
  146. workspacePath,
  147. provider,
  148. error: error instanceof Error ? error.message : String(error),
  149. });
  150. set({
  151. loading: false,
  152. error: error instanceof Error ? error.message : String(error),
  153. loadedWorkspacePath: workspacePath,
  154. loadedWorkspaceIdentity: normalizedWorkspaceIdentity,
  155. loadedProvider: provider,
  156. });
  157. }
  158. },
  159. async refresh(skillsService: ISkillsService, workspaceIdentity?: string) {
  160. const workspacePath = get().workspacePath;
  161. if (!workspacePath) {
  162. return;
  163. }
  164. const workspaceIdentityFromState =
  165. workspaceIdentity?.trim() || get().workspaceIdentity || undefined;
  166. const provider = normalizeAgentProviderToZCodeAgent(get().provider);
  167. const hasCachedSkills = get().skills.length > 0;
  168. // 开关技能后会触发 refresh,之前每次都把 loading 置 true,
  169. // Settings 列表会先切到“加载中”再切回数据,用户看到整列表闪烁。
  170. // 这里改成“仅首次无缓存时显示阻塞 loading”,有缓存时后台刷新并保留当前列表。
  171. set({ loading: !hasCachedSkills, error: null });
  172. // refresh 必须保证拿到「最新一次」的服务端结果。
  173. // 直接调 loadSkillsOnce 会复用 in-flight 的旧请求,
  174. // 导致复制 skill 到通用目录后 chat mention 仍看到旧列表。
  175. // 这里在 refresh 时显式跳过 in-flight 缓存,强制发起一次新请求。
  176. inFlightSkillLoads.delete(getSkillLoadKey(workspacePath, provider, workspaceIdentityFromState));
  177. try {
  178. const result = await loadSkillsOnce(
  179. workspacePath,
  180. provider,
  181. skillsService,
  182. workspaceIdentityFromState,
  183. );
  184. set({
  185. skills: result.skills,
  186. capability: result.capability,
  187. loading: false,
  188. loadedWorkspacePath: workspacePath,
  189. loadedWorkspaceIdentity: workspaceIdentityFromState ?? null,
  190. loadedProvider: provider,
  191. });
  192. } catch (error) {
  193. logger.error("[skills] refresh failed", {
  194. workspacePath,
  195. provider,
  196. error: error instanceof Error ? error.message : String(error),
  197. });
  198. set({
  199. loading: false,
  200. error: error instanceof Error ? error.message : String(error),
  201. loadedWorkspacePath: workspacePath,
  202. loadedWorkspaceIdentity: workspaceIdentityFromState ?? null,
  203. loadedProvider: provider,
  204. });
  205. }
  206. },
  207. async setEnabled(
  208. skillId: string,
  209. providerOrEnabled: ZCodeProvider | boolean,
  210. scopeOrSkillsService: SkillSummary["scope"] | ISkillsService,
  211. enabledOrSkillsService?: boolean | ISkillsService,
  212. maybeSkillsService?: ISkillsService,
  213. workspaceIdentity?: string,
  214. ) {
  215. const workspacePath = get().workspacePath;
  216. if (!workspacePath) {
  217. return;
  218. }
  219. const workspaceIdentityFromState =
  220. workspaceIdentity?.trim() || get().workspaceIdentity || undefined;
  221. const legacyCall = typeof providerOrEnabled === "boolean";
  222. const provider = normalizeAgentProviderToZCodeAgent(
  223. legacyCall ? get().provider : providerOrEnabled,
  224. );
  225. const scope = legacyCall ? undefined : (scopeOrSkillsService as SkillSummary["scope"]);
  226. const enabled = legacyCall ? providerOrEnabled : (enabledOrSkillsService as boolean);
  227. const skillsService = legacyCall
  228. ? (scopeOrSkillsService as ISkillsService)
  229. : maybeSkillsService;
  230. if (!skillsService) {
  231. set({ error: "skillsService is required" });
  232. return;
  233. }
  234. try {
  235. await skillsService.setEnabled({
  236. workspacePath,
  237. workspaceIdentity: workspaceIdentityFromState,
  238. provider,
  239. ...(scope ? { scope } : {}),
  240. skillId,
  241. enabled,
  242. });
  243. await get().refresh(skillsService, workspaceIdentityFromState);
  244. } catch (error) {
  245. set({
  246. error: error instanceof Error ? error.message : String(error),
  247. });
  248. }
  249. },
  250. }));
  251. type SkillStoreE2EBridge = typeof useSkillStore;
  252. declare global {
  253. interface Window {
  254. __skillStoreE2E?: SkillStoreE2EBridge;
  255. }
  256. }
  257. if (shouldExposeE2EStoreBridge()) {
  258. // E2E 诊断入口必须由 WDIO 显式打开,不能复用 ZCODE_ENV=test,避免产品测试环境暴露可变全局 store。
  259. window.__skillStoreE2E = useSkillStore;
  260. }