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

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