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

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