SlashCommandPlugin.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /* eslint-disable max-lines -- Lexical slash 插件的 trigger/面板/键盘导航同属一个协议状态机,oxfmt 换行后略超 400 行。 */
  2. /**
  3. * SlashCommandPlugin — Lexical trigger 面板插件
  4. *
  5. * 处理 `/` 面板里的 slash commands 和 subagents:
  6. * 1. `/` 直接展示 ZCode Agent 广播的真实 slash commands,并补充可用 subagents
  7. * 2. 面板通过 portal 渲染到输入区上方的独立挂载层,展开时直接覆盖消息区
  8. * 3. 支持 Esc 关闭、上下键切换、Enter / Tab 选中,以及跟随输入做模糊搜索
  9. */
  10. import { useCallback, useEffect, useMemo, useRef, useState } from "react";
  11. import type { ZCodeProvider } from "@zcode/shared";
  12. import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
  13. import { createPortal } from "react-dom";
  14. import {
  15. $createTextNode,
  16. BLUR_COMMAND,
  17. COMMAND_PRIORITY_CRITICAL,
  18. COMMAND_PRIORITY_LOW,
  19. KEY_ARROW_DOWN_COMMAND,
  20. KEY_ARROW_UP_COMMAND,
  21. KEY_ENTER_COMMAND,
  22. KEY_ESCAPE_COMMAND,
  23. KEY_TAB_COMMAND,
  24. } from "lexical";
  25. import { useSubagents } from "@/hooks/useSubagents.js";
  26. import { useSkills } from "@/hooks/useSkills.js";
  27. import { buildSlashApplyMentionPayload } from "@/lib/slashApplyMentionPayload.js";
  28. import { filterSkillsForProvider } from "@/lib/skillSourceFilter.js";
  29. import { useZCodeIntl } from "./i18n/IntlProvider.js";
  30. import { useSlashCommands } from "./hooks/useSlashCommands.js";
  31. import { $createPromptMentionNode } from "./mentions/nodes/PromptMentionNode.js";
  32. import {
  33. extractActivePromptInputTrigger,
  34. filterPromptInputSuggestions,
  35. getActivePromptInputTokenTailLength,
  36. getBestPromptInputSuggestionIndex,
  37. getPromptInputTriggerSignature,
  38. type ActivePromptInputTrigger,
  39. type PromptInputSuggestionItem,
  40. } from "./lib/promptInputTriggers.js";
  41. import { MentionPanel } from "./mentions/components/MentionPanel.js";
  42. import {
  43. buildAppSlashCommandSuggestions,
  44. buildSkillSuggestions,
  45. buildSubagentSuggestions,
  46. buildSlashSuggestions,
  47. getTextAroundCursor,
  48. isAppSlashCommandSuggestion,
  49. normalizeSlashCommandValue,
  50. type SlashCommandPluginProps,
  51. } from "./slashCommandHelpers.js";
  52. import { useSlashCommandMentionPanelSections } from "./slashCommandPanelSections.js";
  53. import { getCurrentTextNodeSelection } from "./mentions/mentionHelpers.js";
  54. import {
  55. getActivePromptInputTokenReplacementRange,
  56. reconcileActivePromptInputTokenSnapshot,
  57. type ActivePromptInputTokenSnapshot,
  58. } from "./mentions/activePromptInputToken.js";
  59. import { shouldSlashPanelProcessUpdate } from "./lib/slashPanelUpdateFilter.js";
  60. export function SlashCommandPlugin({
  61. workspacePath,
  62. workspaceIdentity,
  63. sessionId,
  64. provider,
  65. container,
  66. disabled = false,
  67. excludedCommandNames,
  68. appCommands,
  69. }: SlashCommandPluginProps & { provider: ZCodeProvider }) {
  70. const [editor] = useLexicalComposerContext();
  71. const { intl, locale } = useZCodeIntl();
  72. const [activeTrigger, setActiveTrigger] = useState<ActivePromptInputTrigger | null>(null);
  73. // 远程 workspace 的 slashCommands 写在 workspaceIdentity 桶。
  74. // 这里只按 workspacePath 读取会落到 path 桶,表现为 ZCode Agent 已收到 available_commands_update 但 / 面板为空。
  75. const commands = useSlashCommands(workspacePath, workspaceIdentity);
  76. const {
  77. agents,
  78. loading: subagentsLoading,
  79. error: subagentsError,
  80. } = useSubagents(workspacePath, provider, workspaceIdentity);
  81. const {
  82. skills,
  83. loading: skillsLoading,
  84. error: skillsError,
  85. } = useSkills({
  86. workspacePath,
  87. workspaceIdentity,
  88. sessionId: sessionId ?? null,
  89. enabled: !disabled && activeTrigger?.trigger === "/",
  90. });
  91. const [selectedIndex, setSelectedIndex] = useState(0);
  92. const dismissedSignatureRef = useRef<string | null>(null);
  93. const activeSignatureRef = useRef<string | null>(null);
  94. const activeTokenRef = useRef<ActivePromptInputTokenSnapshot | null>(null);
  95. const commandSuggestions = useMemo(() => {
  96. const excluded = new Set((excludedCommandNames ?? []).map(normalizeSlashCommandValue));
  97. const cliSuggestions = buildSlashSuggestions(commands).filter(
  98. (item) => !excluded.has(item.value),
  99. );
  100. // App 层命令追加在 CLI catalog 之后展示;CLI 已提供同名命令时以 CLI 为准,避免遮蔽。
  101. const cliValues = new Set(cliSuggestions.map((item) => item.value));
  102. const appSuggestions = buildAppSlashCommandSuggestions(appCommands ?? []).filter(
  103. (item) => !cliValues.has(item.value) && !excluded.has(item.value),
  104. );
  105. return [...cliSuggestions, ...appSuggestions];
  106. }, [appCommands, commands, excludedCommandNames]);
  107. const subagentSuggestions = useMemo(() => buildSubagentSuggestions(agents), [agents]);
  108. const skillSuggestions = useMemo(
  109. () =>
  110. buildSkillSuggestions(
  111. filterSkillsForProvider(skills, provider).filter((skill) => skill.enabled),
  112. locale,
  113. ),
  114. [locale, provider, skills],
  115. );
  116. const filteredCommandSuggestions = useMemo(
  117. () => filterPromptInputSuggestions(commandSuggestions, activeTrigger?.query ?? null),
  118. [commandSuggestions, activeTrigger?.query],
  119. );
  120. const filteredSubagentSuggestions = useMemo(
  121. () => filterPromptInputSuggestions(subagentSuggestions, activeTrigger?.query ?? null),
  122. [subagentSuggestions, activeTrigger?.query],
  123. );
  124. const filteredSkillSuggestions = useMemo(
  125. () => filterPromptInputSuggestions(skillSuggestions, activeTrigger?.query ?? null),
  126. [skillSuggestions, activeTrigger?.query],
  127. );
  128. const filteredSuggestions = useMemo(
  129. () => [
  130. ...filteredCommandSuggestions,
  131. ...filteredSkillSuggestions,
  132. ...filteredSubagentSuggestions,
  133. ],
  134. [filteredCommandSuggestions, filteredSkillSuggestions, filteredSubagentSuggestions],
  135. );
  136. const activeSignature = useMemo(
  137. () => getPromptInputTriggerSignature(activeTrigger),
  138. [activeTrigger],
  139. );
  140. const isOpen = !disabled && activeTrigger !== null;
  141. useEffect(() => {
  142. activeSignatureRef.current = activeSignature;
  143. }, [activeSignature]);
  144. useEffect(() => {
  145. // 面板展示需要保留 commands/subagents 分组顺序,但键盘默认选中不能固定落在第一个分组。
  146. // 例如 `/rev` 时 command 描述里的弱匹配可能排在 subagent 分组前面,导致无法默认选中最佳 subagent。
  147. // 这里按统一的模糊评分选择全局最佳项,同时不改变面板的分组展示顺序。
  148. setSelectedIndex(
  149. getBestPromptInputSuggestionIndex(filteredSuggestions, activeTrigger?.query ?? null),
  150. );
  151. }, [activeSignature, activeTrigger?.query, filteredSuggestions]);
  152. useEffect(() => {
  153. setSelectedIndex((current) => {
  154. if (filteredSuggestions.length === 0) {
  155. return 0;
  156. }
  157. return Math.min(current, filteredSuggestions.length - 1);
  158. });
  159. }, [filteredSuggestions.length]);
  160. useEffect(() => {
  161. if (!disabled) {
  162. return;
  163. }
  164. setActiveTrigger(null);
  165. setSelectedIndex(0);
  166. activeTokenRef.current = null;
  167. }, [disabled]);
  168. useEffect(() => {
  169. return editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, editorState, tags }) => {
  170. editorState.read(() => {
  171. // 历史导航回填含 / 的历史条目时,不应重新打开 slash 面板,
  172. // 否则面板以 COMMAND_PRIORITY_CRITICAL 注册方向键处理器,吞掉后续历史翻阅按键。
  173. if (!shouldSlashPanelProcessUpdate(tags)) {
  174. activeTokenRef.current = null;
  175. setActiveTrigger(null);
  176. return;
  177. }
  178. if (disabled) {
  179. activeTokenRef.current = null;
  180. setActiveTrigger(null);
  181. return;
  182. }
  183. const selectionState = getCurrentTextNodeSelection();
  184. const cursorText = selectionState ?? getTextAroundCursor();
  185. if (!cursorText) {
  186. activeTokenRef.current = null;
  187. dismissedSignatureRef.current = null;
  188. setActiveTrigger(null);
  189. return;
  190. }
  191. const nextActiveToken = selectionState
  192. ? reconcileActivePromptInputTokenSnapshot(
  193. activeTokenRef.current,
  194. selectionState,
  195. dirtyElements.size === 0 && dirtyLeaves.size === 0,
  196. )
  197. : null;
  198. const nextActiveTrigger = selectionState
  199. ? nextActiveToken
  200. : extractActivePromptInputTrigger(cursorText.textBeforeCursor);
  201. if (!nextActiveTrigger || nextActiveTrigger.trigger !== "/") {
  202. activeTokenRef.current = null;
  203. dismissedSignatureRef.current = null;
  204. setActiveTrigger(null);
  205. return;
  206. }
  207. activeTokenRef.current = nextActiveToken;
  208. const nextSignature = getPromptInputTriggerSignature(nextActiveTrigger);
  209. if (
  210. dismissedSignatureRef.current !== null &&
  211. dismissedSignatureRef.current !== nextSignature
  212. ) {
  213. dismissedSignatureRef.current = null;
  214. }
  215. if (dismissedSignatureRef.current === nextSignature) {
  216. setActiveTrigger(null);
  217. return;
  218. }
  219. setActiveTrigger((current) => {
  220. if (
  221. current?.trigger === nextActiveTrigger.trigger &&
  222. current.query === nextActiveTrigger.query
  223. ) {
  224. return current;
  225. }
  226. return nextActiveTrigger;
  227. });
  228. });
  229. });
  230. }, [disabled, editor]);
  231. const applySuggestion = useCallback(
  232. (suggestion: PromptInputSuggestionItem) => {
  233. const isAppCommand = isAppSlashCommandSuggestion(suggestion);
  234. editor.update(() => {
  235. const selectionState = getCurrentTextNodeSelection();
  236. if (!selectionState) {
  237. return;
  238. }
  239. const snapshotRange = getActivePromptInputTokenReplacementRange(
  240. activeTokenRef.current,
  241. selectionState,
  242. );
  243. const activeSlashTrigger = snapshotRange
  244. ? activeTokenRef.current
  245. : extractActivePromptInputTrigger(selectionState.textBeforeCursor);
  246. if (!activeSlashTrigger || activeSlashTrigger.trigger !== "/") {
  247. return;
  248. }
  249. const tokenStart =
  250. snapshotRange?.start ?? selectionState.cursorOffset - activeSlashTrigger.query.length - 1;
  251. const tokenEnd =
  252. snapshotRange?.end ??
  253. selectionState.cursorOffset +
  254. getActivePromptInputTokenTailLength(
  255. activeSlashTrigger,
  256. selectionState.textAfterCursor,
  257. suggestion.value,
  258. );
  259. selectionState.selection.setTextNodeRange(
  260. selectionState.node,
  261. tokenStart,
  262. selectionState.node,
  263. tokenEnd,
  264. );
  265. if (isAppCommand) {
  266. // App 层命令"选中即执行":只移除输入中的 `/xxx` token,不插入 mention、不发送。
  267. selectionState.selection.removeText();
  268. return;
  269. }
  270. const mentionNode = $createPromptMentionNode(buildSlashApplyMentionPayload(suggestion));
  271. const trailingWhitespace = $createTextNode(" ");
  272. selectionState.selection.insertNodes([mentionNode, trailingWhitespace]);
  273. trailingWhitespace.selectEnd();
  274. });
  275. dismissedSignatureRef.current = null;
  276. activeTokenRef.current = null;
  277. setActiveTrigger(null);
  278. setSelectedIndex(0);
  279. if (isAppCommand) {
  280. appCommands
  281. ?.find((command) => normalizeSlashCommandValue(command.value) === suggestion.value)
  282. ?.run();
  283. return;
  284. }
  285. requestAnimationFrame(() => {
  286. editor.focus();
  287. });
  288. },
  289. [appCommands, editor],
  290. );
  291. const selectSuggestion = useCallback(
  292. (index: number) => {
  293. const suggestion = filteredSuggestions[index];
  294. if (!suggestion) {
  295. return false;
  296. }
  297. applySuggestion(suggestion);
  298. return true;
  299. },
  300. [applySuggestion, filteredSuggestions],
  301. );
  302. useEffect(() => {
  303. if (!isOpen) {
  304. return;
  305. }
  306. const unregisterDown = editor.registerCommand(
  307. KEY_ARROW_DOWN_COMMAND,
  308. (event) => {
  309. if (filteredSuggestions.length === 0) {
  310. return false;
  311. }
  312. event?.preventDefault();
  313. event?.stopPropagation();
  314. setSelectedIndex((prev) => Math.min(prev + 1, filteredSuggestions.length - 1));
  315. return true;
  316. },
  317. COMMAND_PRIORITY_CRITICAL,
  318. );
  319. const unregisterUp = editor.registerCommand(
  320. KEY_ARROW_UP_COMMAND,
  321. (event) => {
  322. if (filteredSuggestions.length === 0) {
  323. return false;
  324. }
  325. event?.preventDefault();
  326. event?.stopPropagation();
  327. setSelectedIndex((prev) => Math.max(prev - 1, 0));
  328. return true;
  329. },
  330. COMMAND_PRIORITY_CRITICAL,
  331. );
  332. const unregisterEnter = editor.registerCommand(
  333. KEY_ENTER_COMMAND,
  334. (event) => {
  335. if (!selectSuggestion(selectedIndex)) {
  336. return false;
  337. }
  338. event?.preventDefault();
  339. event?.stopPropagation();
  340. return true;
  341. },
  342. COMMAND_PRIORITY_CRITICAL,
  343. );
  344. const unregisterTab = editor.registerCommand(
  345. KEY_TAB_COMMAND,
  346. (event) => {
  347. if (!selectSuggestion(selectedIndex)) {
  348. return false;
  349. }
  350. event?.preventDefault();
  351. event?.stopPropagation();
  352. return true;
  353. },
  354. COMMAND_PRIORITY_CRITICAL,
  355. );
  356. const unregisterEscape = editor.registerCommand(
  357. KEY_ESCAPE_COMMAND,
  358. (event) => {
  359. event?.preventDefault();
  360. event?.stopPropagation();
  361. // 如果 Esc 关闭后只记 query,不区分 `/` 和 `@`,两个触发器同名查询会互相把面板压住。
  362. // 这里保存 trigger + query 组合签名,只有当前 token 真正变化后才重新打开,避免一关闭就立刻弹回。
  363. dismissedSignatureRef.current = activeSignatureRef.current;
  364. setActiveTrigger(null);
  365. setSelectedIndex(0);
  366. return true;
  367. },
  368. COMMAND_PRIORITY_CRITICAL,
  369. );
  370. const unregisterBlur = editor.registerCommand(
  371. BLUR_COMMAND,
  372. () => {
  373. dismissedSignatureRef.current = null;
  374. activeTokenRef.current = null;
  375. setActiveTrigger(null);
  376. setSelectedIndex(0);
  377. return false;
  378. },
  379. COMMAND_PRIORITY_LOW,
  380. );
  381. return () => {
  382. unregisterDown();
  383. unregisterUp();
  384. unregisterEnter();
  385. unregisterTab();
  386. unregisterEscape();
  387. unregisterBlur();
  388. };
  389. }, [editor, filteredSuggestions.length, isOpen, selectSuggestion, selectedIndex]);
  390. const panelTitle = intl.formatMessage({ id: "chat.slash.title" });
  391. const hasActiveQuery = (activeTrigger?.query ?? "").trim().length > 0;
  392. const panelDescription = hasActiveQuery
  393. ? ""
  394. : intl.formatMessage({ id: "chat.slash.searchHint" });
  395. const panelSections = useSlashCommandMentionPanelSections(
  396. intl,
  397. commands.length,
  398. filteredCommandSuggestions,
  399. filteredSkillSuggestions,
  400. skillsLoading,
  401. skillsError,
  402. filteredSubagentSuggestions,
  403. subagentsLoading,
  404. subagentsError,
  405. );
  406. if (!isOpen || !container) {
  407. return null;
  408. }
  409. return createPortal(
  410. <MentionPanel
  411. title={panelTitle}
  412. description={panelDescription}
  413. trigger="/"
  414. sections={panelSections}
  415. emptyText=""
  416. selectedIndex={selectedIndex}
  417. hasActiveQuery={hasActiveQuery}
  418. onSelect={selectSuggestion}
  419. />,
  420. container,
  421. );
  422. }