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

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