plugin-extension-mention.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // PLM-EXT-P2C:输入框 `@` 面板的插件分组 composer.mention(docs/plugins/extension-host.md §16.6)。
  2. // 隔离 HOME:两个纯 JS fixture 插件(test/e2e/fixtures/fs/plugins/plugin-extension-mention/)复制到 E2E HOME,
  3. // 经 ~/.zcode/cli/config.json 的 plugins.dirs 加载:
  4. // - e2e-ext-mention(扩展):条目 items 指向扩展命令 search。query 越短命令返回越慢(每少一个字多 1.5 秒),
  5. // 快速输入时旧结果晚到,验证只采用最新一次。
  6. // - e2e-mcp-mention(只有 MCP):条目 docs 指向 app 可见的工具 mention_search,CLI plugins/mentionItems 调它。
  7. // 首次调用在会话里弹审批:先拒绝(组内显示错误),再「始终允许」(候选项出现,之后不再询问)。
  8. // 发送用 replay:准备轮与插入轮按独立 marker 匹配 plugin-extension-mention.json;
  9. // 断言 provider 请求里有选中候选项的 insertText 原文。
  10. // 运行时证据:Main 日志([extensions] / [extension-host] / fixture 的 E2E_MENTION_*)、`@` 面板 DOM、
  11. // 输入框的 canonical markdown(Lexical E2E bridge)、MCP server 的调用记录、provider 请求捕获。
  12. import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
  13. import { join, resolve } from "node:path";
  14. import { TID_PROMPT_SUGGESTION_PANEL, TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  15. import { DEFAULT_WORKSPACE, clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  16. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  17. import { createExtensionLog, writePluginDirsConfig } from "#e2e/helpers/extension-host-views";
  18. import { waitForUpstreamNetworkCapture } from "#e2e/helpers/upstream-capture";
  19. import {
  20. approveV4PermissionAlways,
  21. clickV4Send,
  22. clickV4SlashOption,
  23. denyV4PermissionWithFeedback,
  24. prepareV4ConversationE2E,
  25. sendV4Prompt,
  26. waitForV4Pane,
  27. waitForV4PermissionDialog,
  28. } from "#e2e/helpers/v4-conversation";
  29. import {
  30. capturePluginManualReview,
  31. requirePluginManualReview,
  32. setPluginPresentation,
  33. } from "#e2e/helpers/plugin-management-lifecycle";
  34. const CASE_ID = "PLM-EXT-P2C";
  35. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  36. const FIXTURE_ROOT = resolve(
  37. process.cwd(),
  38. "test/e2e/fixtures/fs/plugins/plugin-extension-mention",
  39. );
  40. const PLUGINS = ["e2e-ext-mention", "e2e-mcp-mention"];
  41. const EXT_PLUGIN = "e2e-ext-mention@inline";
  42. const MCP_PLUGIN = "e2e-mcp-mention@inline";
  43. const EXT_ITEM = `${EXT_PLUGIN}/items`;
  44. const MCP_ITEM = `${MCP_PLUGIN}/docs`;
  45. const EXT_SECTION = `extension:${EXT_ITEM}`;
  46. const MCP_SECTION = `extension:${MCP_ITEM}`;
  47. // query 选不太可能命中文件、会话、插件名的字母,`@` 面板里只剩插件分组。
  48. const SLOW_QUERY = "qx";
  49. const FAST_QUERY = "qxjv";
  50. const CHOSEN = `ext:${EXT_ITEM}:${FAST_QUERY}-2`;
  51. const CHOSEN_INSERT = `E2E_MENTION_INSERT[${FAST_QUERY}#2]`;
  52. // MCP 分组的三次查询:拒绝、始终允许、允许后不再询问。
  53. const MCP_DENIED_QUERY = "jzq";
  54. const MCP_ALLOWED_QUERY = "jzqk";
  55. const MCP_AGAIN_QUERY = "jzqkw";
  56. const SETUP_PROMPT = `E2E_EXT_MENTION_SETUP: Reply with exactly "upstream-e2e-ok" and no other text.`;
  57. const REPLY_PROMPT = `Reply with exactly "upstream-e2e-ok" and no other text.`;
  58. const evidence: Record<string, unknown> = {};
  59. const log = createExtensionLog();
  60. function fixtureHome(): string {
  61. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-mention");
  62. }
  63. async function seedFixtures(): Promise<void> {
  64. const target = fixtureHome();
  65. await mkdir(target, { recursive: true });
  66. for (const name of PLUGINS) {
  67. await cp(join(FIXTURE_ROOT, name), join(target, name), { recursive: true, force: true });
  68. }
  69. await writePluginDirsConfig(
  70. PLUGINS.map((name) => join(target, name)),
  71. PLUGINS.map((name) => `${name}@inline`),
  72. );
  73. }
  74. interface MentionGroupReading {
  75. panelOpen: boolean;
  76. header: string | null;
  77. status: string | null;
  78. statusText: string;
  79. options: Array<{ id: string; text: string }>;
  80. }
  81. /** 读 `@` 面板里一个分组:组名、状态行(loading / error)与候选行(按 data-section-id)。 */
  82. async function readMentionGroup(sectionId: string): Promise<MentionGroupReading> {
  83. return browser.execute(
  84. (panelTestId, id) => {
  85. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  86. const rows = Array.from(
  87. panel?.querySelectorAll<HTMLElement>("[data-section-id]") ?? [],
  88. ).filter((element) => element.dataset.sectionId === id);
  89. const header = rows.find((element) =>
  90. element.dataset.testid?.startsWith("prompt-suggestion-section"),
  91. );
  92. const status = rows.find((element) => element.dataset.status);
  93. return {
  94. panelOpen: Boolean(panel),
  95. header: header?.textContent ?? null,
  96. status: status?.dataset.status ?? null,
  97. statusText: status?.textContent ?? "",
  98. options: rows
  99. .filter((element) => element.dataset.optionId)
  100. .map((element) => ({
  101. id: element.dataset.optionId ?? "",
  102. text: element.textContent ?? "",
  103. })),
  104. };
  105. },
  106. TID_PROMPT_SUGGESTION_PANEL,
  107. sectionId,
  108. );
  109. }
  110. async function waitForMentionGroup(
  111. sectionId: string,
  112. predicate: (group: MentionGroupReading) => boolean,
  113. message: string,
  114. timeout = 30000,
  115. ): Promise<MentionGroupReading> {
  116. let latest: MentionGroupReading | null = null;
  117. try {
  118. await browser.waitUntil(
  119. async () => {
  120. latest = await readMentionGroup(sectionId);
  121. return predicate(latest);
  122. },
  123. { timeout, interval: 200, timeoutMsg: message },
  124. );
  125. } catch (error) {
  126. const sections = await browser.execute(
  127. (panelTestId) => [
  128. ...new Set(
  129. Array.from(
  130. document
  131. .querySelector(`[data-testid="${panelTestId}"]`)
  132. ?.querySelectorAll<HTMLElement>("[data-section-id]") ?? [],
  133. ).map((element) => element.dataset.sectionId ?? ""),
  134. ),
  135. ],
  136. TID_PROMPT_SUGGESTION_PANEL,
  137. );
  138. await capturePluginManualReview(CASE_ID, `group-missing-${sectionId.split("/").pop()}`).catch(
  139. () => undefined,
  140. );
  141. throw new Error(`${message}: ${JSON.stringify({ latest, sections })}`, { cause: error });
  142. }
  143. return latest!;
  144. }
  145. /** 输入框的 canonical markdown(发送的就是它)与插件提及块。 */
  146. async function readComposer(): Promise<{ markdown: string; chips: string[] }> {
  147. return browser.execute((inputTestId) => {
  148. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  149. const bridge = (input as HTMLElement & { __zcodeLexicalInputE2E?: { getText: () => string } })
  150. ?.__zcodeLexicalInputE2E;
  151. return {
  152. markdown: bridge?.getText() ?? "",
  153. chips: Array.from(
  154. input?.querySelectorAll<HTMLElement>('[data-mention-category="extensions"]') ?? [],
  155. ).map((element) => element.textContent ?? ""),
  156. };
  157. }, TID_V4_COMPOSER_INPUT);
  158. }
  159. /** 光标移到输入框末尾后输入(选中候选项后编辑器已在 rAF 里拿回焦点)。 */
  160. async function typeAtComposerEnd(text: string): Promise<void> {
  161. await focusAppWindow();
  162. await browser.execute((inputTestId) => {
  163. const input = document.querySelector<
  164. HTMLElement & { __zcodeLexicalInputE2E?: { focus: () => void } }
  165. >(`[data-testid="${inputTestId}"]`);
  166. input?.__zcodeLexicalInputE2E?.focus();
  167. }, TID_V4_COMPOSER_INPUT);
  168. await browser.keys(text.split(""));
  169. }
  170. async function readMcpCalls(): Promise<Array<{ event: string; query?: string }>> {
  171. const raw = await readFile(join(fixtureHome(), "e2e-mcp-mention-calls.jsonl"), "utf8").catch(
  172. () => "",
  173. );
  174. return raw
  175. .split("\n")
  176. .filter(Boolean)
  177. .map((line) => JSON.parse(line) as { event: string; query?: string });
  178. }
  179. /**
  180. * 让页面始终按「有焦点」处理(CDP Emulation.setFocusEmulationEnabled),并等文档拿到焦点。
  181. * `@` 面板只在编辑器有选区时打开,审批卡片的键盘选择也要焦点。
  182. * 修复原因:同一台机器上并行跑的其他 E2E(别的 worktree)会抢走前台,编辑器 focus 落空,面板不打开
  183. * (运行时证据:document.hasFocus() === false、activeElement 是 body;切前台后又被立即抢走)。
  184. * 焦点模拟不依赖操作系统的前台窗口,不和别的运行抢。
  185. */
  186. async function focusAppWindow(): Promise<void> {
  187. await browser.electron.execute(async (electron) => {
  188. const window = electron.BrowserWindow.getAllWindows().find(
  189. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  190. );
  191. if (!window) throw new Error("no visible app window");
  192. if (!window.webContents.debugger.isAttached()) window.webContents.debugger.attach("1.3");
  193. await window.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {
  194. enabled: true,
  195. });
  196. });
  197. await browser.waitUntil(() => browser.execute(() => document.hasFocus()), {
  198. timeout: 15000,
  199. interval: 300,
  200. timeoutMsg: "the page should have focus under focus emulation",
  201. });
  202. }
  203. /**
  204. * 写入 `@` 查询,光标在末尾。先清空、再聚焦、再写入,各占一帧:
  205. * 修复原因:带着旧文本聚焦时,浏览器会把光标放回旧位置,触发器按光标前的文本算出半截查询
  206. * (运行时日志:审批后重新打开 `@jzq` 时扩展先收到 q="jz"),tool 条目会因此多弹一次审批。
  207. * 清空后聚焦没有 `@`,不会查询;最后 setText 由 Lexical 把选区放到末尾。
  208. */
  209. async function writeMentionQuery(query: string): Promise<void> {
  210. await focusAppWindow();
  211. const written = await browser.executeAsync(
  212. (inputTestId, text, done: (result?: string) => void) => {
  213. const input = document.querySelector<
  214. HTMLElement & {
  215. __zcodeLexicalInputE2E?: { focus: () => void; setText: (value: string) => void };
  216. }
  217. >(`[data-testid="${inputTestId}"]`);
  218. const bridge = input?.__zcodeLexicalInputE2E;
  219. if (!input?.isContentEditable || !bridge) {
  220. done("not-editable");
  221. return;
  222. }
  223. bridge.setText("");
  224. requestAnimationFrame(() => {
  225. bridge.focus();
  226. requestAnimationFrame(() => {
  227. bridge.setText(text);
  228. done("ok");
  229. });
  230. });
  231. },
  232. TID_V4_COMPOSER_INPUT,
  233. `@${query}`,
  234. );
  235. if (written !== "ok") {
  236. throw new Error(`the composer should accept the @ query ${query}: ${written}`);
  237. }
  238. }
  239. /** 写入 `@` 查询后等面板打开;打不开时带上焦点与输入框状态并截图,便于定位。 */
  240. async function setMentionQuery(query: string): Promise<void> {
  241. await writeMentionQuery(query);
  242. try {
  243. await browser.waitUntil(
  244. () =>
  245. browser.execute(
  246. (panelTestId) => Boolean(document.querySelector(`[data-testid="${panelTestId}"]`)),
  247. TID_PROMPT_SUGGESTION_PANEL,
  248. ),
  249. { timeout: 15000, interval: 200, timeoutMsg: `the @ panel should open for ${query}` },
  250. );
  251. } catch (error) {
  252. const state = await browser.execute((inputTestId) => {
  253. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  254. return {
  255. hasFocus: document.hasFocus(),
  256. active: (document.activeElement as HTMLElement | null)?.dataset.testid ?? null,
  257. inComposer: Boolean(input?.contains(document.activeElement)),
  258. editable: input?.isContentEditable ?? null,
  259. anchor: window.getSelection()?.anchorNode?.textContent ?? null,
  260. anchorOffset: window.getSelection()?.anchorOffset ?? null,
  261. composers: document.querySelectorAll(`[data-testid="${inputTestId}"]`).length,
  262. };
  263. }, TID_V4_COMPOSER_INPUT);
  264. await capturePluginManualReview(CASE_ID, `panel-missing-${query}`).catch(() => undefined);
  265. throw new Error(`@ panel did not open: ${JSON.stringify(state)}`, { cause: error });
  266. }
  267. }
  268. /**
  269. * 审批卡片替换输入框、切换语言或主题时面板会关闭;用同一查询重新打开。键没变,不重发,直接显示已有结果。
  270. */
  271. const reopenMentionQuery = setMentionQuery;
  272. async function capture(label: string): Promise<string> {
  273. await browser.pause(300);
  274. return capturePluginManualReview(CASE_ID, label);
  275. }
  276. describe("PLM-EXT-P2C 输入框 @ 面板的插件分组", () => {
  277. after(async () => {
  278. await writeFile(
  279. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-p2c-evidence.json"),
  280. JSON.stringify(evidence, null, 2),
  281. ).catch(() => undefined);
  282. await clearAppData();
  283. });
  284. it("MCP 工具分组(先跑:之后的查询不再弹审批):首次调用在会话里弹审批,拒绝显示组内错误,始终允许后显示候选项", async function () {
  285. this.timeout(600000);
  286. requirePluginManualReview();
  287. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  288. await seedFixtures();
  289. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  290. afterElectronProcessExit: () => log.mark(),
  291. });
  292. await prepareV4ConversationE2E();
  293. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  294. await log.waitFor(
  295. (line) => line.includes(`[${EXT_PLUGIN}] activated in`),
  296. "the mention extension should activate",
  297. 60000,
  298. );
  299. evidence.staticTable = await log.waitFor(
  300. (line) => line.includes("[extensions]") && /static table rev=\d+ .*items=/.test(line),
  301. "the window host should read the static table",
  302. );
  303. // 先发一条消息,让草稿成为正式会话:「始终允许本项目」只在已持久化的会话里写进项目规则。
  304. // 运行时证据:草稿(预热会话)里选「始终允许本项目」后 CLI 记
  305. // `Project permission update skipped without persisted session`,同一会话的下一次调用仍然询问。
  306. await sendV4Prompt(SETUP_PROMPT);
  307. const session = await waitForV4Pane(
  308. (snapshot) =>
  309. Boolean(snapshot.sessionId && snapshot.sessionId !== "draft") &&
  310. snapshot.timelineText.includes("upstream-e2e-ok"),
  311. "the setup message should create a session",
  312. 60000,
  313. );
  314. evidence.sessionId = session.sessionId;
  315. // MCP server 随会话启动:等会话列出它的工具再查,否则首个查询会因工具还没列出而失败。
  316. await browser.waitUntil(
  317. async () => (await readMcpCalls()).some((call) => call.event === "listed"),
  318. {
  319. timeout: 60000,
  320. interval: 500,
  321. timeoutMsg: "the session should list the mention MCP tools",
  322. },
  323. );
  324. // (b1) 拒绝:组内显示「已拒绝调用插件工具」,不影响扩展分组。
  325. await writeMentionQuery(MCP_DENIED_QUERY);
  326. await waitForV4PermissionDialog();
  327. await capture("mcp-mention-approval-zh-CN-zai-light");
  328. await focusAppWindow();
  329. expect(await denyV4PermissionWithFeedback("")).toBe(true);
  330. evidence.deniedLog = await log.waitFor(
  331. (line) =>
  332. line.includes("mention items error") &&
  333. line.includes(`entry=${MCP_ITEM}`) &&
  334. line.includes("code=plugin_mention_tool_denied"),
  335. "the window host should report the denied tool call",
  336. );
  337. // 审批卡片替换输入框时面板关闭;同一查询重新打开面板,不重发,直接显示拒绝结果。
  338. await reopenMentionQuery(MCP_DENIED_QUERY);
  339. const denied = await waitForMentionGroup(
  340. MCP_SECTION,
  341. (group) => group.status === "notice",
  342. "the MCP group should show the denied state",
  343. );
  344. evidence.deniedGroup = denied;
  345. expect(denied.header).toContain("E2E 文档");
  346. expect(denied.statusText).toContain("已拒绝调用插件工具");
  347. const extensionBesideDenied = await waitForMentionGroup(
  348. EXT_SECTION,
  349. (group) => group.options.length === 3,
  350. "the extension group should still show its candidates",
  351. );
  352. evidence.extensionBesideDenied = extensionBesideDenied.options.map((option) => option.id);
  353. expect(
  354. await waitForV4PermissionDialog(2000)
  355. .then(() => true)
  356. .catch(() => false),
  357. ).toBe(false);
  358. await capture("mcp-mention-denied-zh-CN-zai-light");
  359. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  360. await reopenMentionQuery(MCP_DENIED_QUERY);
  361. await waitForMentionGroup(
  362. MCP_SECTION,
  363. (group) => group.statusText.includes("denied"),
  364. "the denied state should follow en-US",
  365. );
  366. await capture("mcp-mention-denied-en-US-zai-dark");
  367. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  368. // (b2) 始终允许:候选项出现;之后的查询不再询问。
  369. await writeMentionQuery(MCP_ALLOWED_QUERY);
  370. await waitForV4PermissionDialog();
  371. await focusAppWindow();
  372. await approveV4PermissionAlways();
  373. await reopenMentionQuery(MCP_ALLOWED_QUERY);
  374. const allowed = await waitForMentionGroup(
  375. MCP_SECTION,
  376. (group) =>
  377. group.options.some((option) => option.id === `ext:${MCP_ITEM}:${MCP_ALLOWED_QUERY}-1`),
  378. "the MCP group should show the tool's candidates after approval",
  379. );
  380. evidence.allowedGroup = allowed;
  381. await setMentionQuery(MCP_AGAIN_QUERY);
  382. const again = await waitForMentionGroup(
  383. MCP_SECTION,
  384. (group) =>
  385. group.options.some((option) => option.id === `ext:${MCP_ITEM}:${MCP_AGAIN_QUERY}-1`),
  386. "the next query should not ask again",
  387. );
  388. evidence.againGroup = again;
  389. expect(
  390. await waitForV4PermissionDialog(1000)
  391. .then(() => true)
  392. .catch(() => false),
  393. ).toBe(false);
  394. for (const [locale, theme] of [
  395. ["zh-CN", "zai-light"],
  396. ["en-US", "zai-dark"],
  397. ] as const) {
  398. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  399. await reopenMentionQuery(MCP_AGAIN_QUERY);
  400. await waitForMentionGroup(
  401. MCP_SECTION,
  402. (group) => (group.header ?? "").includes(locale === "en-US" ? "E2E docs" : "E2E 文档"),
  403. `the MCP group title should follow ${locale}`,
  404. );
  405. await capture(`mcp-mention-items-${locale}-${theme}`);
  406. }
  407. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  408. const calls = await readMcpCalls();
  409. evidence.mcpCalls = calls;
  410. // 被拒绝的调用没有到达 server;批准后的两次都到了。
  411. expect(calls.filter((call) => call.event === "call").map((call) => call.query)).toEqual([
  412. MCP_ALLOWED_QUERY,
  413. MCP_AGAIN_QUERY,
  414. ]);
  415. evidence.lifecycle = (await log.lines()).filter((line) =>
  416. /static table|mention items|E2E_MENTION|activated in/.test(line),
  417. );
  418. });
  419. it("扩展命令分组:快速输入只采用最新结果,选中插入 insertText,发送后请求里有原文", async function () {
  420. this.timeout(600000);
  421. // (a1) 慢查询:命令收到 { query: "qx" },结果 3 秒后才回。结果回来前组里不会有 qx 的候选项
  422. // (上一个用例已经查过,组里是上次采用的结果;没有结果时显示加载)。
  423. const linesBeforeSlow = (await log.lines()).length;
  424. await setMentionQuery(SLOW_QUERY);
  425. evidence.slowQueryLog = await log.waitFor(
  426. (line) => line.includes(`E2E_MENTION_QUERY q="${SLOW_QUERY}"`),
  427. "the extension command should receive the slow query",
  428. );
  429. expect(String(evidence.slowQueryLog)).toContain("scope=session");
  430. const pending = await readMentionGroup(EXT_SECTION);
  431. evidence.pendingGroup = pending;
  432. expect(pending.header).toContain("E2E 条目");
  433. expect(pending.options.some((option) => option.id.includes(`:${SLOW_QUERY}-`))).toBe(false);
  434. await capture("mention-pending-zh-CN-zai-light");
  435. // (a2) 快速输入:新查询立即返回,组显示它的候选项。
  436. await setMentionQuery(FAST_QUERY);
  437. const fast = await waitForMentionGroup(
  438. EXT_SECTION,
  439. (group) => group.options.some((option) => option.id === CHOSEN),
  440. "the extension group should show the latest query's candidates",
  441. );
  442. evidence.fastGroup = fast;
  443. expect(fast.options.map((option) => option.id)).toEqual(
  444. [1, 2, 3].map((n) => `ext:${EXT_ITEM}:${FAST_QUERY}-${n}`),
  445. );
  446. // (a3) 旧查询的结果晚到:丢弃,组仍是最新查询的候选项。
  447. evidence.slowDoneLog = await log.waitFor(
  448. (line) => line.includes(`E2E_MENTION_DONE q="${SLOW_QUERY}"`),
  449. "the slow query should finish after the fast one",
  450. );
  451. const queryOrder = (await log.lines())
  452. .slice(linesBeforeSlow)
  453. .filter((line) => line.includes("E2E_MENTION_"));
  454. evidence.queryOrder = queryOrder;
  455. const fastDone = queryOrder.findIndex((line) =>
  456. line.includes(`E2E_MENTION_DONE q="${FAST_QUERY}"`),
  457. );
  458. const slowDone = queryOrder.findIndex((line) =>
  459. line.includes(`E2E_MENTION_DONE q="${SLOW_QUERY}"`),
  460. );
  461. expect(fastDone).toBeGreaterThanOrEqual(0);
  462. expect(slowDone).toBeGreaterThan(fastDone);
  463. // 每次输入只发一次查询(没有面板刚打开时的空串查询)。
  464. expect(
  465. queryOrder
  466. .filter((line) => line.includes("E2E_MENTION_QUERY"))
  467. .map((line) => /q="([^"]*)"/.exec(line)?.[1]),
  468. ).toEqual([SLOW_QUERY, FAST_QUERY]);
  469. // 晚到的结果要经过 Window Host 回到 Renderer:等一小段时间再读,确认没有被它覆盖。
  470. await browser.pause(1500);
  471. const afterStale = await readMentionGroup(EXT_SECTION);
  472. evidence.afterStaleGroup = afterStale;
  473. expect(afterStale.options.map((option) => option.id)).toEqual(fast.options.map((o) => o.id));
  474. for (const [locale, theme] of [
  475. ["zh-CN", "zai-light"],
  476. ["zh-CN", "zai-dark"],
  477. ["en-US", "zai-light"],
  478. ["en-US", "zai-dark"],
  479. ] as const) {
  480. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  481. await reopenMentionQuery(FAST_QUERY);
  482. await waitForMentionGroup(
  483. EXT_SECTION,
  484. (group) =>
  485. (group.header ?? "").includes(locale === "en-US" ? "E2E items" : "E2E 条目") &&
  486. group.options.length === 3,
  487. `the extension group title should follow ${locale}`,
  488. );
  489. await capture(`mention-items-${locale}-${theme}`);
  490. }
  491. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  492. await reopenMentionQuery(FAST_QUERY);
  493. await waitForMentionGroup(
  494. EXT_SECTION,
  495. (group) => group.options.some((option) => option.id === CHOSEN),
  496. "the extension group should still be open",
  497. );
  498. // (a4) 选中:插入提及块,输入框的 markdown 就是 insertText 原文(后面跟一个空格)。
  499. await focusAppWindow();
  500. expect(await clickV4SlashOption(CHOSEN)).toBe(true);
  501. await browser.waitUntil(async () => (await readComposer()).markdown === `${CHOSEN_INSERT} `, {
  502. timeout: 10000,
  503. timeoutMsg: `the composer markdown should be the insertText: ${JSON.stringify(await readComposer())}`,
  504. });
  505. const composer = await readComposer();
  506. evidence.composerAfterChoose = composer;
  507. expect(composer.chips).toEqual([`E2E ${FAST_QUERY} #2`]);
  508. await capture("mention-chip-zh-CN-zai-light");
  509. // (a5) 发送(replay):provider 请求里有 insertText 原文。
  510. await typeAtComposerEnd(REPLY_PROMPT);
  511. await browser.waitUntil(
  512. async () => (await readComposer()).markdown === `${CHOSEN_INSERT} ${REPLY_PROMPT}`,
  513. {
  514. timeout: 10000,
  515. timeoutMsg: `the composer should hold the chip and the prompt: ${JSON.stringify(await readComposer())}`,
  516. },
  517. );
  518. await clickV4Send();
  519. const request = await waitForUpstreamNetworkCapture(CHOSEN_INSERT);
  520. evidence.requestPath = request.path;
  521. // 请求体是 JSON:提示词里的引号被转义,按同一种转义比较。
  522. expect(JSON.stringify(request.requestJson)).toContain(
  523. JSON.stringify(`${CHOSEN_INSERT} ${REPLY_PROMPT}`).slice(1, -1),
  524. );
  525. await waitForV4Pane(
  526. (snapshot) =>
  527. snapshot.timelineText.includes(`E2E ${FAST_QUERY} #2`) ||
  528. snapshot.timelineText.includes(CHOSEN_INSERT),
  529. "the sent message with the mention should appear in the timeline",
  530. 60000,
  531. );
  532. await capture("mention-sent-zh-CN-zai-light");
  533. });
  534. });