chatPromptActionMenuInteraction.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // @vitest-environment jsdom
  2. import { createElement, type ComponentProps, type ReactNode } from "react";
  3. import { cleanup, fireEvent, render, screen } from "@testing-library/react";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import type { LexicalChatInputHandle } from "@/LexicalChatInput.js";
  6. import type { MentionItem } from "@/mentions/mentionTypes.js";
  7. import type { MentionPanel } from "@/mentions/components/MentionPanel.js";
  8. import { ChatPromptActionMenu } from "@/prompt-editor/ChatPromptActionMenu.js";
  9. const mocks = vi.hoisted(() => ({
  10. plugins: vi.fn(),
  11. files: vi.fn(),
  12. sessions: vi.fn(),
  13. slashCommands: vi.fn(),
  14. }));
  15. vi.mock("@/hooks/useSlashCommands.js", () => ({ useSlashCommands: mocks.slashCommands }));
  16. vi.mock("@/mentions/providers/pluginsMentionProvider.js", () => ({
  17. usePluginsMentionProvider: mocks.plugins,
  18. }));
  19. vi.mock("@/mentions/providers/fileMentionProvider.js", () => ({
  20. useFileMentionProvider: mocks.files,
  21. }));
  22. vi.mock("@/mentions/providers/sessionsMentionProvider.js", () => ({
  23. useSessionsMentionProvider: mocks.sessions,
  24. }));
  25. vi.mock("@/v4/activeTaskProvider.js", () => ({ useChatViewActiveTaskProvider: () => "zcode" }));
  26. vi.mock("@/i18n/IntlProvider.js", () => ({
  27. useZCodeIntl: () => ({ intl: { formatMessage: ({ id }: { id: string }) => id } }),
  28. }));
  29. vi.mock("@/ControlHintTooltip.js", () => ({
  30. ControlHintTooltip: ({ children }: { children: ReactNode }) => children,
  31. }));
  32. // 虚拟列表的尺寸与真实焦点由 Electron E2E 验证;这里保留菜单接线和所有候选。
  33. vi.mock("@/mentions/components/MentionPanel.js", () => ({
  34. MentionPanel: ({ sections, onSelect, footer }: ComponentProps<typeof MentionPanel>) => {
  35. let index = 0;
  36. return createElement(
  37. "div",
  38. {},
  39. ...sections.map((section) =>
  40. createElement(
  41. "section",
  42. { key: section.id, "data-section": section.id },
  43. ...section.options.map((option) => {
  44. const optionIndex = index++;
  45. return createElement(
  46. "button",
  47. { key: option.id, onClick: () => onSelect(optionIndex) },
  48. option.id,
  49. );
  50. }),
  51. ),
  52. ),
  53. footer,
  54. );
  55. },
  56. }));
  57. function item(category: MentionItem["category"], id: string, disabled = false): MentionItem {
  58. return {
  59. id,
  60. category,
  61. label: id,
  62. description: "",
  63. value: id,
  64. markdown: `[@${id}](plugin://${id})`,
  65. disabled,
  66. };
  67. }
  68. function setup(
  69. attachment = true,
  70. sessionId: string | null = "session-1",
  71. text = "",
  72. excludedSlashCommandNames: readonly string[] = [],
  73. workflowInCatalog = false,
  74. ) {
  75. // 命令目录以 CLI catalog 为权威:仅当 catalog 含 workflow 时 + 菜单才提供工作流。
  76. mocks.slashCommands.mockReturnValue(
  77. workflowInCatalog ? [{ name: "goal" }, { name: "workflow" }, { name: "compact" }] : [],
  78. );
  79. const pluginItems = [item("plugins", "conflict", true), item("plugins", "enabled")];
  80. const fileItems = [item("files", "file:a")];
  81. const sessionItems = [item("sessions", "session:a")];
  82. for (const [mock, items, title] of [
  83. [mocks.plugins, pluginItems, "plugins"],
  84. [mocks.files, fileItems, "files"],
  85. [mocks.sessions, sessionItems, "sessions"],
  86. ] as const) {
  87. mock.mockReturnValue({ items, title, loading: false, error: null, emptyText: "" });
  88. }
  89. const savedState = {};
  90. const api = {
  91. getText: () => text,
  92. getEditorState: vi.fn(() => savedState),
  93. insertMention: vi.fn(),
  94. focus: vi.fn(),
  95. };
  96. const onSelect = vi.fn();
  97. const result = render(
  98. createElement(ChatPromptActionMenu, {
  99. actionMenuTitle: "Add context",
  100. attachmentAction: attachment ? { label: "Attachments", onSelect } : undefined,
  101. inputApiRef: { current: api as unknown as LexicalChatInputHandle },
  102. workspacePath: "/workspace",
  103. workspaceIdentity: "remote:test",
  104. sessionId,
  105. container: null,
  106. showPlugins: true,
  107. excludedSlashCommandNames,
  108. }),
  109. );
  110. fireEvent.click(screen.getByRole("button", { name: "Add context" }));
  111. return { ...result, api, savedState, onSelect, pluginItems, fileItems, sessionItems };
  112. }
  113. afterEach(() => {
  114. cleanup();
  115. vi.clearAllMocks();
  116. });
  117. describe("plus menu wiring", () => {
  118. it("preserves group order and provider scope without opting into disabled plugins", () => {
  119. setup();
  120. expect(
  121. [...document.querySelectorAll("[data-section]")].map((e) => e.getAttribute("data-section")),
  122. ).toEqual(["add", "plugins", "files", "sessions"]);
  123. expect(mocks.plugins.mock.lastCall).toEqual([
  124. "/workspace",
  125. "remote:test",
  126. "session-1",
  127. "",
  128. true,
  129. "chat.mention.plugins.empty",
  130. "chat.mention.plugins.title",
  131. ]);
  132. expect(mocks.files.mock.lastCall?.[6]).toBe(10);
  133. expect(mocks.sessions.mock.lastCall?.[5]).toBe("current-workspace");
  134. });
  135. it.each(["enabled", "file:a", "session:a"])(
  136. "inserts %s using the saved editor selection",
  137. (id) => {
  138. const { api, savedState } = setup();
  139. fireEvent.click(screen.getByText(id));
  140. expect(api.insertMention).toHaveBeenCalledWith(expect.objectContaining({ id }), savedState);
  141. },
  142. );
  143. it("inserts canonical goal when attachment is unavailable", () => {
  144. const { api, savedState } = setup(false, null);
  145. expect(screen.queryByText("attach-files")).toBeNull();
  146. fireEvent.click(screen.getByText("add-goal"));
  147. expect(api.insertMention).toHaveBeenCalledWith(
  148. expect.objectContaining({ category: "commands", markdown: "/goal", value: "goal" }),
  149. savedState,
  150. );
  151. });
  152. it.each([
  153. [null, "draft text"],
  154. ["session-1", ""],
  155. ["session-1", "message"],
  156. ] as const)("hides Goal for session=%s text=%s", (sessionId, text) => {
  157. setup(true, sessionId, text);
  158. expect(screen.queryByText("add-goal")).toBeNull();
  159. });
  160. it("offers Workflow right after Goal in an empty new draft when the catalog has it", () => {
  161. const { api, savedState } = setup(true, null, "", [], true);
  162. expect(
  163. [...document.querySelectorAll('[data-section="add"] button')].map((e) => e.textContent),
  164. ).toEqual(["attach-files", "add-goal", "add-workflow"]);
  165. fireEvent.click(screen.getByText("add-workflow"));
  166. expect(api.insertMention).toHaveBeenCalledWith(
  167. expect.objectContaining({ category: "commands", markdown: "/workflow", value: "workflow" }),
  168. savedState,
  169. );
  170. });
  171. it("offers Workflow without Goal in an existing session with an empty draft", () => {
  172. const { api } = setup(false, "session-1", "", [], true);
  173. expect(screen.queryByText("add-goal")).toBeNull();
  174. fireEvent.click(screen.getByText("add-workflow"));
  175. expect(api.insertMention).toHaveBeenCalledWith(
  176. expect.objectContaining({ markdown: "/workflow" }),
  177. expect.anything(),
  178. );
  179. });
  180. it("keeps mention indices aligned when Workflow is the only quick command", () => {
  181. const { api } = setup(true, "session-1", "", [], true);
  182. fireEvent.click(screen.getByText("enabled"));
  183. expect(api.insertMention).toHaveBeenCalledWith(
  184. expect.objectContaining({ id: "enabled" }),
  185. expect.anything(),
  186. );
  187. });
  188. it.each([
  189. ["non-empty draft", null, "draft text", [], true],
  190. ["catalog without workflow", null, "", [], false],
  191. ["excluded name", "session-1", "", ["workflow"], true],
  192. ] as const)("hides Workflow for %s", (_label, sessionId, text, excluded, inCatalog) => {
  193. setup(true, sessionId, text, excluded, inCatalog);
  194. expect(screen.queryByText("add-workflow")).toBeNull();
  195. });
  196. it("respects side chat Goal exclusions", () => {
  197. setup(true, null, "", ["goal"]);
  198. expect(screen.queryByText("add-goal")).toBeNull();
  199. });
  200. it("hides Goal for whitespace-only drafts", () => {
  201. setup(true, null, " ");
  202. expect(screen.queryByText("add-goal")).toBeNull();
  203. });
  204. it("omits an empty Add section", () => {
  205. setup(false, "session-1");
  206. expect(document.querySelector('[data-section="add"]')).toBeNull();
  207. });
  208. it("calls the attachment action once without inserting a mention", () => {
  209. const { api, onSelect } = setup();
  210. fireEvent.click(screen.getByText("attach-files"));
  211. expect(onSelect).toHaveBeenCalledTimes(1);
  212. expect(api.insertMention).not.toHaveBeenCalled();
  213. });
  214. it("rejects conflicts and skips them during keyboard navigation", () => {
  215. const { api } = setup();
  216. fireEvent.click(screen.getByText("conflict"));
  217. expect(api.insertMention).not.toHaveBeenCalled();
  218. const dialog = screen.getByRole("dialog");
  219. fireEvent.keyDown(dialog, { key: "ArrowDown" });
  220. fireEvent.keyDown(dialog, { key: "Enter" });
  221. expect(api.insertMention).toHaveBeenCalledWith(
  222. expect.objectContaining({ id: "enabled" }),
  223. expect.anything(),
  224. );
  225. });
  226. });