conversation-session-assistant-preview-cards.test.ts 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. /* eslint-disable max-lines -- APC01-APC15 共用真实 Host stat、Browser/Preview Pane 与 cold-resume fixture。 */
  2. import {
  3. copyFile,
  4. mkdir,
  5. readFile,
  6. readdir,
  7. realpath,
  8. rm,
  9. stat,
  10. writeFile,
  11. } from "node:fs/promises";
  12. import { createServer, type Server } from "node:http";
  13. import type { AddressInfo } from "node:net";
  14. import { basename, dirname, join } from "node:path";
  15. import { fileURLToPath } from "node:url";
  16. import {
  17. TID_BROWSER_ADDRESS_INPUT,
  18. TID_BROWSER_WEBVIEW,
  19. TID_PREVIEW_PANE,
  20. } from "@zcode/shared/test-ids";
  21. import type { ChainablePromiseElement } from "webdriverio";
  22. import { PlatformChannels, type FileApplicationInfo } from "@zcode/shared";
  23. import {
  24. installFileApplicationMenuProbe,
  25. readFileApplicationMenuProbe,
  26. readFileLocateProbe,
  27. readFileManagerRevealProbe,
  28. restoreFileApplicationMenuProbe,
  29. } from "#e2e/helpers/file-application-menu-probe";
  30. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  31. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart";
  32. import {
  33. clickV4Stop,
  34. prepareV4ConversationE2E,
  35. selectV4TaskById,
  36. sendV4Prompt,
  37. startNewV4Draft,
  38. switchV4Mode,
  39. waitForV4AssistantMessageContaining,
  40. waitForV4Pane,
  41. } from "#e2e/helpers/v4-conversation";
  42. const CASE_MARKER = "E2E_ASSISTANT_PREVIEW_CARDS";
  43. const CASE_RELATIVE_ROOT = "assistant-preview-e2e";
  44. const CASE_ROOT = join(DEFAULT_WORKSPACE, CASE_RELATIVE_ROOT);
  45. const OFFICE_FIXTURE_ROOT = fileURLToPath(
  46. new URL(
  47. "../../fixtures/fs/conversation-session/conversation-session-assistant-preview-cards/",
  48. import.meta.url,
  49. ),
  50. );
  51. const STREAM_URL = "http://localhost:41789/assistant-preview-stream";
  52. const SOURCE_HTML_RELATIVE_PATH = `${CASE_RELATIVE_ROOT}/本轮 输出/index 页面.html`;
  53. const SOURCE_MARKDOWN_RELATIVE_PATH = `${CASE_RELATIVE_ROOT}/本轮 输出/说明 文档.md`;
  54. const SOURCE_HTML_PATH = join(DEFAULT_WORKSPACE, SOURCE_HTML_RELATIVE_PATH);
  55. const REVEAL_SOURCE_HTML_RELATIVE_PATH = `${CASE_RELATIVE_ROOT}/预览 源码/app 页面.html`;
  56. const OFFICE_FILES = [
  57. { fixture: "sample.docx", name: "项目 简介.docx" },
  58. { fixture: "sample.xlsx", name: "年度 总结.xlsx" },
  59. { fixture: "sample.pptx", name: "产品 路线.pptx" },
  60. { fixture: "sample.pdf", name: "审计 报告.pdf" },
  61. ] as const;
  62. const MEDIA_FILES = ["生成 视频.mp4", "生成 音频.wav"] as const;
  63. // 与 getFileManagerLabel 按平台取文案一致;E2E 进程与 Electron 同机,process.platform 等价于 UA 判断。
  64. const FILE_MANAGER_LABEL =
  65. process.platform === "darwin"
  66. ? /^(Open in Finder|在 Finder 中打开)$/
  67. : process.platform === "win32"
  68. ? /^(Open in File Explorer|在资源管理器中打开)$/
  69. : /^(Open in File Manager|在文件管理器中打开)$/;
  70. const REVEAL_IN_FINDER_LABEL = /^(Open in Finder|在 Finder 中打开)$/;
  71. const SELECT_OPEN_APP_SELECTOR =
  72. 'button[aria-label="Choose app"], button[aria-label="选择打开方式"]';
  73. interface PreviewCardSnapshot {
  74. text: string;
  75. title: string;
  76. }
  77. let fixtureServer: Server | null = null;
  78. let fixtureRootUrl = "";
  79. describe("Assistant Preview Cards E2E", () => {
  80. before(async () => {
  81. fixtureServer = createFixtureServer();
  82. fixtureRootUrl = await listen(fixtureServer);
  83. });
  84. afterEach(async () => {
  85. await closeSidePanes();
  86. await rm(CASE_ROOT, { recursive: true, force: true });
  87. });
  88. after(async () => {
  89. await closeServer(fixtureServer);
  90. fixtureServer = null;
  91. await browser.electron.restoreAllMocks();
  92. await clearAppData();
  93. });
  94. it("APC01/APC04: completed localhost URL 去重并打开真实 Browser 页面", async () => {
  95. await prepareCase();
  96. const marker = `${CASE_MARKER}_LOCAL_URL`;
  97. await sendV4Prompt(
  98. `${marker}: reply with the same local preview URL more than once. E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`,
  99. );
  100. await waitForCompleted(`${marker}_DONE`);
  101. await waitForPreviewCards(["APC Local Preview"]);
  102. // APC01 同时验证整卡点击:localhost 网页卡片主体与主按钮触发同一 Browser 预览。
  103. await clickPreviewCardBody("APC Local Preview");
  104. await waitForBrowserSurface(fixtureRootUrl, "APC01_LOCAL_URL_PAGE");
  105. }).timeout(180_000);
  106. it("APC02: interrupted turn 在 URL 已到达后 Stop,卡片只在终态出现", async () => {
  107. await prepareCase();
  108. const marker = `${CASE_MARKER}_INTERRUPTED`;
  109. await sendV4Prompt(`${marker}: keep streaming after publishing ${STREAM_URL}.`);
  110. await waitForV4AssistantMessageContaining(`${marker}_EARLY`, 60_000);
  111. expect(await readPreviewCards()).toEqual([]);
  112. await clickV4Stop();
  113. await waitForV4Pane(
  114. (snapshot) => !snapshot.canStop && snapshot.timelineText.includes(`${marker}_EARLY`),
  115. "APC02 Stop 后 turn 没有进入 interrupted 终态",
  116. 60_000,
  117. );
  118. await waitForPreviewCards(["assistant-preview-stream"]);
  119. }).timeout(180_000);
  120. it("APC03: streaming 期间不显示卡片,complete 后显示", async () => {
  121. await prepareCase();
  122. const marker = `${CASE_MARKER}_STREAMING`;
  123. await sendV4Prompt(`${marker}: stream ${STREAM_URL} before the final marker.`);
  124. await waitForV4AssistantMessageContaining(`${marker}_EARLY`, 60_000);
  125. expect(await readPreviewCards()).toEqual([]);
  126. await waitForCompleted(`${marker}_DONE`);
  127. await waitForPreviewCards(["assistant-preview-stream"]);
  128. }).timeout(180_000);
  129. it("APC04: localhost 与本轮 HTML 同时出现时按现有业务规则抑制 HTML", async () => {
  130. await prepareCase({ yolo: true });
  131. const marker = `${CASE_MARKER}_LOCAL_SUPPRESSES_HTML`;
  132. await sendV4Prompt(
  133. `${marker}: create ${SOURCE_HTML_RELATIVE_PATH}, then mention it with E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}.`,
  134. );
  135. await waitForCompleted(`${marker}_DONE`);
  136. await waitForPreviewCards(["APC Local Only"]);
  137. await expectPreviewCardMissing(basename(SOURCE_HTML_RELATIVE_PATH));
  138. }).timeout(180_000);
  139. it("APC06/APC07: source gate、Office 自动打开 PPTX", async () => {
  140. await prepareCase();
  141. await materializeOfficeFixtures();
  142. await materializeStaleSourceFiles();
  143. const marker = `${CASE_MARKER}_OFFICE`;
  144. await sendV4Prompt(`${marker}_PPTX: report the prepared Office files and one missing PDF.`);
  145. // 失败原因:PPTX 自动打开只在本 renderer 观察到 running 边沿后武装(冷恢复直接落在
  146. // completedSuccess 不应自动打开)。fixture 整轮仅几十毫秒,running 与 completedSuccess
  147. // 会被合并到同一次渲染,门控没武装,Preview Pane 始终不出现。
  148. // fixture 延迟回复,这里先确认 UI 已渲染出运行态(可停止)再等完成,边沿才可观察。
  149. await waitForV4Pane(
  150. (snapshot) => snapshot.canStop,
  151. "Office PPTX 轮次没有进入可观察的 running 态",
  152. 30_000,
  153. );
  154. await waitForCompleted(`${marker}_PPTX_DONE`);
  155. const officeTitles = [...OFFICE_FILES].reverse().map((item) => item.name);
  156. await waitForPreviewCards(officeTitles);
  157. await expectPreviewCardMissing("旧 页面.html");
  158. await expectPreviewCardMissing("旧 说明.md");
  159. await expectPreviewCardMissing("不存在.pdf");
  160. await waitForPreviewRenderer("产品 路线.pptx", "pptx");
  161. for (const file of OFFICE_FILES) {
  162. await assertFileOpenApps(file.name);
  163. }
  164. }).timeout(240_000);
  165. it("APC14: unified file menu defaults, first three and More dispatch the selected application", async () => {
  166. await prepareCase();
  167. await materializeOfficeFixtures();
  168. const marker = `${CASE_MARKER}_OFFICE`;
  169. await sendV4Prompt(`${marker}_PPTX: report the prepared Office files and one missing PDF.`);
  170. await waitForCompleted(`${marker}_PPTX_DONE`);
  171. await waitForPreviewCards([...OFFICE_FILES].reverse().map((item) => item.name));
  172. await closeSidePanes();
  173. const filename = "产品 路线.pptx";
  174. const targetPath = await realpath(join(CASE_ROOT, "office", filename));
  175. const row = await browser.$(`[data-preview-card-title="${filename}"]`);
  176. // 原生候选依平台而变;固定边界使用明确 IPC fixture,不冒充系统枚举或实际启动。
  177. for (const count of [0, 1, 3, 10]) {
  178. const applications = Array.from({ length: count }, (_, index) => ({
  179. id: `apc-app-${index}`,
  180. name: `APC Application ${index}`,
  181. isDefault: index === count - 1,
  182. }));
  183. await installFileApplicationMenuProbe(targetPath, applications);
  184. try {
  185. await assertFileOpenApps(filename, applications);
  186. await row.click({ button: "right" });
  187. const menu = await browser.$('[data-slot="context-menu-content"][data-state="open"]');
  188. await menu.waitForDisplayed();
  189. // 修复原因:候选超过 3 个时 assertApplicationMenu 会打开 More 子菜单并按 Escape;
  190. // Radix 子菜单的 Escape 会关闭整棵菜单,之后再读主菜单项会命中已卸载的节点。
  191. // 主菜单标签必须在进入子菜单前读取。
  192. const labels = await menu.$$('[role="menuitem"]').map((item) => item.getText());
  193. expect(labels[0]).toMatch(/^(Preview|预览)$/);
  194. expect(labels.some((label) => /Open containing folder|打开所在目录/.test(label))).toBe(
  195. false,
  196. );
  197. // 卡片右键与 Open 下拉提供同一个定位项(右键行为由 APC15 覆盖)。
  198. expect(labels.filter((label) => FILE_MANAGER_LABEL.test(label))).toHaveLength(1);
  199. await assertApplicationMenu(menu, applications);
  200. await browser.keys("Escape");
  201. await assertRevealInFileManager(row, targetPath);
  202. // 点击真实预览动作后核对 renderer,而不是直接调用产品回调。
  203. await row.click({ button: "right" });
  204. await browser
  205. .$('[data-slot="context-menu-content"][data-state="open"] [role="menuitem"]')
  206. .click();
  207. await waitForPreviewRenderer(filename, "pptx");
  208. if (count > 3) {
  209. await row.$('button[aria-label="Choose app"], button[aria-label="选择打开方式"]').click();
  210. const dropdown = await browser.$(
  211. '[data-slot="dropdown-menu-content"][data-state="open"]',
  212. );
  213. await dropdown.waitForDisplayed();
  214. // 修复原因:下拉刚显示时候选仍在加载,约 8ms 就 moveTo 到 More,菜单随后按候选重排,
  215. // 单次 hover 丢失后 [data-file-application-list] 不再出现(死等 5s)。
  216. // 复用 assertApplicationMenu 的就绪条件,候选落定后再 hover。
  217. await waitForApplicationMenuReady(dropdown, applications);
  218. await dropdown.$(".file-application-more-trigger").moveTo();
  219. const list = await browser.$("[data-file-application-list]");
  220. await list.waitForDisplayed();
  221. const items = await list.$$('[role="menuitem"]');
  222. const last = items[(await items.length) - 1]!;
  223. await last.scrollIntoView();
  224. await last.click();
  225. await browser.waitUntil(async () => (await readFileApplicationMenuProbe()).length === 1, {
  226. timeout: 10_000,
  227. });
  228. const [call] = await readFileApplicationMenuProbe();
  229. expect(call?.applicationId).toBe("apc-app-8");
  230. // 修复原因:Windows 路径大小写不敏感,应用实际路径目录大小写可能与 realpath 不同,Windows 上按小写比较。
  231. expect(
  232. process.platform === "win32" ? call?.target.path.toLowerCase() : call?.target.path,
  233. ).toBe(process.platform === "win32" ? targetPath.toLowerCase() : targetPath);
  234. expect(call?.target.pathKind).toBe("file");
  235. }
  236. } finally {
  237. await browser.keys("Escape");
  238. await browser.keys("Escape");
  239. await restoreFileApplicationMenuProbe();
  240. }
  241. }
  242. }).timeout(240_000);
  243. it("APC15: macOS 文件卡「在 Finder 中打开」定位到所在目录,纯网址卡不提供该项", async function () {
  244. // 文案与定位通道按平台分叉(Finder / 资源管理器 / 文件管理器),本例只覆盖 macOS。
  245. if (process.platform !== "darwin") this.skip();
  246. await prepareCase();
  247. await materializeOfficeFixtures();
  248. const marker = `${CASE_MARKER}_REVEAL`;
  249. await sendV4Prompt(
  250. `${marker}: report the prepared DOCX and a local preview URL. E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`,
  251. );
  252. await waitForCompleted(`${marker}_DONE`);
  253. const filename = "项目 简介.docx";
  254. const linkTitle = "APC Reveal Link";
  255. await waitForPreviewCardSet([filename, linkTitle]);
  256. await closeSidePanes();
  257. const expectedFile = await realpath(join(CASE_ROOT, "office", filename));
  258. const row = await browser.$(`[data-preview-card-title="${filename}"]`);
  259. const linkRow = await browser.$(`[data-preview-card-title="${linkTitle}"]`);
  260. await installFileManagerRevealProbe();
  261. try {
  262. // 右键菜单:文件卡出现该项,点击后让 Finder 打开所在目录并选中该文件。
  263. await row.click({ button: "right" });
  264. await clickOpenMenuItem("context-menu", REVEAL_IN_FINDER_LABEL);
  265. await expectFinderRevealCalls([expectedFile]);
  266. // 「打开」下拉:同一项走同一条定位通道。
  267. await row.$(SELECT_OPEN_APP_SELECTOR).click();
  268. await clickOpenMenuItem("dropdown-menu", REVEAL_IN_FINDER_LABEL);
  269. await expectFinderRevealCalls([expectedFile, expectedFile]);
  270. // 纯网址卡没有本机文件可定位:右键与下拉都不出现该项,也不触发 IPC。
  271. await linkRow.click({ button: "right" });
  272. expect(await readOpenMenuLabels("context-menu")).not.toContainEqual(
  273. expect.stringMatching(REVEAL_IN_FINDER_LABEL),
  274. );
  275. await browser.keys("Escape");
  276. // 下拉必须真实存在,否则「没有该项」的断言会因为没打开菜单而空过。
  277. const linkDropdownTrigger = await linkRow.$(SELECT_OPEN_APP_SELECTOR);
  278. expect(await linkDropdownTrigger.isExisting()).toBe(true);
  279. await linkDropdownTrigger.click();
  280. expect(await readOpenMenuLabels("dropdown-menu")).not.toContainEqual(
  281. expect.stringMatching(REVEAL_IN_FINDER_LABEL),
  282. );
  283. await browser.keys("Escape");
  284. expect(await readFileManagerRevealCalls()).toHaveLength(2);
  285. } finally {
  286. await browser.keys("Escape");
  287. await restoreFileManagerRevealProbe();
  288. }
  289. }).timeout(180_000);
  290. it("APC15: macOS localhost 预览卡映射到本轮 HTML 时定位源文件目录,打开仍走原 URL", async function () {
  291. if (process.platform !== "darwin") this.skip();
  292. await prepareCase({ yolo: true });
  293. const marker = `${CASE_MARKER}_LOCAL_SOURCE`;
  294. // localhost 路径与本轮 Write 的工作区 HTML 一致,卡片才会带 sourcePath;URL 内不能有空白。
  295. const encodedSourcePath = REVEAL_SOURCE_HTML_RELATIVE_PATH.split("/")
  296. .map(encodeURIComponent)
  297. .join("/");
  298. const sourceUrl = `${new URL(fixtureRootUrl).origin}/${encodedSourcePath}`;
  299. await sendV4Prompt(
  300. `${marker}: create ${REVEAL_SOURCE_HTML_RELATIVE_PATH}, then share its local preview URL. E2E_BROWSER_FIXTURE_URL:${sourceUrl}`,
  301. );
  302. await waitForCompleted(`${marker}_DONE`);
  303. const title = basename(REVEAL_SOURCE_HTML_RELATIVE_PATH);
  304. await waitForPreviewCards([title]);
  305. await closeSidePanes();
  306. const expectedFile = await realpath(join(DEFAULT_WORKSPACE, REVEAL_SOURCE_HTML_RELATIVE_PATH));
  307. const row = await browser.$(`[data-preview-card-title="${title}"]`);
  308. await installFileManagerRevealProbe();
  309. try {
  310. // 卡片标题与 URL 兜底标题相同,卡片先于本轮 fileChanges 映射出现;sourcePath 到位后才有定位项。
  311. await browser.waitUntil(
  312. async () => {
  313. await row.click({ button: "right" });
  314. const labels = await readOpenMenuLabels("context-menu");
  315. if (labels.some((text) => REVEAL_IN_FINDER_LABEL.test(text))) return true;
  316. await browser.keys("Escape");
  317. return false;
  318. },
  319. { timeout: 15_000, interval: 500, timeoutMsg: "localhost 卡片没有出现定位源文件的菜单项" },
  320. );
  321. await clickOpenMenuItem("context-menu", REVEAL_IN_FINDER_LABEL);
  322. await expectFinderRevealCalls([expectedFile]);
  323. const dropdownTrigger = await row.$(SELECT_OPEN_APP_SELECTOR);
  324. expect(await dropdownTrigger.isExisting()).toBe(true);
  325. await dropdownTrigger.click();
  326. await clickOpenMenuItem("dropdown-menu", REVEAL_IN_FINDER_LABEL);
  327. await expectFinderRevealCalls([expectedFile, expectedFile]);
  328. } finally {
  329. await browser.keys("Escape");
  330. await restoreFileManagerRevealProbe();
  331. }
  332. // sourcePath 只用于定位:卡片打开仍把原 localhost URL 交给 Browser,而不是 file:// 源文件。
  333. await clickPreviewCardBody(title);
  334. await waitForBrowserSurface(sourceUrl, "APC01_LOCAL_URL_PAGE");
  335. }).timeout(180_000);
  336. it("APC15: macOS 正文文件链接右键「在 Finder 中打开」定位文件,目录链接直接打开目录", async function () {
  337. if (process.platform !== "darwin") this.skip();
  338. await prepareCase();
  339. await materializeOfficeFixtures();
  340. const marker = `${CASE_MARKER}_BODY_LINK_REVEAL`;
  341. await sendV4Prompt(`${marker}: link the prepared DOCX and its folder in the reply body.`);
  342. await waitForCompleted(`${marker}_DONE`);
  343. await closeSidePanes();
  344. const fileLinkLabel = "APC 正文文件链接";
  345. const directoryLinkLabel = "APC 正文目录链接";
  346. const fileLinkPath = await findBodyFileLinkPath(fileLinkLabel);
  347. const directoryLinkPath = await findBodyFileLinkPath(directoryLinkLabel);
  348. expect(await realpath(fileLinkPath)).toBe(
  349. await realpath(join(CASE_ROOT, "office", "项目 简介.docx")),
  350. );
  351. expect(await realpath(directoryLinkPath)).toBe(await realpath(join(CASE_ROOT, "office")));
  352. // 关联应用用固定 IPC fixture,菜单分组稳定;定位与打开目录两条 IPC 只记录,不拉起 Finder。
  353. const applications: FileApplicationInfo[] = [
  354. { id: "apc-body-app-0", name: "APC Body Application 0", isDefault: true },
  355. { id: "apc-body-app-1", name: "APC Body Application 1", isDefault: false },
  356. ];
  357. await installFileApplicationMenuProbe(fileLinkPath, applications);
  358. try {
  359. // 文件链接:定位项在应用分组之后、另存为之前,点击只发出一次 finder select-file。
  360. await browser.$(`button=${fileLinkLabel}`).click({ button: "right" });
  361. const order = await readBodyLinkMenuOrder(
  362. (current) => current.saveAs >= 0 && current.lastApplication >= 0 && !current.loading,
  363. );
  364. expect(order.revealCount).toBe(1);
  365. expect(order.reveal).toBeGreaterThan(order.lastApplication);
  366. expect(order.saveAs).toBe(order.reveal + 1);
  367. await clickOpenMenuItem("context-menu", REVEAL_IN_FINDER_LABEL);
  368. await browser.waitUntil(async () => (await readFileLocateProbe()).length > 0, {
  369. timeout: 10_000,
  370. timeoutMsg: "正文文件链接没有发出 Finder 定位请求",
  371. });
  372. // 稍等确认没有重复派发,也没有回退成打开目录或交给关联应用。
  373. await browser.pause(500);
  374. expect(await readFileLocateProbe()).toEqual([
  375. { editorId: "finder", path: fileLinkPath, pathKind: "file" },
  376. ]);
  377. expect(await readFileManagerRevealProbe()).toEqual([]);
  378. // 目录链接:同一项直接打开该目录,不走 select-file;目录没有另存为。
  379. await browser.$(`button=${directoryLinkLabel}`).click({ button: "right" });
  380. const directoryOrder = await readBodyLinkMenuOrder(
  381. (current) => current.reveal >= 0 && !current.loading,
  382. );
  383. expect(directoryOrder.revealCount).toBe(1);
  384. expect(directoryOrder.saveAs).toBe(-1);
  385. await clickOpenMenuItem("context-menu", REVEAL_IN_FINDER_LABEL);
  386. await browser.waitUntil(async () => (await readFileManagerRevealProbe()).length > 0, {
  387. timeout: 10_000,
  388. timeoutMsg: "正文目录链接没有发出打开目录请求",
  389. });
  390. await browser.pause(500);
  391. expect(await readFileManagerRevealProbe()).toEqual([directoryLinkPath]);
  392. expect(await readFileLocateProbe()).toHaveLength(1);
  393. expect(await readFileApplicationMenuProbe()).toEqual([]);
  394. } finally {
  395. await browser.keys("Escape");
  396. await restoreFileApplicationMenuProbe();
  397. }
  398. }).timeout(180_000);
  399. it("APC12: 独立音频消息打开原生 audio 播放器", async () => {
  400. await prepareCase();
  401. await materializeMediaFixtures();
  402. const marker = `${CASE_MARKER}_OFFICE_AUDIO`;
  403. await sendV4Prompt(`${marker}: report the prepared audio file only.`);
  404. await waitForCompleted(`${marker}_DONE`);
  405. await waitForPreviewCards(["生成 音频.wav"]);
  406. const logSnapshot = await snapshotDesktopRuntimeLogs();
  407. await clickPreviewCard("生成 音频.wav");
  408. await waitForPreviewRenderer("生成 音频.wav", "audio");
  409. await assertLocalMediaPreviewLogs(logSnapshot);
  410. }).timeout(180_000);
  411. it("APC12: 独立视频消息打开并保持 media 节点", async () => {
  412. await prepareCase();
  413. await materializeMediaFixtures();
  414. const marker = `${CASE_MARKER}_OFFICE_VIDEO`;
  415. await sendV4Prompt(`${marker}: report the prepared video file only.`);
  416. await waitForCompleted(`${marker}_DONE`);
  417. await waitForPreviewCards(["生成 视频.mp4"]);
  418. await assertFileOpenApps("生成 视频.mp4");
  419. const logSnapshot = await snapshotDesktopRuntimeLogs();
  420. await clickPreviewCard("生成 视频.mp4");
  421. await waitForPreviewRenderer("生成 视频.mp4", "video");
  422. const mediaUrl = await browser.execute(
  423. () => document.querySelector<HTMLVideoElement>("video[controls]")?.currentSrc ?? "",
  424. );
  425. expect(mediaUrl).not.toBe("");
  426. expect(new URL(mediaUrl).protocol).toBe("zcode-media:");
  427. await assertPreviewVideoSurvivesResizeAndFullscreen();
  428. await assertLocalMediaPreviewLogs(logSnapshot);
  429. }).timeout(180_000);
  430. it("APC08: 最多显示 10 张,并且前 15 个不足时不从第 16 个以后回填", async () => {
  431. await prepareCase();
  432. await materializeBoundFiles();
  433. const maxMarker = `${CASE_MARKER}_MAX_TEN`;
  434. await sendV4Prompt(`${maxMarker}: list the twelve prepared max-bound PDF paths in order.`);
  435. await waitForCompleted(`${maxMarker}_DONE`);
  436. await waitForPreviewCards(
  437. Array.from({ length: 10 }, (_, index) => `max-${String(12 - index).padStart(2, "0")}.pdf`),
  438. );
  439. await expectPreviewCardMissing("max-02.pdf");
  440. await expectPreviewCardMissing("max-01.pdf");
  441. await prepareCase();
  442. await materializeBoundFiles();
  443. const noFillMarker = `${CASE_MARKER}_NO_BACKFILL`;
  444. await sendV4Prompt(
  445. `${noFillMarker}: list all sixteen no-backfill PDF paths in ascending order.`,
  446. );
  447. await waitForCompleted(`${noFillMarker}_DONE`);
  448. await waitForPreviewCards(
  449. Array.from({ length: 9 }, (_, index) => `nofill-${String(16 - index).padStart(2, "0")}.pdf`),
  450. );
  451. await expectPreviewCardMissing("nofill-01.pdf");
  452. }).timeout(240_000);
  453. it("APC05/APC09/APC11: 当前轮 HTML/Markdown 逆序展示、打开,收起偏好在切换会话和 cold resume 后保留", async () => {
  454. await prepareCase({ yolo: true });
  455. const marker = `${CASE_MARKER}_SOURCE_AND_COLD`;
  456. await sendV4Prompt(
  457. `${marker}: create ${SOURCE_HTML_RELATIVE_PATH} and ${SOURCE_MARKDOWN_RELATIVE_PATH}, then report both.`,
  458. );
  459. await waitForCompleted(`${marker}_DONE`);
  460. const targetSession = await waitForBoundSession(marker);
  461. const expectedTitles = [
  462. basename(SOURCE_MARKDOWN_RELATIVE_PATH),
  463. basename(SOURCE_HTML_RELATIVE_PATH),
  464. ];
  465. await waitForPreviewCards(expectedTitles);
  466. await assertSourcePreviewTargets();
  467. await assertLocalHtmlExternalOpen();
  468. await clickPreviewCard(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  469. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  470. await waitForSidePaneExpanded(true);
  471. await clickSidePaneToggle();
  472. await waitForSidePaneExpanded(false);
  473. await startNewV4Draft();
  474. const parkingMarker = `${CASE_MARKER}_PARKING`;
  475. await sendV4Prompt(`${parkingMarker}: complete a parking task before cold resume.`);
  476. await waitForCompleted(`${parkingMarker}_DONE`);
  477. const parkingSession = await waitForBoundSession(parkingMarker);
  478. expect(parkingSession).not.toBe(targetSession);
  479. await selectV4TaskById(targetSession, 60_000);
  480. await waitForV4Pane(
  481. (snapshot) =>
  482. snapshot.sessionId === targetSession && snapshot.timelineText.includes(`${marker}_DONE`),
  483. `APC11 切回目标 session ${targetSession} 后没有恢复对话`,
  484. 90_000,
  485. );
  486. await waitForPreviewCards(expectedTitles, 90_000);
  487. await waitForSidePaneExpanded(false);
  488. await clickPreviewCard(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  489. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  490. await waitForSidePaneExpanded(true);
  491. await closeSidePanes();
  492. await restartIntoWorkspacePreservingProfile();
  493. await selectV4TaskById(targetSession, 60_000);
  494. await waitForV4Pane(
  495. (snapshot) =>
  496. snapshot.sessionId === targetSession && snapshot.timelineText.includes(`${marker}_DONE`),
  497. `APC09 cold resume 后没有恢复目标 session ${targetSession}`,
  498. 90_000,
  499. );
  500. await waitForPreviewCards(expectedTitles, 90_000);
  501. await assertSourcePreviewTargets();
  502. }).timeout(360_000);
  503. });
  504. async function prepareCase(options: { yolo?: boolean } = {}) {
  505. await prepareV4ConversationE2E();
  506. if (options.yolo) {
  507. await switchV4Mode("yolo");
  508. }
  509. await rm(CASE_ROOT, { recursive: true, force: true });
  510. await mkdir(CASE_ROOT, { recursive: true });
  511. }
  512. async function waitForCompleted(marker: string) {
  513. await waitForV4AssistantMessageContaining(marker, 90_000);
  514. await waitForV4Pane(
  515. (snapshot) => !snapshot.canStop && snapshot.timelineText.includes(marker),
  516. `Assistant Preview Cards turn 没有完成: ${marker}`,
  517. 90_000,
  518. );
  519. }
  520. async function waitForBoundSession(marker: string): Promise<string> {
  521. const snapshot = await waitForV4Pane(
  522. (current) =>
  523. current.sessionId !== null &&
  524. current.sessionId !== "draft" &&
  525. !current.canStop &&
  526. current.timelineText.includes(marker),
  527. `Assistant Preview Cards 缺少已绑定 session: ${marker}`,
  528. 60_000,
  529. );
  530. if (!snapshot.sessionId || snapshot.sessionId === "draft") {
  531. throw new Error(`Assistant Preview Cards 得到无效 sessionId: ${snapshot.sessionId ?? "null"}`);
  532. }
  533. return snapshot.sessionId;
  534. }
  535. async function readPreviewCards(
  536. expectedTitles: readonly string[] = [],
  537. ): Promise<PreviewCardSnapshot[]> {
  538. return browser.execute(
  539. (titles) => {
  540. const openLabels = new Set(["Open", "打开", "Preview", "预览"]);
  541. return Array.from(
  542. document.querySelectorAll<HTMLElement>('[data-zcode-stream-animate="true"]'),
  543. )
  544. .filter((row) =>
  545. Array.from(row.querySelectorAll<HTMLButtonElement>("button")).some((button) =>
  546. openLabels.has((button.textContent ?? "").trim()),
  547. ),
  548. )
  549. .map((row) => {
  550. const text = row.innerText.replace(/\u00a0/g, " ").trim();
  551. const title = titles.find((candidate) => text.includes(candidate)) ?? "";
  552. return { text, title };
  553. });
  554. },
  555. [...expectedTitles],
  556. );
  557. }
  558. async function waitForPreviewCards(expectedTitles: readonly string[], timeout = 60_000) {
  559. let latest: PreviewCardSnapshot[] = [];
  560. await browser.waitUntil(
  561. async () => {
  562. latest = await readPreviewCards(expectedTitles);
  563. return (
  564. latest.length === expectedTitles.length &&
  565. latest.every((card, index) => card.title === expectedTitles[index])
  566. );
  567. },
  568. {
  569. timeout,
  570. timeoutMsg: `预览卡片没有按预期收敛: expected=${JSON.stringify(expectedTitles)} latest=${JSON.stringify(latest)}`,
  571. },
  572. );
  573. }
  574. async function expectPreviewCardMissing(title: string) {
  575. const cards = await readPreviewCards([title]);
  576. expect(cards.some((card) => card.title === title)).toBe(false);
  577. }
  578. async function clickPreviewCard(title: string) {
  579. const result = await browser.execute((expectedTitle) => {
  580. const openLabels = new Set(["Open", "打开", "Preview", "预览"]);
  581. const row = Array.from(
  582. document.querySelectorAll<HTMLElement>('[data-zcode-stream-animate="true"]'),
  583. ).find((candidate) => candidate.innerText.includes(expectedTitle));
  584. const button = Array.from(row?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  585. (candidate) => openLabels.has((candidate.textContent ?? "").trim()),
  586. );
  587. button?.click();
  588. return { clicked: Boolean(button), disabled: Boolean(button?.disabled) };
  589. }, title);
  590. expect(result.clicked).toBe(true);
  591. expect(result.disabled).toBe(false);
  592. }
  593. // 卡片主体整卡可点:点击标题区域(铺满卡片的透明按钮)与主按钮执行同一预览动作。
  594. async function clickPreviewCardBody(title: string) {
  595. const result = await browser.execute((expectedTitle) => {
  596. const row = document.querySelector<HTMLElement>(`[data-preview-card-title="${expectedTitle}"]`);
  597. const overlay = Array.from(row?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  598. (button) => (button.getAttribute("aria-label") ?? "").endsWith(expectedTitle),
  599. );
  600. overlay?.click();
  601. return { clicked: Boolean(overlay), disabled: Boolean(overlay?.disabled) };
  602. }, title);
  603. expect(result.clicked).toBe(true);
  604. expect(result.disabled).toBe(false);
  605. }
  606. /** 候选列表按绑定目标加载完成(直接项与预期一致、不再 Loading)后,返回排好序的候选。 */
  607. async function waitForApplicationMenuReady(
  608. menu: ChainablePromiseElement,
  609. applications: FileApplicationInfo[],
  610. ) {
  611. const unique = [...new Map(applications.map((app) => [app.id, app])).values()];
  612. const ordered = [
  613. ...unique.filter((app) => app.isDefault),
  614. ...unique.filter((app) => !app.isDefault),
  615. ];
  616. await browser.waitUntil(
  617. async () => {
  618. const ids = await menu
  619. .$$("[data-file-application-direct]")
  620. .map((item) => item.getAttribute("data-file-application-direct"));
  621. const text = await menu.getText();
  622. return (
  623. JSON.stringify(ids) === JSON.stringify(ordered.slice(0, 3).map((app) => app.id)) &&
  624. !/^(Loading|加载中)[….]*$/m.test(text)
  625. );
  626. },
  627. { timeout: 10_000, timeoutMsg: "File applications did not match the bound target" },
  628. );
  629. return ordered;
  630. }
  631. async function assertApplicationMenu(
  632. menu: ChainablePromiseElement,
  633. applications: FileApplicationInfo[],
  634. ) {
  635. const ordered = await waitForApplicationMenuReady(menu, applications);
  636. const direct = await menu.$$("[data-file-application-direct]");
  637. for (let index = 0; index < (await direct.length); index++) {
  638. const label = await direct[index]!.getText();
  639. expect(label).toContain(ordered[index]!.name);
  640. if (ordered[index]!.isDefault) expect(label).toMatch(/Open in|在.*中打开/);
  641. expect(
  642. await direct[index]!.$(
  643. '[data-slot="file-application-icon"], [data-slot="file-application-icon-fallback"]',
  644. ).isExisting(),
  645. ).toBe(true);
  646. }
  647. const text = await menu.getText();
  648. expect(text).toMatch(/Save as|另存为/i);
  649. expect(text).toMatch(/Copy absolute path|复制绝对路径/);
  650. if (ordered.length === 0) expect(text).toMatch(/Open with default app|使用默认应用打开/);
  651. const more = await menu.$(".file-application-more-trigger");
  652. expect(await more.isExisting()).toBe(ordered.length > 3);
  653. if (ordered.length > 3) {
  654. await more.moveTo();
  655. const list = await browser.$("[data-file-application-list]");
  656. await list.waitForDisplayed();
  657. const labels = await list.$$('[role="menuitem"]').map((item) => item.getText());
  658. expect(labels).toEqual(ordered.slice(3).map((app) => app.name));
  659. if (ordered.length > 9) {
  660. const dimensions = await list.getSize();
  661. expect(dimensions.height).toBeLessThanOrEqual(179);
  662. }
  663. await browser.keys("Escape");
  664. }
  665. }
  666. /**
  667. * 本地工作区 Open 下拉:定位项在应用分组之后、另存为之前。
  668. * macOS / Windows 点击后只发出一次 finder / explorer 定位(打开所在目录并选中该文件);
  669. * 其他平台没有系统定位能力,只打开文件所在目录一次。
  670. */
  671. async function assertRevealInFileManager(row: ChainablePromiseElement, targetPath: string) {
  672. await row.$('button[aria-label="Choose app"], button[aria-label="选择打开方式"]').click();
  673. const menu = await browser.$('[data-slot="dropdown-menu-content"][data-state="open"]');
  674. await menu.waitForDisplayed();
  675. await browser.waitUntil(async () => !/^(Loading|加载中)[….]*$/m.test(await menu.getText()), {
  676. timeout: 10_000,
  677. timeoutMsg: "File applications did not finish loading",
  678. });
  679. const order = await browser.execute((labelSource) => {
  680. const content = document.querySelector(
  681. '[data-slot="dropdown-menu-content"][data-state="open"]',
  682. );
  683. const items = Array.from(content?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? []);
  684. const label = new RegExp(labelSource);
  685. const index = (predicate: (item: HTMLElement) => boolean) => items.findIndex(predicate);
  686. const appIndexes = items
  687. .map((item, position) =>
  688. item.matches("[data-file-application-direct], .file-application-more-trigger") ||
  689. /Open with default app|使用默认应用打开/.test(item.textContent ?? "")
  690. ? position
  691. : -1,
  692. )
  693. .filter((position) => position >= 0);
  694. return {
  695. lastApplication: appIndexes.at(-1) ?? -1,
  696. reveal: index((item) => label.test(item.textContent?.trim() ?? "")),
  697. revealCount: items.filter((item) => label.test(item.textContent?.trim() ?? "")).length,
  698. saveAs: index((item) => /^(Save as|另存为)/i.test(item.textContent?.trim() ?? "")),
  699. };
  700. }, FILE_MANAGER_LABEL.source);
  701. expect(order.revealCount).toBe(1);
  702. expect(order.lastApplication).toBeGreaterThanOrEqual(0);
  703. expect(order.reveal).toBeGreaterThan(order.lastApplication);
  704. expect(order.saveAs).toBe(order.reveal + 1);
  705. const reveal = (await menu.$$('[role="menuitem"]'))[order.reveal]!;
  706. expect(await reveal.getText()).toMatch(FILE_MANAGER_LABEL);
  707. await reveal.click();
  708. const dispatched = async () =>
  709. (await readFileManagerRevealProbe()).length + (await readFileLocateProbe()).length;
  710. await browser.waitUntil(async () => (await dispatched()) > 0, {
  711. timeout: 10_000,
  712. timeoutMsg: "Open in file manager was not dispatched",
  713. });
  714. // 稍等确认没有重复派发,也没有把文件交给系统默认应用或回退成第二次打开目录。
  715. await browser.pause(500);
  716. const locatorId =
  717. process.platform === "darwin" ? "finder" : process.platform === "win32" ? "explorer" : null;
  718. if (locatorId) {
  719. // 修复原因:Windows 路径大小写不敏感,realpath 返回的目录大小写(Code)可能与应用实际使用的(code)不同;
  720. // Windows 上按小写比较路径,其他平台保持精确比较。
  721. const fold = (value: string) => (process.platform === "win32" ? value.toLowerCase() : value);
  722. expect(
  723. (await readFileLocateProbe()).map((call) => ({ ...call, path: fold(call.path) })),
  724. ).toEqual([{ editorId: locatorId, path: fold(targetPath), pathKind: "file" }]);
  725. expect(await readFileManagerRevealProbe()).toEqual([]);
  726. } else {
  727. expect(await readFileLocateProbe()).toEqual([]);
  728. expect(await readFileManagerRevealProbe()).toEqual([dirname(targetPath)]);
  729. }
  730. expect(await readFileApplicationMenuProbe()).toEqual([]);
  731. }
  732. async function assertFileOpenApps(filename: string, fixture?: FileApplicationInfo[]) {
  733. // Office 夹具位于 office/,不能按 CASE_ROOT 根目录查找;必须查询卡片对应的同一个真实文件。
  734. const filePath = await realpath(
  735. join(
  736. CASE_ROOT,
  737. OFFICE_FILES.some((file) => file.name === filename) ? "office" : "media",
  738. filename,
  739. ),
  740. );
  741. const expected =
  742. fixture ??
  743. (await browser.execute(async (filePath) => {
  744. const platform = (
  745. window as unknown as Window & {
  746. zcode: {
  747. getFileApplications(target: {
  748. path: string;
  749. pathKind: "file";
  750. }): Promise<FileApplicationInfo[]>;
  751. };
  752. }
  753. ).zcode;
  754. return platform.getFileApplications({ path: filePath, pathKind: "file" });
  755. }, filePath));
  756. const row = await browser.$(`[data-preview-card-title="${filename}"]`);
  757. await row.$('button[aria-label="Choose app"], button[aria-label="选择打开方式"]').click();
  758. const menu = await browser.$('[data-slot="dropdown-menu-content"][data-state="open"]');
  759. await menu.waitForDisplayed();
  760. try {
  761. // 修复原因:候选超过 3 个时 assertApplicationMenu 会打开 More 子菜单并按 Escape,Radix 子菜单的
  762. // Escape 会关闭整棵菜单,之后 menu.getText() 命中已卸载节点(本机应用多于 CI 时必现)。
  763. // 须先等应用列表加载完,再在进入子菜单前读取主菜单文本。
  764. await browser.waitUntil(async () => !/^(Loading|加载中)[….]*$/m.test(await menu.getText()), {
  765. timeout: 10_000,
  766. timeoutMsg: "File application menu stayed in loading state",
  767. });
  768. const menuText = await menu.getText();
  769. await assertApplicationMenu(menu, expected);
  770. expect(menuText).toMatch(/Copy relative path|复制相对路径/);
  771. } finally {
  772. await browser.keys("Escape");
  773. }
  774. }
  775. async function assertLocalHtmlExternalOpen() {
  776. const openPath = await browser.electron.mock("shell", "openPath");
  777. await openPath.mockResolvedValue("");
  778. try {
  779. const expectedTitle = basename(SOURCE_HTML_RELATIVE_PATH);
  780. const rows = await browser.$$('[data-zcode-stream-animate="true"]');
  781. const row = (
  782. await rows.map(async (candidate) => ({
  783. candidate,
  784. text: await candidate.getText(),
  785. }))
  786. ).find(({ text }) => text.includes(expectedTitle))?.candidate;
  787. expect(row).toBeDefined();
  788. const trigger = await row?.$(
  789. 'button[aria-label="Choose app"], button[aria-label="选择打开方式"]',
  790. );
  791. expect(trigger).toBeDefined();
  792. await trigger?.click();
  793. await browser.waitUntil(
  794. async () => {
  795. const labels = new Set(["Open in browser", "在浏览器中打开"]);
  796. const items = await browser.$$('[role="menuitem"]');
  797. const item = (
  798. await items.map(async (candidate) => ({
  799. candidate,
  800. text: await candidate.getText(),
  801. }))
  802. ).find(({ text }) => labels.has(text.trim()))?.candidate;
  803. if (!item) return false;
  804. await item.click();
  805. return true;
  806. },
  807. { timeout: 10_000, timeoutMsg: "本地 HTML 卡片没有显示外部浏览器入口" },
  808. );
  809. await browser.waitUntil(
  810. async () => {
  811. try {
  812. await expect(openPath).toHaveBeenCalledWith(await realpath(SOURCE_HTML_PATH));
  813. return true;
  814. } catch {
  815. return false;
  816. }
  817. },
  818. { timeout: 10_000, timeoutMsg: "本地 HTML 没有通过 shell.openPath 打开" },
  819. );
  820. } finally {
  821. await browser.electron.restoreAllMocks();
  822. }
  823. }
  824. async function clickSidePaneToggle() {
  825. const clicked = await browser.execute(() => {
  826. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  827. (candidate) =>
  828. ["收起侧边面板", "Collapse side pane", "展开侧边面板", "Expand side pane"].includes(
  829. candidate.getAttribute("aria-label") ?? "",
  830. ),
  831. );
  832. button?.click();
  833. return Boolean(button);
  834. });
  835. expect(clicked).toBe(true);
  836. }
  837. async function waitForSidePaneExpanded(expectedExpanded: boolean) {
  838. let latestLabel = "";
  839. await browser.waitUntil(
  840. async () => {
  841. latestLabel = await browser.execute(() => {
  842. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  843. (candidate) =>
  844. ["收起侧边面板", "Collapse side pane", "展开侧边面板", "Expand side pane"].includes(
  845. candidate.getAttribute("aria-label") ?? "",
  846. ),
  847. );
  848. return button?.getAttribute("aria-label") ?? "";
  849. });
  850. const isExpanded = ["收起侧边面板", "Collapse side pane"].includes(latestLabel);
  851. return isExpanded === expectedExpanded;
  852. },
  853. {
  854. timeout: 15_000,
  855. timeoutMsg: `side pane 展开状态不符合预期: expected=${expectedExpanded}, label=${latestLabel}`,
  856. },
  857. );
  858. }
  859. async function waitForBrowserSurface(expectedUrl: string, bodyMarker: string) {
  860. let latest = { address: "", webContentsId: 0 };
  861. await browser.waitUntil(
  862. async () => {
  863. latest = await browser.execute(
  864. (addressTestId, webviewTestId) => {
  865. const address = document.querySelector<HTMLInputElement>(
  866. `[data-testid="${addressTestId}"]`,
  867. );
  868. const webview = document.querySelector<HTMLElement>(`[data-testid="${webviewTestId}"]`) as
  869. | (HTMLElement & { getWebContentsId?: () => number })
  870. | null;
  871. return {
  872. address: address?.value ?? "",
  873. webContentsId: webview?.getWebContentsId?.() ?? 0,
  874. };
  875. },
  876. TID_BROWSER_ADDRESS_INPUT,
  877. TID_BROWSER_WEBVIEW,
  878. );
  879. return latest.webContentsId > 0 && new URL(latest.address).href === new URL(expectedUrl).href;
  880. },
  881. {
  882. timeout: 60_000,
  883. timeoutMsg: `Browser Pane 没有打开目标 URL: ${JSON.stringify(latest)}`,
  884. },
  885. );
  886. let latestBody = "";
  887. await browser.waitUntil(
  888. async () => {
  889. latestBody = await browser.electron.execute(async (electron, webContentsId) => {
  890. const contents = electron.webContents.fromId(webContentsId);
  891. if (!contents || contents.isDestroyed()) return "";
  892. return contents.executeJavaScript("document.body?.innerText ?? ''");
  893. }, latest.webContentsId);
  894. return latestBody.includes(bodyMarker);
  895. },
  896. {
  897. timeout: 60_000,
  898. timeoutMsg: `Browser webview 没有加载页面 marker ${bodyMarker}: ${latestBody}`,
  899. },
  900. );
  901. }
  902. async function waitForPreviewRenderer(
  903. filename: string,
  904. renderer: "docx" | "excel" | "pptx" | "pdf" | "markdown" | "audio" | "video",
  905. ) {
  906. let latest = { hasError: false, header: "", ready: false, text: "" };
  907. await browser.waitUntil(
  908. async () => {
  909. latest = await browser.execute(
  910. (previewTestId, expectedFilename, expectedRenderer) => {
  911. const pane = document.querySelector<HTMLElement>(`[data-testid="${previewTestId}"]`);
  912. const text = (pane?.innerText ?? "").replace(/\u00a0/g, " ");
  913. const hasError = Boolean(pane?.querySelector('[role="alert"]'));
  914. let ready = false;
  915. if (expectedRenderer === "docx" || expectedRenderer === "excel") {
  916. ready = Boolean(
  917. pane?.querySelector(`[data-office-preview-kind="${expectedRenderer}"]`),
  918. );
  919. } else if (expectedRenderer === "pptx") {
  920. ready = Boolean(pane?.querySelector("aside[aria-label] button[aria-label]"));
  921. } else if (expectedRenderer === "pdf") {
  922. ready = Boolean(pane?.querySelector(".react-pdf__Document .react-pdf__Page"));
  923. } else if (expectedRenderer === "audio") {
  924. ready = Boolean(pane?.querySelector("audio[controls]"));
  925. } else if (expectedRenderer === "video") {
  926. ready = Boolean(pane?.querySelector("video[controls][playsinline]"));
  927. } else {
  928. ready = text.includes("APC05 Markdown renderer marker");
  929. }
  930. return {
  931. hasError,
  932. // 文件管理器把预览标题 portal 到共同头部;不能在预览正文里找文件名。
  933. header:
  934. pane?.closest("[data-file-manager-pane]")?.firstElementChild?.textContent ??
  935. text.split("\n")[0] ??
  936. "",
  937. ready,
  938. text,
  939. };
  940. },
  941. TID_PREVIEW_PANE,
  942. filename,
  943. renderer,
  944. );
  945. return !latest.hasError && latest.header.includes(filename) && latest.ready;
  946. },
  947. {
  948. timeout: 90_000,
  949. timeoutMsg: `Preview Pane renderer 没有就绪: ${filename}/${renderer}; latest=${JSON.stringify(latest)}`,
  950. },
  951. );
  952. }
  953. async function assertPreviewVideoSurvivesResizeAndFullscreen() {
  954. const videoReady = await browser.execute(() => {
  955. const video = document.querySelector<HTMLVideoElement>("video[controls][playsinline]");
  956. if (!video) return false;
  957. const probeWindow = window as Window & { __zcodePreviewVideo?: HTMLVideoElement };
  958. probeWindow.__zcodePreviewVideo = video;
  959. window.dispatchEvent(new Event("resize"));
  960. return true;
  961. });
  962. expect(videoReady).toBe(true);
  963. // resize settling 的 state update 应该已经完成;媒体节点不能被替换或卸载。
  964. await browser.pause(80);
  965. const sameVideoAfterResize = await browser.execute(() => {
  966. const probeWindow = window as Window & { __zcodePreviewVideo?: HTMLVideoElement };
  967. return (
  968. document.querySelector<HTMLVideoElement>("video[controls][playsinline]") ===
  969. probeWindow.__zcodePreviewVideo
  970. );
  971. });
  972. expect(sameVideoAfterResize).toBe(true);
  973. const fullscreenResult = await browser.executeAsync((done) => {
  974. const video = document.querySelector<HTMLVideoElement>("video[controls][playsinline]");
  975. if (!video?.requestFullscreen) {
  976. done("unsupported");
  977. return;
  978. }
  979. const finish = () => {
  980. document.removeEventListener("fullscreenchange", finish);
  981. done(document.fullscreenElement === video ? "entered" : "not-entered");
  982. };
  983. document.addEventListener("fullscreenchange", finish, { once: true });
  984. void video.requestFullscreen().catch(() => {
  985. document.removeEventListener("fullscreenchange", finish);
  986. done("unsupported");
  987. });
  988. });
  989. if (fullscreenResult === "entered") {
  990. await browser.pause(500);
  991. // 修复原因:旧断言把"节点未替换"和"仍在全屏"合成一个布尔值。Windows CI runner 运行在无显示设备的
  992. // session 0(1024×768),本地 1920×1080 同一步骤节点与全屏均保持;CI 只报 false,无法区分是节点被
  993. // 重新挂载还是环境退出了全屏。合同是保持 media 节点:节点必须不变;仍在全屏时全屏元素必须是它。
  994. // 断言携带现场,便于再次失败时直接定位。
  995. const fullscreenState = await browser.execute(() => {
  996. const probeWindow = window as Window & { __zcodePreviewVideo?: HTMLVideoElement };
  997. const video = document.querySelector<HTMLVideoElement>("video[controls][playsinline]");
  998. return {
  999. sameVideo: video === probeWindow.__zcodePreviewVideo,
  1000. oldVideoConnected: probeWindow.__zcodePreviewVideo?.isConnected ?? false,
  1001. fullscreenElement: document.fullscreenElement?.tagName ?? null,
  1002. fullscreenIsVideo: document.fullscreenElement === video,
  1003. viewport: [window.innerWidth, window.innerHeight],
  1004. screen: [screen.width, screen.height],
  1005. };
  1006. });
  1007. expect({ sameVideo: fullscreenState.sameVideo, state: fullscreenState }).toMatchObject({
  1008. sameVideo: true,
  1009. });
  1010. if (fullscreenState.fullscreenElement !== null) {
  1011. expect(fullscreenState).toMatchObject({ fullscreenIsVideo: true });
  1012. }
  1013. await browser.execute(() => {
  1014. if (document.fullscreenElement) void document.exitFullscreen().catch(() => undefined);
  1015. });
  1016. }
  1017. }
  1018. async function assertSourcePreviewTargets() {
  1019. // 整卡点击(标题区域透明按钮)与主按钮路径先后各验证一次,防止整卡可点回归退化为仅按钮可点。
  1020. await clickPreviewCardBody(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  1021. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  1022. await closePreviewPane();
  1023. await clickPreviewCard(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  1024. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  1025. await closePreviewPane();
  1026. await clickPreviewCard(basename(SOURCE_HTML_RELATIVE_PATH));
  1027. await waitForBrowserSurface(new URL(`file://${SOURCE_HTML_PATH}`).href, "APC05_HTML_PAGE");
  1028. await closeSidePanes();
  1029. }
  1030. async function materializeOfficeFixtures() {
  1031. const officeRoot = join(CASE_ROOT, "office");
  1032. await mkdir(officeRoot, { recursive: true });
  1033. await Promise.all(
  1034. OFFICE_FILES.map((item) =>
  1035. copyFile(join(OFFICE_FIXTURE_ROOT, item.fixture), join(officeRoot, item.name)),
  1036. ),
  1037. );
  1038. }
  1039. async function materializeMediaFixtures() {
  1040. const mediaRoot = join(CASE_ROOT, "media");
  1041. await mkdir(mediaRoot, { recursive: true });
  1042. const videoFixture = await readFile(
  1043. new URL("../../fixtures/media/sample-video.mp4", import.meta.url),
  1044. );
  1045. const largeVideo = Buffer.concat([
  1046. videoFixture,
  1047. Buffer.alloc(Math.max(0, 8 * 1024 * 1024 + 1 - videoFixture.length)),
  1048. ]);
  1049. const wav = Buffer.alloc(45);
  1050. wav.write("RIFF", 0, "ascii");
  1051. wav.writeUInt32LE(37, 4);
  1052. wav.write("WAVEfmt ", 8, "ascii");
  1053. wav.writeUInt32LE(16, 16);
  1054. wav.writeUInt16LE(1, 20);
  1055. wav.writeUInt16LE(1, 22);
  1056. wav.writeUInt32LE(8_000, 24);
  1057. wav.writeUInt32LE(8_000, 28);
  1058. wav.writeUInt16LE(1, 32);
  1059. wav.writeUInt16LE(8, 34);
  1060. wav.write("data", 36, "ascii");
  1061. wav.writeUInt32LE(1, 40);
  1062. wav[44] = 128;
  1063. await Promise.all([
  1064. writeFile(join(mediaRoot, "生成 视频.mp4"), largeVideo),
  1065. writeFile(join(mediaRoot, "生成 音频.wav"), wav),
  1066. ]);
  1067. expect((await stat(join(mediaRoot, "生成 视频.mp4"))).size).toBeGreaterThan(8 * 1024 * 1024);
  1068. }
  1069. async function materializeStaleSourceFiles() {
  1070. const staleRoot = join(CASE_ROOT, "stale");
  1071. await mkdir(staleRoot, { recursive: true });
  1072. await Promise.all([
  1073. writeFile(join(staleRoot, "旧 页面.html"), "<p>stale html</p>", "utf8"),
  1074. writeFile(join(staleRoot, "旧 说明.md"), "stale markdown", "utf8"),
  1075. ]);
  1076. }
  1077. async function assertLocalMediaPreviewLogs(snapshot: Map<string, number>): Promise<void> {
  1078. const runtimeLogDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR?.trim();
  1079. if (!runtimeLogDir) {
  1080. throw new Error("当前 E2E worker 没有配置 desktop runtime log 目录");
  1081. }
  1082. let desktopLogs = "";
  1083. await browser.waitUntil(
  1084. async () => {
  1085. desktopLogs = await readDesktopRuntimeLogsSince(runtimeLogDir, snapshot);
  1086. return (
  1087. desktopLogs.includes("[rpc:call] media-preview.prepare OK") &&
  1088. desktopLogs.includes("local media preview path authorization OK")
  1089. );
  1090. },
  1091. {
  1092. timeout: 30_000,
  1093. interval: 250,
  1094. timeoutMsg: `本地媒体预览日志没有完成: ${desktopLogs}`,
  1095. },
  1096. );
  1097. expect(desktopLogs).not.toContain("[rpc:call] file.readMediaPreview");
  1098. }
  1099. async function snapshotDesktopRuntimeLogs(): Promise<Map<string, number>> {
  1100. const runtimeLogDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR?.trim();
  1101. if (!runtimeLogDir) {
  1102. throw new Error("当前 E2E worker 没有配置 desktop runtime log 目录");
  1103. }
  1104. const entries = await readdir(runtimeLogDir, { withFileTypes: true }).catch(() => []);
  1105. const snapshot = new Map<string, number>();
  1106. await Promise.all(
  1107. entries
  1108. .filter((entry) => entry.isFile() && entry.name.endsWith(".log"))
  1109. .map(async (entry) => {
  1110. snapshot.set(entry.name, (await stat(join(runtimeLogDir, entry.name))).size);
  1111. }),
  1112. );
  1113. return snapshot;
  1114. }
  1115. async function readDesktopRuntimeLogsSince(
  1116. runtimeLogDir: string,
  1117. snapshot: Map<string, number>,
  1118. ): Promise<string> {
  1119. const entries = await readdir(runtimeLogDir, { withFileTypes: true }).catch(() => []);
  1120. const logFiles = entries
  1121. .filter((entry) => entry.isFile() && entry.name.endsWith(".log"))
  1122. .map((entry) => entry.name)
  1123. .sort();
  1124. const contents = await Promise.all(
  1125. logFiles.map(async (fileName) => {
  1126. const content = await readFile(join(runtimeLogDir, fileName));
  1127. const offset = Math.min(snapshot.get(fileName) ?? 0, content.byteLength);
  1128. return content.subarray(offset).toString("utf8");
  1129. }),
  1130. );
  1131. return contents.join("\n");
  1132. }
  1133. async function materializeBoundFiles() {
  1134. const boundsRoot = join(CASE_ROOT, "bounds");
  1135. await mkdir(boundsRoot, { recursive: true });
  1136. await Promise.all([
  1137. ...Array.from({ length: 12 }, (_, index) =>
  1138. writeFile(
  1139. join(boundsRoot, `max-${String(index + 1).padStart(2, "0")}.pdf`),
  1140. "exists",
  1141. "utf8",
  1142. ),
  1143. ),
  1144. writeFile(join(boundsRoot, "nofill-01.pdf"), "excluded existing candidate", "utf8"),
  1145. ...Array.from({ length: 9 }, (_, index) =>
  1146. writeFile(
  1147. join(boundsRoot, `nofill-${String(index + 8).padStart(2, "0")}.pdf`),
  1148. "exists",
  1149. "utf8",
  1150. ),
  1151. ),
  1152. ]);
  1153. }
  1154. async function closePreviewPane() {
  1155. // Bug 根因:PreviewPane 自身没有关闭按钮,关闭动作属于外层 side-pane tab。
  1156. // 必须关闭当前激活 tab 并等待旧 pane 卸载,否则下一次点击卡片仍会看到旧 renderer。
  1157. const closed = await browser.execute(() => {
  1158. const activeTab = document.querySelector<HTMLElement>("[data-side-pane-tab-id][data-active]");
  1159. const closeButton = activeTab?.querySelector<HTMLButtonElement>("button");
  1160. closeButton?.click();
  1161. return Boolean(closeButton);
  1162. });
  1163. expect(closed).toBe(true);
  1164. await browser.waitUntil(
  1165. async () =>
  1166. !(await browser.execute(
  1167. (previewTestId) => Boolean(document.querySelector(`[data-testid="${previewTestId}"]`)),
  1168. TID_PREVIEW_PANE,
  1169. )),
  1170. {
  1171. timeout: 10_000,
  1172. timeoutMsg: "Preview Pane 点击关闭后没有卸载",
  1173. },
  1174. );
  1175. }
  1176. async function closeSidePanes() {
  1177. await browser.waitUntil(
  1178. async () =>
  1179. browser.execute(() => {
  1180. const tab =
  1181. document.querySelector<HTMLElement>("[data-side-pane-tab-id][data-active]") ??
  1182. document.querySelector<HTMLElement>("[data-side-pane-tab-id]");
  1183. const closeButton = tab?.querySelector<HTMLButtonElement>("button");
  1184. if (!closeButton) return true;
  1185. closeButton.click();
  1186. return false;
  1187. }),
  1188. {
  1189. interval: 100,
  1190. timeout: 10_000,
  1191. timeoutMsg: "Assistant Preview Cards 清理 side pane tabs 超时",
  1192. },
  1193. );
  1194. }
  1195. function createFixtureServer(): Server {
  1196. return createServer((_request, response) => {
  1197. response.setHeader("content-type", "text/html; charset=utf-8");
  1198. response.end(
  1199. "<!doctype html><html><head><title>APC01 Local Preview</title></head><body>APC01_LOCAL_URL_PAGE</body></html>",
  1200. );
  1201. });
  1202. }
  1203. async function listen(server: Server): Promise<string> {
  1204. await new Promise<void>((resolveListen, rejectListen) => {
  1205. server.once("error", rejectListen);
  1206. server.listen(0, "127.0.0.1", () => {
  1207. server.off("error", rejectListen);
  1208. resolveListen();
  1209. });
  1210. });
  1211. const address = server.address() as AddressInfo;
  1212. return `http://127.0.0.1:${address.port}/assistant-preview`;
  1213. }
  1214. async function closeServer(server: Server | null) {
  1215. if (!server) return;
  1216. await new Promise<void>((resolveClose, rejectClose) => {
  1217. server.close((error) => (error ? rejectClose(error) : resolveClose()));
  1218. });
  1219. }
  1220. async function waitForPreviewCardSet(expectedTitles: readonly string[], timeout = 60_000) {
  1221. const expected = [...expectedTitles].sort();
  1222. let latest: string[] = [];
  1223. await browser.waitUntil(
  1224. async () => {
  1225. latest = (await readPreviewCards(expectedTitles)).map((card) => card.title).sort();
  1226. return JSON.stringify(latest) === JSON.stringify(expected);
  1227. },
  1228. {
  1229. timeout,
  1230. timeoutMsg: `预览卡片集合没有收敛: expected=${JSON.stringify(expected)} latest=${JSON.stringify(latest)}`,
  1231. },
  1232. );
  1233. }
  1234. type OpenMenuSlot = "context-menu" | "dropdown-menu";
  1235. async function readOpenMenuLabels(slot: OpenMenuSlot) {
  1236. const menu = await browser.$(`[data-slot="${slot}-content"][data-state="open"]`);
  1237. await menu.waitForDisplayed();
  1238. return menu.$$('[role="menuitem"]').map(async (item) => (await item.getText()).trim());
  1239. }
  1240. async function clickOpenMenuItem(slot: OpenMenuSlot, label: RegExp) {
  1241. const menuSelector = `[data-slot="${slot}-content"][data-state="open"]`;
  1242. expect(await readOpenMenuLabels(slot)).toContainEqual(expect.stringMatching(label));
  1243. // 菜单弹出动画期间的点击会被 Radix 吞掉(不触发 onSelect,下拉还会直接关闭),等动画结束再点。
  1244. await browser.waitUntil(
  1245. () =>
  1246. browser.execute((selector) => {
  1247. const menu = document.querySelector(selector);
  1248. return Boolean(
  1249. menu?.getAnimations({ subtree: true }).every((item) => item.playState !== "running"),
  1250. );
  1251. }, menuSelector),
  1252. { timeout: 5_000, timeoutMsg: `${slot} 打开动画没有结束` },
  1253. );
  1254. // 关联应用列表异步加载,「加载中」占位行会在读取标签后消失;点击前按文字重新定位,不能复用旧序号。
  1255. const items = await browser.$$(`${menuSelector} [role="menuitem"]`);
  1256. for (const item of items) {
  1257. if (label.test((await item.getText()).trim())) {
  1258. await item.click();
  1259. return;
  1260. }
  1261. }
  1262. throw new Error(`${slot} 中找不到菜单项 ${label}`);
  1263. }
  1264. interface FileManagerRevealCall {
  1265. channel: "OpenInFileManager" | "OpenInEditor";
  1266. path: string;
  1267. editorId?: string;
  1268. pathKind?: string;
  1269. }
  1270. /**
  1271. * 只在隔离 E2E 主进程替换「在文件管理器中打开」的两条 IPC,记录参数,不真的拉起 Finder:
  1272. * macOS / Windows 走 OpenInEditor(finder / explorer 定位并选中文件),失败或 Linux 回退 OpenInFileManager(打开目录)。
  1273. */
  1274. async function installFileManagerRevealProbe() {
  1275. await browser.electron.execute(
  1276. (electron, channels) => {
  1277. type Handler = (...args: unknown[]) => unknown;
  1278. const scope = globalThis as unknown as {
  1279. __apcFileManagerReveal?: { calls: FileManagerRevealCall[]; restore(): void };
  1280. };
  1281. if (scope.__apcFileManagerReveal)
  1282. throw new Error("File manager reveal probe already installed");
  1283. const handlers = (electron.ipcMain as unknown as { _invokeHandlers: Map<string, Handler> })
  1284. ._invokeHandlers;
  1285. const openDirectory = handlers.get(channels.openInFileManager);
  1286. const openInEditor = handlers.get(channels.openInEditor);
  1287. if (!openDirectory || !openInEditor) throw new Error("File manager IPC handlers unavailable");
  1288. const probe = {
  1289. calls: [] as FileManagerRevealCall[],
  1290. restore() {
  1291. handlers.set(channels.openInFileManager, openDirectory);
  1292. handlers.set(channels.openInEditor, openInEditor);
  1293. delete scope.__apcFileManagerReveal;
  1294. },
  1295. };
  1296. handlers.set(channels.openInFileManager, (_event, path) => {
  1297. probe.calls.push({ channel: "OpenInFileManager", path: String(path) });
  1298. return { success: true };
  1299. });
  1300. handlers.set(channels.openInEditor, (_event, payload) => {
  1301. const request = payload as {
  1302. editorId: string;
  1303. path: string;
  1304. options?: { pathKind?: string };
  1305. };
  1306. probe.calls.push({
  1307. channel: "OpenInEditor",
  1308. editorId: request.editorId,
  1309. path: request.path,
  1310. pathKind: request.options?.pathKind,
  1311. });
  1312. return { success: true };
  1313. });
  1314. scope.__apcFileManagerReveal = probe;
  1315. },
  1316. {
  1317. openInFileManager: PlatformChannels.OpenInFileManager,
  1318. openInEditor: PlatformChannels.OpenInEditor,
  1319. },
  1320. );
  1321. }
  1322. async function readFileManagerRevealCalls(): Promise<FileManagerRevealCall[]> {
  1323. return browser.electron.execute(
  1324. () =>
  1325. (globalThis as unknown as { __apcFileManagerReveal?: { calls: FileManagerRevealCall[] } })
  1326. .__apcFileManagerReveal?.calls ?? [],
  1327. );
  1328. }
  1329. async function restoreFileManagerRevealProbe() {
  1330. await browser.electron.execute(() =>
  1331. (
  1332. globalThis as unknown as { __apcFileManagerReveal?: { restore(): void } }
  1333. ).__apcFileManagerReveal?.restore(),
  1334. );
  1335. }
  1336. /** macOS:每次点击只发一次 finder 定位请求,目标是文件本身(Finder 打开所在目录并选中它)。 */
  1337. async function expectFinderRevealCalls(expectedFiles: string[]) {
  1338. let calls: FileManagerRevealCall[] = [];
  1339. // timeoutMsg 在调用时就求值,只能反映初始空数组;超时后用最后一次读到的 calls 重新报错。
  1340. await browser
  1341. .waitUntil(
  1342. async () => {
  1343. calls = await readFileManagerRevealCalls();
  1344. return calls.length === expectedFiles.length;
  1345. },
  1346. { timeout: 10_000 },
  1347. )
  1348. .catch(() => {
  1349. throw new Error(
  1350. `文件管理器定位调用次数不符: expected=${expectedFiles.length} calls=${JSON.stringify(calls)}`,
  1351. );
  1352. });
  1353. expect(calls.map(({ channel, editorId, pathKind }) => ({ channel, editorId, pathKind }))).toEqual(
  1354. expectedFiles.map(() => ({ channel: "OpenInEditor", editorId: "finder", pathKind: "file" })),
  1355. );
  1356. // renderer 传的是工作区内路径,可能未解析 /var → /private/var 等软链;按真实路径比对。
  1357. expect(await Promise.all(calls.map(({ path }) => realpath(path)))).toEqual(expectedFiles);
  1358. }
  1359. /** 正文 Markdown 文件链接按钮的 title 是渲染层解析出的路径(与传给 IPC 的路径一致);按可见文案读取。 */
  1360. async function findBodyFileLinkPath(label: string): Promise<string> {
  1361. let path = "";
  1362. await browser.waitUntil(
  1363. async () => {
  1364. path = await browser.execute((text) => {
  1365. const button = Array.from(
  1366. document.querySelectorAll<HTMLButtonElement>("button[title]"),
  1367. ).find((item) => (item.textContent ?? "").trim() === text);
  1368. return button?.title ?? "";
  1369. }, label);
  1370. return path.length > 0;
  1371. },
  1372. { timeout: 30_000, timeoutMsg: `正文没有渲染文件链接 ${label}` },
  1373. );
  1374. return path;
  1375. }
  1376. interface BodyLinkMenuOrder {
  1377. lastApplication: number;
  1378. loading: boolean;
  1379. reveal: number;
  1380. revealCount: number;
  1381. saveAs: number;
  1382. }
  1383. /** 正文链接右键菜单:stat 与关联应用异步加载,按调用方给的就绪条件轮询后返回各分组位置。 */
  1384. async function readBodyLinkMenuOrder(
  1385. ready: (order: BodyLinkMenuOrder) => boolean,
  1386. ): Promise<BodyLinkMenuOrder> {
  1387. const menuSelector = '[data-slot="context-menu-content"][data-state="open"]';
  1388. await browser.$(menuSelector).waitForDisplayed();
  1389. let order: BodyLinkMenuOrder | null = null;
  1390. await browser
  1391. .waitUntil(
  1392. async () => {
  1393. order = await browser.execute(
  1394. (selector, labelSource) => {
  1395. const items = Array.from(
  1396. document
  1397. .querySelector(selector)
  1398. ?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [],
  1399. );
  1400. const label = new RegExp(labelSource);
  1401. const text = (item: HTMLElement) => item.textContent?.trim() ?? "";
  1402. const appIndexes = items
  1403. .map((item, position) =>
  1404. item.matches("[data-file-application-direct], .file-application-more-trigger") ||
  1405. /Open with default app|使用默认应用打开/.test(text(item))
  1406. ? position
  1407. : -1,
  1408. )
  1409. .filter((position) => position >= 0);
  1410. return {
  1411. lastApplication: appIndexes.at(-1) ?? -1,
  1412. loading: items.some((item) => /^(Loading|加载中)[….]*$/.test(text(item))),
  1413. reveal: items.findIndex((item) => label.test(text(item))),
  1414. revealCount: items.filter((item) => label.test(text(item))).length,
  1415. saveAs: items.findIndex((item) => /^(Save as|另存为)/i.test(text(item))),
  1416. };
  1417. },
  1418. menuSelector,
  1419. REVEAL_IN_FINDER_LABEL.source,
  1420. );
  1421. return ready(order);
  1422. },
  1423. { timeout: 10_000 },
  1424. )
  1425. .catch(() => {
  1426. throw new Error(`正文链接右键菜单没有就绪: ${JSON.stringify(order)}`);
  1427. });
  1428. return order!;
  1429. }