conversation-session-composer-prefix-routing.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  4. import { DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  5. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  6. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  7. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  8. const TEST_TIMEOUT_MS = 120000;
  9. const TID_PROMPT_SUGGESTION_PANEL = "prompt-suggestion-panel";
  10. const TID_PROMPT_SUGGESTION_OPTION = "prompt-suggestion-option";
  11. const TID_PROMPT_SUGGESTION_STATUS = "prompt-suggestion-status";
  12. const createdWorkspacePaths: string[] = [];
  13. interface PanelOptionSnapshot {
  14. id: string | null;
  15. index: number;
  16. sectionId: string | null;
  17. selected: boolean;
  18. text: string;
  19. }
  20. interface PanelSnapshot {
  21. options: PanelOptionSnapshot[];
  22. statuses: Array<{ sectionId: string | null; status: string | null; text: string }>;
  23. trigger: string | null;
  24. }
  25. describe("会话区 Composer 前缀提示路由 E2E", () => {
  26. before(async function () {
  27. this.timeout(TEST_TIMEOUT_MS);
  28. await prepareV4ConversationE2E();
  29. });
  30. beforeEach(async function () {
  31. this.timeout(TEST_TIMEOUT_MS);
  32. // 文件及候选夹具归属于项目;全局新建会切到未归类 cwd,无法读取这里的文件。
  33. await startDraftFromProject(DEFAULT_WORKSPACE);
  34. });
  35. after(async () => {
  36. await Promise.all(
  37. createdWorkspacePaths.map((targetPath) => rm(targetPath, { recursive: true, force: true })),
  38. );
  39. await browser.electron.restoreAllMocks();
  40. // 修复原因:task index sqlite 由 host/service 生命周期持有,Windows 上在
  41. // spec-level after 里删除整个 appData 会撞到仍打开的 -shm 文件。全局 e2e
  42. // beforeSession 会重置隔离 HOME,Electron 退出后的兜底清理由 wdio 生命周期处理。
  43. });
  44. it("@ 聚合 plugin/file/session/whiteboard,/ 提示 command/skill/subagent,$ 兼容面板保留,且键盘选择写入正确 mention", async function () {
  45. this.timeout(TEST_TIMEOUT_MS);
  46. const runId = Date.now();
  47. const seed = {
  48. commandName: `e2e-cmd-${runId}`,
  49. directoryName: `e2e-route-dir-${runId}`,
  50. fileName: `e2e-route-file-${runId}.ts`,
  51. skillName: `e2e-skill-${runId}`,
  52. subagentName: `e2e-agent-${runId}`,
  53. whiteboardName: `e2e-route-board-${runId}`,
  54. };
  55. // 目录现在由 CLI runtime 持有。旧测试写 renderer store 会被真实加载覆盖;
  56. // 冷启动前准备文件,确保本轮 prewarm 的冻结目录包含这三类候选。
  57. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  58. afterElectronProcessExit: async () => {
  59. await seedWorkspaceFileCandidates(seed);
  60. await seedPromptCatalogFiles(seed);
  61. },
  62. });
  63. await startDraftFromProject(DEFAULT_WORKSPACE);
  64. await createWhiteboard(seed.whiteboardName);
  65. await setComposerText(`@${seed.fileName}`);
  66. const atFilePanel = await waitForPanelSections("@", ["files"], "@ 文件候选面板没有打开");
  67. expect(optionTexts(atFilePanel).join("\n")).toContain(seed.fileName);
  68. assertPanelExcludesSections(atFilePanel, ["commands", "subagents", "skills"]);
  69. await browser.keys("Enter");
  70. await waitForComposerMarkdownContaining(
  71. seed.fileName,
  72. "@ 文件候选 Enter 后没有写入文件 mention markdown",
  73. );
  74. await setComposerText(`@${seed.directoryName}`);
  75. const atDirectoryPanel = await waitForPanelSections("@", ["files"], "@ 文件夹候选面板没有打开");
  76. expect(optionTexts(atDirectoryPanel).join("\n")).toContain(seed.directoryName);
  77. await browser.keys("Tab");
  78. await waitForComposerMarkdownContaining(
  79. `${seed.directoryName}/`,
  80. "@ 文件夹候选 Tab 后没有写入目录 mention markdown",
  81. );
  82. await setComposerText(`@${seed.whiteboardName}`);
  83. const atWhiteboardPanel = await waitForPanelSections(
  84. "@",
  85. ["whiteboards"],
  86. "@ 画板候选面板没有打开",
  87. );
  88. expect(optionTexts(atWhiteboardPanel).join("\n")).toContain(seed.whiteboardName);
  89. assertPanelExcludesSections(atWhiteboardPanel, ["commands", "subagents", "skills"]);
  90. // S01 语义:`@` 固定按 plugins → files → sessions → whiteboards 路由;
  91. // 当前 query 只命中 Plugin,选中后仍写入既有 canonical plugin:// markdown。
  92. // 默认启用的官方纯内容插件 skill-creator 作为确定性候选;选中写入 canonical plugin:// markdown。
  93. await setComposerText("@skill-creator");
  94. const atPluginPanel = await waitForPanelSections("@", ["plugins"], "@ plugin 候选面板没有打开");
  95. // 展示名称随语言变化;下方仍精确校验选中的 canonical plugin 标识。
  96. expect(optionTexts(atPluginPanel).join("\n")).toMatch(/skill-creator|技能创建器/u);
  97. assertPanelExcludesSections(atPluginPanel, ["commands", "subagents", "skills"]);
  98. await browser.keys("Enter");
  99. await waitForComposerMarkdownContaining(
  100. "plugin://skill-creator@zcode-plugins-official",
  101. "@ plugin 候选 Enter 后没有写入 canonical plugin mention markdown",
  102. );
  103. // 候选列表虚拟化后,空 query 的 subagent 可能尚未挂载到 DOM;
  104. // 用三个磁盘夹具共有的前缀同时命中三组,仍精确验证分组顺序与排除项。
  105. await setComposerText("/e2e-");
  106. const slashPanel = await waitForPanelSections(
  107. "/",
  108. ["commands", "skills", "subagents"],
  109. "/ 候选面板没有打开",
  110. );
  111. assertPanelExcludesSections(slashPanel, ["files", "whiteboards"]);
  112. await setComposerText(`/${seed.commandName}`);
  113. const slashCommandPanel = await waitForPanelSections(
  114. "/",
  115. ["commands"],
  116. "/ command 候选面板没有打开",
  117. );
  118. expect(optionTexts(slashCommandPanel).join("\n")).toContain(`/${seed.commandName}`);
  119. await browser.keys("Enter");
  120. await waitForComposerMarkdown(
  121. `/${seed.commandName}`,
  122. "/ command 候选 Enter 后没有写入 slash command mention markdown",
  123. );
  124. await setComposerText(`/${seed.skillName}`);
  125. const slashSkillPanel = await waitForPanelSections("/", ["skills"], "/ skill 候选面板没有打开");
  126. expect(optionTexts(slashSkillPanel).join("\n")).toContain(`$${seed.skillName}`);
  127. await browser.keys("Enter");
  128. await waitForComposerMarkdownContaining(
  129. `$${seed.skillName}`,
  130. "/ skill 候选 Enter 后没有写入 skill mention markdown",
  131. );
  132. await setComposerText(`/${seed.subagentName}`);
  133. const slashSubagentPanel = await waitForPanelSections(
  134. "/",
  135. ["subagents"],
  136. "/ subagent 候选面板没有打开",
  137. );
  138. expect(optionTexts(slashSubagentPanel).join("\n")).toContain(seed.subagentName);
  139. await browser.keys("Tab");
  140. await waitForComposerMarkdown(
  141. `@${seed.subagentName}`,
  142. "/ subagent 候选 Tab 后没有写入 subagent mention markdown",
  143. );
  144. await setComposerText(`$${seed.skillName}`);
  145. const skillPanel = await waitForPanelSections("$", ["skills"], "$ skill 候选面板没有打开");
  146. expect(optionTexts(skillPanel).join("\n")).toContain(seed.skillName);
  147. assertPanelExcludesSections(skillPanel, ["files", "whiteboards", "commands", "subagents"]);
  148. await browser.keys("Enter");
  149. await waitForComposerMarkdownContaining(
  150. `$${seed.skillName}`,
  151. "$ skill 候选 Enter 后没有写入 skill mention markdown",
  152. );
  153. });
  154. });
  155. async function seedWorkspaceFileCandidates(seed: { directoryName: string; fileName: string }) {
  156. const directoryPath = join(DEFAULT_WORKSPACE, seed.directoryName);
  157. const filePath = join(DEFAULT_WORKSPACE, seed.fileName);
  158. await mkdir(directoryPath, { recursive: true });
  159. await writeFile(filePath, "export const e2eComposerPrefixRouting = true;\n", "utf-8");
  160. createdWorkspacePaths.push(directoryPath, filePath);
  161. }
  162. async function seedPromptCatalogFiles(seed: {
  163. commandName: string;
  164. skillName: string;
  165. subagentName: string;
  166. }) {
  167. const files: Array<[string, string]> = [
  168. [
  169. join(DEFAULT_WORKSPACE, ".zcode", "commands", `${seed.commandName}.md`),
  170. `---\ndescription: E2E prefix command\nargument-hint: [topic]\n---\nPrefix fixture $ARGUMENTS.\n`,
  171. ],
  172. [
  173. join(DEFAULT_WORKSPACE, ".zcode", "skills", seed.skillName, "SKILL.md"),
  174. `---\nname: ${seed.skillName}\ndescription: E2E prefix skill\n---\nUse only for prefix routing.\n`,
  175. ],
  176. [
  177. join(DEFAULT_WORKSPACE, ".zcode", "agents", `${seed.subagentName}.md`),
  178. `---\nname: ${seed.subagentName}\ndescription: E2E prefix subagent\ntools: Read\n---\nUse only for prefix routing.\n`,
  179. ],
  180. ];
  181. for (const [file, body] of files) {
  182. await mkdir(join(file, ".."), { recursive: true });
  183. await writeFile(file, body, "utf8");
  184. createdWorkspacePaths.push(file);
  185. }
  186. }
  187. async function createWhiteboard(name: string) {
  188. await browser.execute(
  189. (workspacePath, boardName) => {
  190. const store = (
  191. window as unknown as {
  192. __whiteboardStoreE2E: {
  193. getState(): {
  194. createBoard(params: { defaultNamePrefix: string; workspacePath: string }): {
  195. id: string;
  196. };
  197. renameBoard(params: { boardId: string; name: string; workspacePath: string }): void;
  198. };
  199. };
  200. }
  201. ).__whiteboardStoreE2E;
  202. const board = store
  203. .getState()
  204. .createBoard({ workspacePath, defaultNamePrefix: "E2E route board" });
  205. store.getState().renameBoard({ workspacePath, boardId: board.id, name: boardName });
  206. },
  207. DEFAULT_WORKSPACE,
  208. name,
  209. );
  210. }
  211. async function setComposerText(text: string) {
  212. await browser.waitUntil(
  213. async () =>
  214. browser.execute(
  215. (inputTestId, nextText) => {
  216. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`) as
  217. | (HTMLElement & {
  218. __zcodeLexicalInputE2E?: {
  219. focus: () => void;
  220. setText: (value: string) => void;
  221. };
  222. })
  223. | null;
  224. const bridge = input?.__zcodeLexicalInputE2E;
  225. if (!bridge) {
  226. return false;
  227. }
  228. bridge.setText(nextText);
  229. bridge.focus();
  230. return true;
  231. },
  232. TID_V4_COMPOSER_INPUT,
  233. text,
  234. ),
  235. {
  236. timeout: 10000,
  237. timeoutMsg: `composer prefix routing: 输入框 E2E bridge 未就绪,无法输入 ${text}`,
  238. },
  239. );
  240. }
  241. async function waitForPanelSections(
  242. trigger: string,
  243. expectedSectionIds: string[],
  244. timeoutMsg: string,
  245. ) {
  246. let latest: PanelSnapshot | null = null;
  247. await browser.waitUntil(
  248. async () => {
  249. latest = await getPanelSnapshot();
  250. // 修复原因:CI runner 上 Lexical 文本更新和 suggestion 过滤会跨帧完成。
  251. // 只等待 trigger/options 会读到上一帧的全量面板,导致 query-specific 断言误判。
  252. return (
  253. latest.trigger === trigger &&
  254. latest.options.length > 0 &&
  255. arraysEqual(optionSectionIds(latest), expectedSectionIds)
  256. );
  257. },
  258. {
  259. timeout: 15000,
  260. timeoutMsg,
  261. },
  262. );
  263. return latest ?? getPanelSnapshot();
  264. }
  265. function arraysEqual(left: string[], right: string[]) {
  266. return left.length === right.length && left.every((value, index) => value === right[index]);
  267. }
  268. function getPanelSnapshot(): Promise<PanelSnapshot> {
  269. return browser.execute(
  270. (panelTestId, optionPrefix, statusPrefix) => {
  271. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  272. const options = Array.from(
  273. panel?.querySelectorAll<HTMLElement>(`[data-testid^="${optionPrefix}-"]`) ?? [],
  274. ).map((element) => ({
  275. id: element.getAttribute("data-option-id"),
  276. index: Number(element.getAttribute("data-option-index") ?? "0"),
  277. sectionId: element.getAttribute("data-section-id"),
  278. selected: element.getAttribute("data-selected") === "true",
  279. text: (element.innerText || element.textContent || "").replace(/\u00a0/g, " ").trim(),
  280. }));
  281. const statuses = Array.from(
  282. panel?.querySelectorAll<HTMLElement>(`[data-testid^="${statusPrefix}-"]`) ?? [],
  283. ).map((element) => ({
  284. sectionId: element.getAttribute("data-section-id"),
  285. status: element.getAttribute("data-status"),
  286. text: (element.innerText || element.textContent || "").replace(/\u00a0/g, " ").trim(),
  287. }));
  288. return {
  289. options,
  290. statuses,
  291. trigger: panel?.getAttribute("data-trigger") ?? null,
  292. };
  293. },
  294. TID_PROMPT_SUGGESTION_PANEL,
  295. TID_PROMPT_SUGGESTION_OPTION,
  296. TID_PROMPT_SUGGESTION_STATUS,
  297. );
  298. }
  299. function optionSectionIds(snapshot: PanelSnapshot) {
  300. return [
  301. ...new Set(
  302. snapshot.options
  303. .map((item) => item.sectionId)
  304. .filter((value): value is string => Boolean(value)),
  305. ),
  306. ];
  307. }
  308. function optionTexts(snapshot: PanelSnapshot) {
  309. return snapshot.options.map((option) => option.text);
  310. }
  311. function assertPanelExcludesSections(snapshot: PanelSnapshot, excludedSectionIds: string[]) {
  312. const actualSectionIds = optionSectionIds(snapshot);
  313. for (const excluded of excludedSectionIds) {
  314. expect(actualSectionIds).not.toContain(excluded);
  315. }
  316. }
  317. async function waitForComposerMarkdown(expected: string, timeoutMsg: string) {
  318. await browser.waitUntil(async () => (await getComposerMarkdown()).trim() === expected, {
  319. timeout: 10000,
  320. timeoutMsg,
  321. });
  322. }
  323. async function waitForComposerMarkdownContaining(expected: string, timeoutMsg: string) {
  324. await browser.waitUntil(async () => (await getComposerMarkdown()).includes(expected), {
  325. timeout: 10000,
  326. timeoutMsg,
  327. });
  328. }
  329. function getComposerMarkdown(): Promise<string> {
  330. return browser.execute((inputTestId) => {
  331. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`) as
  332. | (HTMLElement & {
  333. __zcodeLexicalInputE2E?: { getText: () => string };
  334. })
  335. | null;
  336. return input?.__zcodeLexicalInputE2E?.getText() ?? "";
  337. }, TID_V4_COMPOSER_INPUT);
  338. }