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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. /* eslint-disable max-lines -- APC01-APC14 共用真实 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, 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 type { FileApplicationInfo } from "@zcode/shared";
  23. import {
  24. installFileApplicationMenuProbe,
  25. readFileApplicationMenuProbe,
  26. restoreFileApplicationMenuProbe,
  27. } from "../helpers/file-application-menu-probe.js";
  28. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  29. import { restartIntoWorkspacePreservingProfile } from "../helpers/model-provider-restart.js";
  30. import {
  31. clickV4Stop,
  32. prepareV4ConversationE2E,
  33. selectV4TaskById,
  34. sendV4Prompt,
  35. startNewV4Draft,
  36. switchV4Mode,
  37. waitForV4AssistantMessageContaining,
  38. waitForV4Pane,
  39. } from "../helpers/v4-conversation.js";
  40. const CASE_MARKER = "E2E_ASSISTANT_PREVIEW_CARDS";
  41. const CASE_RELATIVE_ROOT = "assistant-preview-e2e";
  42. const CASE_ROOT = join(DEFAULT_WORKSPACE, CASE_RELATIVE_ROOT);
  43. const OFFICE_FIXTURE_ROOT = fileURLToPath(
  44. new URL(
  45. "../fixtures/fs/conversation-session/conversation-session-assistant-preview-cards/",
  46. import.meta.url,
  47. ),
  48. );
  49. const STREAM_URL = "http://localhost:41789/assistant-preview-stream";
  50. const SOURCE_HTML_RELATIVE_PATH = `${CASE_RELATIVE_ROOT}/本轮 输出/index 页面.html`;
  51. const SOURCE_MARKDOWN_RELATIVE_PATH = `${CASE_RELATIVE_ROOT}/本轮 输出/说明 文档.md`;
  52. const SOURCE_HTML_PATH = join(DEFAULT_WORKSPACE, SOURCE_HTML_RELATIVE_PATH);
  53. const OFFICE_FILES = [
  54. { fixture: "sample.docx", name: "项目 简介.docx" },
  55. { fixture: "sample.xlsx", name: "年度 总结.xlsx" },
  56. { fixture: "sample.pptx", name: "产品 路线.pptx" },
  57. { fixture: "sample.pdf", name: "审计 报告.pdf" },
  58. ] as const;
  59. const MEDIA_FILES = ["生成 视频.mp4", "生成 音频.wav"] as const;
  60. interface PreviewCardSnapshot {
  61. text: string;
  62. title: string;
  63. }
  64. let fixtureServer: Server | null = null;
  65. let fixtureRootUrl = "";
  66. describe("Assistant Preview Cards E2E", () => {
  67. before(async () => {
  68. fixtureServer = createFixtureServer();
  69. fixtureRootUrl = await listen(fixtureServer);
  70. });
  71. afterEach(async () => {
  72. await closeSidePanes();
  73. await rm(CASE_ROOT, { recursive: true, force: true });
  74. });
  75. after(async () => {
  76. await closeServer(fixtureServer);
  77. fixtureServer = null;
  78. await browser.electron.restoreAllMocks();
  79. await clearAppData();
  80. });
  81. it("APC01/APC04: completed localhost URL 去重并打开真实 Browser 页面", async () => {
  82. await prepareCase();
  83. const marker = `${CASE_MARKER}_LOCAL_URL`;
  84. await sendV4Prompt(
  85. `${marker}: reply with the same local preview URL more than once. E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`,
  86. );
  87. await waitForCompleted(`${marker}_DONE`);
  88. await waitForPreviewCards(["APC Local Preview"]);
  89. // APC01 同时验证整卡点击:localhost 网页卡片主体与主按钮触发同一 Browser 预览。
  90. await clickPreviewCardBody("APC Local Preview");
  91. await waitForBrowserSurface(fixtureRootUrl, "APC01_LOCAL_URL_PAGE");
  92. }).timeout(180_000);
  93. it("APC02: interrupted turn 在 URL 已到达后 Stop,卡片只在终态出现", async () => {
  94. await prepareCase();
  95. const marker = `${CASE_MARKER}_INTERRUPTED`;
  96. await sendV4Prompt(`${marker}: keep streaming after publishing ${STREAM_URL}.`);
  97. await waitForV4AssistantMessageContaining(`${marker}_EARLY`, 60_000);
  98. expect(await readPreviewCards()).toEqual([]);
  99. await clickV4Stop();
  100. await waitForV4Pane(
  101. (snapshot) => !snapshot.canStop && snapshot.timelineText.includes(`${marker}_EARLY`),
  102. "APC02 Stop 后 turn 没有进入 interrupted 终态",
  103. 60_000,
  104. );
  105. await waitForPreviewCards(["assistant-preview-stream"]);
  106. }).timeout(180_000);
  107. it("APC03: streaming 期间不显示卡片,complete 后显示", async () => {
  108. await prepareCase();
  109. const marker = `${CASE_MARKER}_STREAMING`;
  110. await sendV4Prompt(`${marker}: stream ${STREAM_URL} before the final marker.`);
  111. await waitForV4AssistantMessageContaining(`${marker}_EARLY`, 60_000);
  112. expect(await readPreviewCards()).toEqual([]);
  113. await waitForCompleted(`${marker}_DONE`);
  114. await waitForPreviewCards(["assistant-preview-stream"]);
  115. }).timeout(180_000);
  116. it("APC04: localhost 与本轮 HTML 同时出现时按现有业务规则抑制 HTML", async () => {
  117. await prepareCase({ yolo: true });
  118. const marker = `${CASE_MARKER}_LOCAL_SUPPRESSES_HTML`;
  119. await sendV4Prompt(
  120. `${marker}: create ${SOURCE_HTML_RELATIVE_PATH}, then mention it with E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}.`,
  121. );
  122. await waitForCompleted(`${marker}_DONE`);
  123. await waitForPreviewCards(["APC Local Only"]);
  124. await expectPreviewCardMissing(basename(SOURCE_HTML_RELATIVE_PATH));
  125. }).timeout(180_000);
  126. it("APC06/APC07: source gate、Office 自动打开 PPTX", async () => {
  127. await prepareCase();
  128. await materializeOfficeFixtures();
  129. await materializeStaleSourceFiles();
  130. const marker = `${CASE_MARKER}_OFFICE`;
  131. await sendV4Prompt(`${marker}_PPTX: report the prepared Office files and one missing PDF.`);
  132. await waitForCompleted(`${marker}_PPTX_DONE`);
  133. const officeTitles = [...OFFICE_FILES].reverse().map((item) => item.name);
  134. await waitForPreviewCards(officeTitles);
  135. await expectPreviewCardMissing("旧 页面.html");
  136. await expectPreviewCardMissing("旧 说明.md");
  137. await expectPreviewCardMissing("不存在.pdf");
  138. await waitForPreviewRenderer("产品 路线.pptx", "pptx");
  139. for (const file of OFFICE_FILES) {
  140. await assertFileOpenApps(file.name);
  141. }
  142. }).timeout(240_000);
  143. it("APC14: unified file menu defaults, first three and More dispatch the selected application", async () => {
  144. await prepareCase();
  145. await materializeOfficeFixtures();
  146. const marker = `${CASE_MARKER}_OFFICE`;
  147. await sendV4Prompt(`${marker}_PPTX: report the prepared Office files and one missing PDF.`);
  148. await waitForCompleted(`${marker}_PPTX_DONE`);
  149. await waitForPreviewCards([...OFFICE_FILES].reverse().map((item) => item.name));
  150. await closeSidePanes();
  151. const filename = "产品 路线.pptx";
  152. const targetPath = await realpath(join(CASE_ROOT, "office", filename));
  153. const row = await browser.$(`[data-preview-card-title="${filename}"]`);
  154. // 原生候选依平台而变;固定边界使用明确 IPC fixture,不冒充系统枚举或实际启动。
  155. for (const count of [0, 1, 3, 10]) {
  156. const applications = Array.from({ length: count }, (_, index) => ({
  157. id: `apc-app-${index}`,
  158. name: `APC Application ${index}`,
  159. isDefault: index === count - 1,
  160. }));
  161. await installFileApplicationMenuProbe(targetPath, applications);
  162. try {
  163. await assertFileOpenApps(filename, applications);
  164. await row.click({ button: "right" });
  165. const menu = await browser.$('[data-slot="context-menu-content"][data-state="open"]');
  166. await menu.waitForDisplayed();
  167. await assertApplicationMenu(menu, applications);
  168. const labels = await menu.$$('[role="menuitem"]').map((item) => item.getText());
  169. expect(labels[0]).toMatch(/^(Preview|预览)$/);
  170. expect(labels.some((label) => /Open containing folder|打开所在目录/.test(label))).toBe(
  171. false,
  172. );
  173. await browser.keys("Escape");
  174. // 点击真实预览动作后核对 renderer,而不是直接调用产品回调。
  175. await row.click({ button: "right" });
  176. await browser
  177. .$('[data-slot="context-menu-content"][data-state="open"] [role="menuitem"]')
  178. .click();
  179. await waitForPreviewRenderer(filename, "pptx");
  180. if (count > 3) {
  181. await row.$('button[aria-label="Choose app"], button[aria-label="选择打开方式"]').click();
  182. const dropdown = await browser.$(
  183. '[data-slot="dropdown-menu-content"][data-state="open"]',
  184. );
  185. await dropdown.$(".file-application-more-trigger").moveTo();
  186. const list = await browser.$("[data-file-application-list]");
  187. await list.waitForDisplayed();
  188. const items = await list.$$('[role="menuitem"]');
  189. const last = items[(await items.length) - 1]!;
  190. await last.scrollIntoView();
  191. await last.click();
  192. await browser.waitUntil(async () => (await readFileApplicationMenuProbe()).length === 1, {
  193. timeout: 10_000,
  194. });
  195. const [call] = await readFileApplicationMenuProbe();
  196. expect(call?.applicationId).toBe("apc-app-8");
  197. expect(call?.target.path).toBe(targetPath);
  198. expect(call?.target.pathKind).toBe("file");
  199. }
  200. } finally {
  201. await browser.keys("Escape");
  202. await browser.keys("Escape");
  203. await restoreFileApplicationMenuProbe();
  204. }
  205. }
  206. }).timeout(240_000);
  207. it("APC12: 独立音频消息打开原生 audio 播放器", async () => {
  208. await prepareCase();
  209. await materializeMediaFixtures();
  210. const marker = `${CASE_MARKER}_OFFICE_AUDIO`;
  211. await sendV4Prompt(`${marker}: report the prepared audio file only.`);
  212. await waitForCompleted(`${marker}_DONE`);
  213. await waitForPreviewCards(["生成 音频.wav"]);
  214. const logSnapshot = await snapshotDesktopRuntimeLogs();
  215. await clickPreviewCard("生成 音频.wav");
  216. await waitForPreviewRenderer("生成 音频.wav", "audio");
  217. await assertLocalMediaPreviewLogs(logSnapshot);
  218. }).timeout(180_000);
  219. it("APC12: 独立视频消息打开并保持 media 节点", async () => {
  220. await prepareCase();
  221. await materializeMediaFixtures();
  222. const marker = `${CASE_MARKER}_OFFICE_VIDEO`;
  223. await sendV4Prompt(`${marker}: report the prepared video file only.`);
  224. await waitForCompleted(`${marker}_DONE`);
  225. await waitForPreviewCards(["生成 视频.mp4"]);
  226. await assertFileOpenApps("生成 视频.mp4");
  227. const logSnapshot = await snapshotDesktopRuntimeLogs();
  228. await clickPreviewCard("生成 视频.mp4");
  229. await waitForPreviewRenderer("生成 视频.mp4", "video");
  230. const mediaUrl = await browser.execute(
  231. () => document.querySelector<HTMLVideoElement>("video[controls]")?.currentSrc ?? "",
  232. );
  233. expect(mediaUrl).not.toBe("");
  234. expect(new URL(mediaUrl).protocol).toBe("zcode-media:");
  235. await assertPreviewVideoSurvivesResizeAndFullscreen();
  236. await assertLocalMediaPreviewLogs(logSnapshot);
  237. }).timeout(180_000);
  238. it("APC08: 最多显示 10 张,并且前 15 个不足时不从第 16 个以后回填", async () => {
  239. await prepareCase();
  240. await materializeBoundFiles();
  241. const maxMarker = `${CASE_MARKER}_MAX_TEN`;
  242. await sendV4Prompt(`${maxMarker}: list the twelve prepared max-bound PDF paths in order.`);
  243. await waitForCompleted(`${maxMarker}_DONE`);
  244. await waitForPreviewCards(
  245. Array.from({ length: 10 }, (_, index) => `max-${String(12 - index).padStart(2, "0")}.pdf`),
  246. );
  247. await expectPreviewCardMissing("max-02.pdf");
  248. await expectPreviewCardMissing("max-01.pdf");
  249. await prepareCase();
  250. await materializeBoundFiles();
  251. const noFillMarker = `${CASE_MARKER}_NO_BACKFILL`;
  252. await sendV4Prompt(
  253. `${noFillMarker}: list all sixteen no-backfill PDF paths in ascending order.`,
  254. );
  255. await waitForCompleted(`${noFillMarker}_DONE`);
  256. await waitForPreviewCards(
  257. Array.from({ length: 9 }, (_, index) => `nofill-${String(16 - index).padStart(2, "0")}.pdf`),
  258. );
  259. await expectPreviewCardMissing("nofill-01.pdf");
  260. }).timeout(240_000);
  261. it("APC05/APC09/APC11: 当前轮 HTML/Markdown 逆序展示、打开,收起偏好在切换会话和 cold resume 后保留", async () => {
  262. await prepareCase({ yolo: true });
  263. const marker = `${CASE_MARKER}_SOURCE_AND_COLD`;
  264. await sendV4Prompt(
  265. `${marker}: create ${SOURCE_HTML_RELATIVE_PATH} and ${SOURCE_MARKDOWN_RELATIVE_PATH}, then report both.`,
  266. );
  267. await waitForCompleted(`${marker}_DONE`);
  268. const targetSession = await waitForBoundSession(marker);
  269. const expectedTitles = [
  270. basename(SOURCE_MARKDOWN_RELATIVE_PATH),
  271. basename(SOURCE_HTML_RELATIVE_PATH),
  272. ];
  273. await waitForPreviewCards(expectedTitles);
  274. await assertSourcePreviewTargets();
  275. await assertLocalHtmlExternalOpen();
  276. await clickPreviewCard(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  277. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  278. await waitForSidePaneExpanded(true);
  279. await clickSidePaneToggle();
  280. await waitForSidePaneExpanded(false);
  281. await startNewV4Draft();
  282. const parkingMarker = `${CASE_MARKER}_PARKING`;
  283. await sendV4Prompt(`${parkingMarker}: complete a parking task before cold resume.`);
  284. await waitForCompleted(`${parkingMarker}_DONE`);
  285. const parkingSession = await waitForBoundSession(parkingMarker);
  286. expect(parkingSession).not.toBe(targetSession);
  287. await selectV4TaskById(targetSession, 60_000);
  288. await waitForV4Pane(
  289. (snapshot) =>
  290. snapshot.sessionId === targetSession && snapshot.timelineText.includes(`${marker}_DONE`),
  291. `APC11 切回目标 session ${targetSession} 后没有恢复对话`,
  292. 90_000,
  293. );
  294. await waitForPreviewCards(expectedTitles, 90_000);
  295. await waitForSidePaneExpanded(false);
  296. await clickPreviewCard(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  297. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  298. await waitForSidePaneExpanded(true);
  299. await closeSidePanes();
  300. await restartIntoWorkspacePreservingProfile();
  301. await selectV4TaskById(targetSession, 60_000);
  302. await waitForV4Pane(
  303. (snapshot) =>
  304. snapshot.sessionId === targetSession && snapshot.timelineText.includes(`${marker}_DONE`),
  305. `APC09 cold resume 后没有恢复目标 session ${targetSession}`,
  306. 90_000,
  307. );
  308. await waitForPreviewCards(expectedTitles, 90_000);
  309. await assertSourcePreviewTargets();
  310. }).timeout(360_000);
  311. });
  312. async function prepareCase(options: { yolo?: boolean } = {}) {
  313. await prepareV4ConversationE2E();
  314. if (options.yolo) {
  315. await switchV4Mode("yolo");
  316. }
  317. await rm(CASE_ROOT, { recursive: true, force: true });
  318. await mkdir(CASE_ROOT, { recursive: true });
  319. }
  320. async function waitForCompleted(marker: string) {
  321. await waitForV4AssistantMessageContaining(marker, 90_000);
  322. await waitForV4Pane(
  323. (snapshot) => !snapshot.canStop && snapshot.timelineText.includes(marker),
  324. `Assistant Preview Cards turn 没有完成: ${marker}`,
  325. 90_000,
  326. );
  327. }
  328. async function waitForBoundSession(marker: string): Promise<string> {
  329. const snapshot = await waitForV4Pane(
  330. (current) =>
  331. current.sessionId !== null &&
  332. current.sessionId !== "draft" &&
  333. !current.canStop &&
  334. current.timelineText.includes(marker),
  335. `Assistant Preview Cards 缺少已绑定 session: ${marker}`,
  336. 60_000,
  337. );
  338. if (!snapshot.sessionId || snapshot.sessionId === "draft") {
  339. throw new Error(`Assistant Preview Cards 得到无效 sessionId: ${snapshot.sessionId ?? "null"}`);
  340. }
  341. return snapshot.sessionId;
  342. }
  343. async function readPreviewCards(
  344. expectedTitles: readonly string[] = [],
  345. ): Promise<PreviewCardSnapshot[]> {
  346. return browser.execute(
  347. (titles) => {
  348. const openLabels = new Set(["Open", "打开", "Preview", "预览"]);
  349. return Array.from(
  350. document.querySelectorAll<HTMLElement>('[data-zcode-stream-animate="true"]'),
  351. )
  352. .filter((row) =>
  353. Array.from(row.querySelectorAll<HTMLButtonElement>("button")).some((button) =>
  354. openLabels.has((button.textContent ?? "").trim()),
  355. ),
  356. )
  357. .map((row) => {
  358. const text = row.innerText.replace(/\u00a0/g, " ").trim();
  359. const title = titles.find((candidate) => text.includes(candidate)) ?? "";
  360. return { text, title };
  361. });
  362. },
  363. [...expectedTitles],
  364. );
  365. }
  366. async function waitForPreviewCards(expectedTitles: readonly string[], timeout = 60_000) {
  367. let latest: PreviewCardSnapshot[] = [];
  368. await browser.waitUntil(
  369. async () => {
  370. latest = await readPreviewCards(expectedTitles);
  371. return (
  372. latest.length === expectedTitles.length &&
  373. latest.every((card, index) => card.title === expectedTitles[index])
  374. );
  375. },
  376. {
  377. timeout,
  378. timeoutMsg: `预览卡片没有按预期收敛: expected=${JSON.stringify(expectedTitles)} latest=${JSON.stringify(latest)}`,
  379. },
  380. );
  381. }
  382. async function expectPreviewCardMissing(title: string) {
  383. const cards = await readPreviewCards([title]);
  384. expect(cards.some((card) => card.title === title)).toBe(false);
  385. }
  386. async function clickPreviewCard(title: string) {
  387. const result = await browser.execute((expectedTitle) => {
  388. const openLabels = new Set(["Open", "打开", "Preview", "预览"]);
  389. const row = Array.from(
  390. document.querySelectorAll<HTMLElement>('[data-zcode-stream-animate="true"]'),
  391. ).find((candidate) => candidate.innerText.includes(expectedTitle));
  392. const button = Array.from(row?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  393. (candidate) => openLabels.has((candidate.textContent ?? "").trim()),
  394. );
  395. button?.click();
  396. return { clicked: Boolean(button), disabled: Boolean(button?.disabled) };
  397. }, title);
  398. expect(result.clicked).toBe(true);
  399. expect(result.disabled).toBe(false);
  400. }
  401. // 卡片主体整卡可点:点击标题区域(铺满卡片的透明按钮)与主按钮执行同一预览动作。
  402. async function clickPreviewCardBody(title: string) {
  403. const result = await browser.execute((expectedTitle) => {
  404. const row = document.querySelector<HTMLElement>(
  405. `[data-preview-card-title="${expectedTitle}"]`,
  406. );
  407. const overlay = Array.from(row?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  408. (button) => (button.getAttribute("aria-label") ?? "").endsWith(expectedTitle),
  409. );
  410. overlay?.click();
  411. return { clicked: Boolean(overlay), disabled: Boolean(overlay?.disabled) };
  412. }, title);
  413. expect(result.clicked).toBe(true);
  414. expect(result.disabled).toBe(false);
  415. }
  416. async function assertApplicationMenu(
  417. menu: ChainablePromiseElement,
  418. applications: FileApplicationInfo[],
  419. ) {
  420. const unique = [...new Map(applications.map((app) => [app.id, app])).values()];
  421. const ordered = [
  422. ...unique.filter((app) => app.isDefault),
  423. ...unique.filter((app) => !app.isDefault),
  424. ];
  425. await browser.waitUntil(
  426. async () => {
  427. const ids = await menu
  428. .$$("[data-file-application-direct]")
  429. .map((item) => item.getAttribute("data-file-application-direct"));
  430. const text = await menu.getText();
  431. return (
  432. JSON.stringify(ids) === JSON.stringify(ordered.slice(0, 3).map((app) => app.id)) &&
  433. !/^(Loading|加载中)[….]*$/m.test(text)
  434. );
  435. },
  436. { timeout: 10_000, timeoutMsg: "File applications did not match the bound target" },
  437. );
  438. const direct = await menu.$$("[data-file-application-direct]");
  439. for (let index = 0; index < (await direct.length); index++) {
  440. const label = await direct[index]!.getText();
  441. expect(label).toContain(ordered[index]!.name);
  442. if (ordered[index]!.isDefault) expect(label).toMatch(/Open in|在.*中打开/);
  443. expect(
  444. await direct[index]!.$(
  445. '[data-slot="file-application-icon"], [data-slot="file-application-icon-fallback"]',
  446. ).isExisting(),
  447. ).toBe(true);
  448. }
  449. const text = await menu.getText();
  450. expect(text).toMatch(/Save as|另存为/i);
  451. expect(text).toMatch(/Copy absolute path|复制绝对路径/);
  452. if (ordered.length === 0) expect(text).toMatch(/Open with default app|使用默认应用打开/);
  453. const more = await menu.$(".file-application-more-trigger");
  454. expect(await more.isExisting()).toBe(ordered.length > 3);
  455. if (ordered.length > 3) {
  456. await more.moveTo();
  457. const list = await browser.$("[data-file-application-list]");
  458. await list.waitForDisplayed();
  459. const labels = await list.$$('[role="menuitem"]').map((item) => item.getText());
  460. expect(labels).toEqual(ordered.slice(3).map((app) => app.name));
  461. if (ordered.length > 9) {
  462. const dimensions = await list.getSize();
  463. expect(dimensions.height).toBeLessThanOrEqual(179);
  464. }
  465. await browser.keys("Escape");
  466. }
  467. }
  468. async function assertFileOpenApps(filename: string, fixture?: FileApplicationInfo[]) {
  469. // Office 夹具位于 office/,不能按 CASE_ROOT 根目录查找;必须查询卡片对应的同一个真实文件。
  470. const filePath = await realpath(
  471. join(
  472. CASE_ROOT,
  473. OFFICE_FILES.some((file) => file.name === filename) ? "office" : "media",
  474. filename,
  475. ),
  476. );
  477. const expected =
  478. fixture ??
  479. (await browser.execute(async (filePath) => {
  480. const platform = (
  481. window as unknown as Window & {
  482. zcode: {
  483. getFileApplications(target: {
  484. path: string;
  485. pathKind: "file";
  486. }): Promise<FileApplicationInfo[]>;
  487. };
  488. }
  489. ).zcode;
  490. return platform.getFileApplications({ path: filePath, pathKind: "file" });
  491. }, filePath));
  492. const row = await browser.$(`[data-preview-card-title="${filename}"]`);
  493. await row.$('button[aria-label="Choose app"], button[aria-label="选择打开方式"]').click();
  494. const menu = await browser.$('[data-slot="dropdown-menu-content"][data-state="open"]');
  495. await menu.waitForDisplayed();
  496. try {
  497. await assertApplicationMenu(menu, expected);
  498. expect(await menu.getText()).toMatch(/Copy relative path|复制相对路径/);
  499. } finally {
  500. await browser.keys("Escape");
  501. }
  502. }
  503. async function assertLocalHtmlExternalOpen() {
  504. const openPath = await browser.electron.mock("shell", "openPath");
  505. await openPath.mockResolvedValue("");
  506. try {
  507. const expectedTitle = basename(SOURCE_HTML_RELATIVE_PATH);
  508. const rows = await browser.$$('[data-zcode-stream-animate="true"]');
  509. const row = (
  510. await rows.map(async (candidate) => ({
  511. candidate,
  512. text: await candidate.getText(),
  513. }))
  514. ).find(({ text }) => text.includes(expectedTitle))?.candidate;
  515. expect(row).toBeDefined();
  516. const trigger = await row?.$(
  517. 'button[aria-label="Choose app"], button[aria-label="选择打开方式"]',
  518. );
  519. expect(trigger).toBeDefined();
  520. await trigger?.click();
  521. await browser.waitUntil(
  522. async () => {
  523. const labels = new Set(["Open in browser", "在浏览器中打开"]);
  524. const items = await browser.$$('[role="menuitem"]');
  525. const item = (
  526. await items.map(async (candidate) => ({
  527. candidate,
  528. text: await candidate.getText(),
  529. }))
  530. ).find(({ text }) => labels.has(text.trim()))?.candidate;
  531. if (!item) return false;
  532. await item.click();
  533. return true;
  534. },
  535. { timeout: 10_000, timeoutMsg: "本地 HTML 卡片没有显示外部浏览器入口" },
  536. );
  537. await browser.waitUntil(
  538. async () => {
  539. try {
  540. await expect(openPath).toHaveBeenCalledWith(await realpath(SOURCE_HTML_PATH));
  541. return true;
  542. } catch {
  543. return false;
  544. }
  545. },
  546. { timeout: 10_000, timeoutMsg: "本地 HTML 没有通过 shell.openPath 打开" },
  547. );
  548. } finally {
  549. await browser.electron.restoreAllMocks();
  550. }
  551. }
  552. async function clickSidePaneToggle() {
  553. const clicked = await browser.execute(() => {
  554. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  555. (candidate) =>
  556. ["收起侧边面板", "Collapse side pane", "展开侧边面板", "Expand side pane"].includes(
  557. candidate.getAttribute("aria-label") ?? "",
  558. ),
  559. );
  560. button?.click();
  561. return Boolean(button);
  562. });
  563. expect(clicked).toBe(true);
  564. }
  565. async function waitForSidePaneExpanded(expectedExpanded: boolean) {
  566. let latestLabel = "";
  567. await browser.waitUntil(
  568. async () => {
  569. latestLabel = await browser.execute(() => {
  570. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  571. (candidate) =>
  572. ["收起侧边面板", "Collapse side pane", "展开侧边面板", "Expand side pane"].includes(
  573. candidate.getAttribute("aria-label") ?? "",
  574. ),
  575. );
  576. return button?.getAttribute("aria-label") ?? "";
  577. });
  578. const isExpanded = ["收起侧边面板", "Collapse side pane"].includes(latestLabel);
  579. return isExpanded === expectedExpanded;
  580. },
  581. {
  582. timeout: 15_000,
  583. timeoutMsg: `side pane 展开状态不符合预期: expected=${expectedExpanded}, label=${latestLabel}`,
  584. },
  585. );
  586. }
  587. async function waitForBrowserSurface(expectedUrl: string, bodyMarker: string) {
  588. let latest = { address: "", webContentsId: 0 };
  589. await browser.waitUntil(
  590. async () => {
  591. latest = await browser.execute(
  592. (addressTestId, webviewTestId) => {
  593. const address = document.querySelector<HTMLInputElement>(
  594. `[data-testid="${addressTestId}"]`,
  595. );
  596. const webview = document.querySelector<HTMLElement>(`[data-testid="${webviewTestId}"]`) as
  597. | (HTMLElement & { getWebContentsId?: () => number })
  598. | null;
  599. return {
  600. address: address?.value ?? "",
  601. webContentsId: webview?.getWebContentsId?.() ?? 0,
  602. };
  603. },
  604. TID_BROWSER_ADDRESS_INPUT,
  605. TID_BROWSER_WEBVIEW,
  606. );
  607. return latest.webContentsId > 0 && new URL(latest.address).href === new URL(expectedUrl).href;
  608. },
  609. {
  610. timeout: 60_000,
  611. timeoutMsg: `Browser Pane 没有打开目标 URL: ${JSON.stringify(latest)}`,
  612. },
  613. );
  614. let latestBody = "";
  615. await browser.waitUntil(
  616. async () => {
  617. latestBody = await browser.electron.execute(async (electron, webContentsId) => {
  618. const contents = electron.webContents.fromId(webContentsId);
  619. if (!contents || contents.isDestroyed()) return "";
  620. return contents.executeJavaScript("document.body?.innerText ?? ''");
  621. }, latest.webContentsId);
  622. return latestBody.includes(bodyMarker);
  623. },
  624. {
  625. timeout: 60_000,
  626. timeoutMsg: `Browser webview 没有加载页面 marker ${bodyMarker}: ${latestBody}`,
  627. },
  628. );
  629. }
  630. async function waitForPreviewRenderer(
  631. filename: string,
  632. renderer: "docx" | "excel" | "pptx" | "pdf" | "markdown" | "audio" | "video",
  633. ) {
  634. let latest = { hasError: false, header: "", ready: false, text: "" };
  635. await browser.waitUntil(
  636. async () => {
  637. latest = await browser.execute(
  638. (previewTestId, expectedFilename, expectedRenderer) => {
  639. const pane = document.querySelector<HTMLElement>(`[data-testid="${previewTestId}"]`);
  640. const text = (pane?.innerText ?? "").replace(/\u00a0/g, " ");
  641. const hasError = Boolean(pane?.querySelector('[role="alert"]'));
  642. let ready = false;
  643. if (expectedRenderer === "docx" || expectedRenderer === "excel") {
  644. ready = Boolean(
  645. pane?.querySelector(`[data-office-preview-kind="${expectedRenderer}"]`),
  646. );
  647. } else if (expectedRenderer === "pptx") {
  648. ready = Boolean(pane?.querySelector("aside[aria-label] button[aria-label]"));
  649. } else if (expectedRenderer === "pdf") {
  650. ready = Boolean(pane?.querySelector(".react-pdf__Document .react-pdf__Page"));
  651. } else if (expectedRenderer === "audio") {
  652. ready = Boolean(pane?.querySelector("audio[controls]"));
  653. } else if (expectedRenderer === "video") {
  654. ready = Boolean(pane?.querySelector("video[controls][playsinline]"));
  655. } else {
  656. ready = text.includes("APC05 Markdown renderer marker");
  657. }
  658. return {
  659. hasError,
  660. // 文件管理器把预览标题 portal 到共同头部;不能在预览正文里找文件名。
  661. header:
  662. pane?.closest("[data-file-manager-pane]")?.firstElementChild?.textContent ??
  663. text.split("\n")[0] ??
  664. "",
  665. ready,
  666. text,
  667. };
  668. },
  669. TID_PREVIEW_PANE,
  670. filename,
  671. renderer,
  672. );
  673. return !latest.hasError && latest.header.includes(filename) && latest.ready;
  674. },
  675. {
  676. timeout: 90_000,
  677. timeoutMsg: `Preview Pane renderer 没有就绪: ${filename}/${renderer}; latest=${JSON.stringify(latest)}`,
  678. },
  679. );
  680. }
  681. async function assertPreviewVideoSurvivesResizeAndFullscreen() {
  682. const videoReady = await browser.execute(() => {
  683. const video = document.querySelector<HTMLVideoElement>("video[controls][playsinline]");
  684. if (!video) return false;
  685. const probeWindow = window as Window & { __zcodePreviewVideo?: HTMLVideoElement };
  686. probeWindow.__zcodePreviewVideo = video;
  687. window.dispatchEvent(new Event("resize"));
  688. return true;
  689. });
  690. expect(videoReady).toBe(true);
  691. // resize settling 的 state update 应该已经完成;媒体节点不能被替换或卸载。
  692. await browser.pause(80);
  693. const sameVideoAfterResize = await browser.execute(() => {
  694. const probeWindow = window as Window & { __zcodePreviewVideo?: HTMLVideoElement };
  695. return (
  696. document.querySelector<HTMLVideoElement>("video[controls][playsinline]") ===
  697. probeWindow.__zcodePreviewVideo
  698. );
  699. });
  700. expect(sameVideoAfterResize).toBe(true);
  701. const fullscreenResult = await browser.executeAsync((done) => {
  702. const video = document.querySelector<HTMLVideoElement>("video[controls][playsinline]");
  703. if (!video?.requestFullscreen) {
  704. done("unsupported");
  705. return;
  706. }
  707. const finish = () => {
  708. document.removeEventListener("fullscreenchange", finish);
  709. done(document.fullscreenElement === video ? "entered" : "not-entered");
  710. };
  711. document.addEventListener("fullscreenchange", finish, { once: true });
  712. void video.requestFullscreen().catch(() => {
  713. document.removeEventListener("fullscreenchange", finish);
  714. done("unsupported");
  715. });
  716. });
  717. if (fullscreenResult === "entered") {
  718. await browser.pause(500);
  719. const sameVideoInFullscreen = await browser.execute(() => {
  720. const probeWindow = window as Window & { __zcodePreviewVideo?: HTMLVideoElement };
  721. const video = document.querySelector<HTMLVideoElement>("video[controls][playsinline]");
  722. return video === probeWindow.__zcodePreviewVideo && document.fullscreenElement === video;
  723. });
  724. expect(sameVideoInFullscreen).toBe(true);
  725. await browser.execute(() => {
  726. if (document.fullscreenElement) void document.exitFullscreen().catch(() => undefined);
  727. });
  728. }
  729. }
  730. async function assertSourcePreviewTargets() {
  731. // 整卡点击(标题区域透明按钮)与主按钮路径先后各验证一次,防止整卡可点回归退化为仅按钮可点。
  732. await clickPreviewCardBody(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  733. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  734. await closePreviewPane();
  735. await clickPreviewCard(basename(SOURCE_MARKDOWN_RELATIVE_PATH));
  736. await waitForPreviewRenderer(basename(SOURCE_MARKDOWN_RELATIVE_PATH), "markdown");
  737. await closePreviewPane();
  738. await clickPreviewCard(basename(SOURCE_HTML_RELATIVE_PATH));
  739. await waitForBrowserSurface(new URL(`file://${SOURCE_HTML_PATH}`).href, "APC05_HTML_PAGE");
  740. await closeSidePanes();
  741. }
  742. async function materializeOfficeFixtures() {
  743. const officeRoot = join(CASE_ROOT, "office");
  744. await mkdir(officeRoot, { recursive: true });
  745. await Promise.all(
  746. OFFICE_FILES.map((item) =>
  747. copyFile(join(OFFICE_FIXTURE_ROOT, item.fixture), join(officeRoot, item.name)),
  748. ),
  749. );
  750. }
  751. async function materializeMediaFixtures() {
  752. const mediaRoot = join(CASE_ROOT, "media");
  753. await mkdir(mediaRoot, { recursive: true });
  754. const videoFixture = await readFile(
  755. new URL("../fixtures/media/sample-video.mp4", import.meta.url),
  756. );
  757. const largeVideo = Buffer.concat([
  758. videoFixture,
  759. Buffer.alloc(Math.max(0, 8 * 1024 * 1024 + 1 - videoFixture.length)),
  760. ]);
  761. const wav = Buffer.alloc(45);
  762. wav.write("RIFF", 0, "ascii");
  763. wav.writeUInt32LE(37, 4);
  764. wav.write("WAVEfmt ", 8, "ascii");
  765. wav.writeUInt32LE(16, 16);
  766. wav.writeUInt16LE(1, 20);
  767. wav.writeUInt16LE(1, 22);
  768. wav.writeUInt32LE(8_000, 24);
  769. wav.writeUInt32LE(8_000, 28);
  770. wav.writeUInt16LE(1, 32);
  771. wav.writeUInt16LE(8, 34);
  772. wav.write("data", 36, "ascii");
  773. wav.writeUInt32LE(1, 40);
  774. wav[44] = 128;
  775. await Promise.all([
  776. writeFile(join(mediaRoot, "生成 视频.mp4"), largeVideo),
  777. writeFile(join(mediaRoot, "生成 音频.wav"), wav),
  778. ]);
  779. expect((await stat(join(mediaRoot, "生成 视频.mp4"))).size).toBeGreaterThan(8 * 1024 * 1024);
  780. }
  781. async function materializeStaleSourceFiles() {
  782. const staleRoot = join(CASE_ROOT, "stale");
  783. await mkdir(staleRoot, { recursive: true });
  784. await Promise.all([
  785. writeFile(join(staleRoot, "旧 页面.html"), "<p>stale html</p>", "utf8"),
  786. writeFile(join(staleRoot, "旧 说明.md"), "stale markdown", "utf8"),
  787. ]);
  788. }
  789. async function assertLocalMediaPreviewLogs(snapshot: Map<string, number>): Promise<void> {
  790. const runtimeLogDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR?.trim();
  791. if (!runtimeLogDir) {
  792. throw new Error("当前 E2E worker 没有配置 desktop runtime log 目录");
  793. }
  794. let desktopLogs = "";
  795. await browser.waitUntil(
  796. async () => {
  797. desktopLogs = await readDesktopRuntimeLogsSince(runtimeLogDir, snapshot);
  798. return (
  799. desktopLogs.includes("[rpc:call] media-preview.prepare OK") &&
  800. desktopLogs.includes("local media preview path authorization OK")
  801. );
  802. },
  803. {
  804. timeout: 30_000,
  805. interval: 250,
  806. timeoutMsg: `本地媒体预览日志没有完成: ${desktopLogs}`,
  807. },
  808. );
  809. expect(desktopLogs).not.toContain("[rpc:call] file.readMediaPreview");
  810. }
  811. async function snapshotDesktopRuntimeLogs(): Promise<Map<string, number>> {
  812. const runtimeLogDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR?.trim();
  813. if (!runtimeLogDir) {
  814. throw new Error("当前 E2E worker 没有配置 desktop runtime log 目录");
  815. }
  816. const entries = await readdir(runtimeLogDir, { withFileTypes: true }).catch(() => []);
  817. const snapshot = new Map<string, number>();
  818. await Promise.all(
  819. entries
  820. .filter((entry) => entry.isFile() && entry.name.endsWith(".log"))
  821. .map(async (entry) => {
  822. snapshot.set(entry.name, (await stat(join(runtimeLogDir, entry.name))).size);
  823. }),
  824. );
  825. return snapshot;
  826. }
  827. async function readDesktopRuntimeLogsSince(
  828. runtimeLogDir: string,
  829. snapshot: Map<string, number>,
  830. ): Promise<string> {
  831. const entries = await readdir(runtimeLogDir, { withFileTypes: true }).catch(() => []);
  832. const logFiles = entries
  833. .filter((entry) => entry.isFile() && entry.name.endsWith(".log"))
  834. .map((entry) => entry.name)
  835. .sort();
  836. const contents = await Promise.all(
  837. logFiles.map(async (fileName) => {
  838. const content = await readFile(join(runtimeLogDir, fileName));
  839. const offset = Math.min(snapshot.get(fileName) ?? 0, content.byteLength);
  840. return content.subarray(offset).toString("utf8");
  841. }),
  842. );
  843. return contents.join("\n");
  844. }
  845. async function materializeBoundFiles() {
  846. const boundsRoot = join(CASE_ROOT, "bounds");
  847. await mkdir(boundsRoot, { recursive: true });
  848. await Promise.all([
  849. ...Array.from({ length: 12 }, (_, index) =>
  850. writeFile(
  851. join(boundsRoot, `max-${String(index + 1).padStart(2, "0")}.pdf`),
  852. "exists",
  853. "utf8",
  854. ),
  855. ),
  856. writeFile(join(boundsRoot, "nofill-01.pdf"), "excluded existing candidate", "utf8"),
  857. ...Array.from({ length: 9 }, (_, index) =>
  858. writeFile(
  859. join(boundsRoot, `nofill-${String(index + 8).padStart(2, "0")}.pdf`),
  860. "exists",
  861. "utf8",
  862. ),
  863. ),
  864. ]);
  865. }
  866. async function closePreviewPane() {
  867. // Bug 根因:PreviewPane 自身没有关闭按钮,关闭动作属于外层 side-pane tab。
  868. // 必须关闭当前激活 tab 并等待旧 pane 卸载,否则下一次点击卡片仍会看到旧 renderer。
  869. const closed = await browser.execute(() => {
  870. const activeTab = document.querySelector<HTMLElement>("[data-side-pane-tab-id][data-active]");
  871. const closeButton = activeTab?.querySelector<HTMLButtonElement>("button");
  872. closeButton?.click();
  873. return Boolean(closeButton);
  874. });
  875. expect(closed).toBe(true);
  876. await browser.waitUntil(
  877. async () =>
  878. !(await browser.execute(
  879. (previewTestId) => Boolean(document.querySelector(`[data-testid="${previewTestId}"]`)),
  880. TID_PREVIEW_PANE,
  881. )),
  882. {
  883. timeout: 10_000,
  884. timeoutMsg: "Preview Pane 点击关闭后没有卸载",
  885. },
  886. );
  887. }
  888. async function closeSidePanes() {
  889. await browser.waitUntil(
  890. async () =>
  891. browser.execute(() => {
  892. const tab =
  893. document.querySelector<HTMLElement>("[data-side-pane-tab-id][data-active]") ??
  894. document.querySelector<HTMLElement>("[data-side-pane-tab-id]");
  895. const closeButton = tab?.querySelector<HTMLButtonElement>("button");
  896. if (!closeButton) return true;
  897. closeButton.click();
  898. return false;
  899. }),
  900. {
  901. interval: 100,
  902. timeout: 10_000,
  903. timeoutMsg: "Assistant Preview Cards 清理 side pane tabs 超时",
  904. },
  905. );
  906. }
  907. function createFixtureServer(): Server {
  908. return createServer((_request, response) => {
  909. response.setHeader("content-type", "text/html; charset=utf-8");
  910. response.end(
  911. "<!doctype html><html><head><title>APC01 Local Preview</title></head><body>APC01_LOCAL_URL_PAGE</body></html>",
  912. );
  913. });
  914. }
  915. async function listen(server: Server): Promise<string> {
  916. await new Promise<void>((resolveListen, rejectListen) => {
  917. server.once("error", rejectListen);
  918. server.listen(0, "127.0.0.1", () => {
  919. server.off("error", rejectListen);
  920. resolveListen();
  921. });
  922. });
  923. const address = server.address() as AddressInfo;
  924. return `http://127.0.0.1:${address.port}/assistant-preview`;
  925. }
  926. async function closeServer(server: Server | null) {
  927. if (!server) return;
  928. await new Promise<void>((resolveClose, rejectClose) => {
  929. server.close((error) => (error ? rejectClose(error) : resolveClose()));
  930. });
  931. }