conversation-session-message-image-gallery.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { ElectronMock } from "@wdio/electron-types";
  5. import { DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  6. import {
  7. getV4ComposerText,
  8. prepareV4ConversationE2E,
  9. sendV4Prompt,
  10. waitForV4AssistantMessageContaining,
  11. waitForV4Pane,
  12. waitForV4QueueCount,
  13. waitForV4TimelineContaining,
  14. } from "#e2e/helpers/v4-conversation";
  15. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  16. const CASE_NAME = "conversation-session-message-image-gallery";
  17. const MARKER = "E2E_MESSAGE_IMAGE_GALLERY";
  18. const IMAGE_DIR = join(DEFAULT_WORKSPACE, ".zcode-e2e", "message-image-gallery");
  19. const IMAGE_NAMES = ["one.svg", "two.svg", "three.svg", "standalone.svg"] as const;
  20. const SAVED_IMAGE_PATH = join(tmpdir(), `zcode-e2e-message-image-gallery-${Date.now()}.svg`);
  21. let replayServer: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>> | null =
  22. null;
  23. let showSaveDialogMock: ElectronMock | null = null;
  24. describe("会话区消息图片画廊与共享预览 E2E", () => {
  25. before(async function () {
  26. this.timeout(240000);
  27. await writeImageFixtures();
  28. replayServer = await startConversationModelProviderReplayServer(CASE_NAME);
  29. await prepareReplayConversation();
  30. await sendV4Prompt(`${MARKER}: 返回约定的 Markdown 图片布局。`);
  31. await browser.waitUntil(async () => (await getV4ComposerText()) === "", {
  32. timeout: 15000,
  33. timeoutMsg: "图片 gallery prompt 发送后输入框没有清空",
  34. });
  35. await waitForV4TimelineContaining(MARKER);
  36. await waitForV4AssistantMessageContaining(MARKER);
  37. await waitForV4Pane(
  38. (snapshot) => !snapshot.canStop && snapshot.sessionId !== "draft",
  39. "图片 gallery 消息完成后没有回到 idle",
  40. 90000,
  41. );
  42. await waitForV4QueueCount(0, 90000);
  43. await waitForImagesLoaded();
  44. });
  45. afterEach(async () => {
  46. // 断言失败会跳过用例末尾的关闭,残留独立图片会污染后续组内导航和下载。
  47. if ((await readPreview()).exists) await closePreview();
  48. });
  49. after(async () => {
  50. await browser.electron.restoreAllMocks();
  51. await rm(SAVED_IMAGE_PATH, { force: true });
  52. await replayServer?.stop();
  53. replayServer = null;
  54. });
  55. it("MIG01/MIG02: 单图与连续多图遵守共享桌面布局", async () => {
  56. const snapshot = await readGalleryLayout();
  57. expect(snapshot.galleryCount).toBe(1);
  58. expect(snapshot.groupedCount).toBe(3);
  59. expect(snapshot.standaloneCount).toBe(1);
  60. expect(snapshot.galleryHorizontalOverflow).toBe(false);
  61. expect(snapshot.documentHorizontalOverflow).toBe(false);
  62. expect(snapshot.groupedHeights.every((height) => height === 176)).toBe(true);
  63. expect(snapshot.radii.every((radius) => radius === "12px")).toBe(true);
  64. expect(snapshot.standaloneAtMostHalfWidth).toBe(true);
  65. await clickStandaloneThumbnail();
  66. expect((await readPreview()).alt).toBe("MIG standalone");
  67. expect((await readPreview()).zoom).toBe("100%");
  68. expect(await countPreviewNavigationButtons()).toBe(0);
  69. await closePreview();
  70. });
  71. it("MIG03: small 与 390px viewport 换成两列和单列且不横向滚动", async () => {
  72. try {
  73. // 原因:macOS 会按屏幕工作区截断原生窗口高度;响应式断言直接控制 renderer viewport。
  74. await setRendererViewport(700, 900);
  75. const small = await waitForResponsiveColumns(2);
  76. expect(small.galleryHorizontalOverflow).toBe(false);
  77. expect(small.documentHorizontalOverflow).toBe(false);
  78. await setRendererViewport(390, 844);
  79. const mobile = await waitForResponsiveColumns(1);
  80. expect(mobile.galleryHorizontalOverflow).toBe(false);
  81. expect(mobile.documentHorizontalOverflow).toBe(false);
  82. } finally {
  83. await clearRendererViewport();
  84. }
  85. });
  86. it("MIG04: 从第二张打开并使用按钮和键盘在组内循环导航", async () => {
  87. await clickGroupedThumbnail(1);
  88. expect((await readPreview()).alt).toBe("MIG two");
  89. expect((await readPreview()).zoom).toBe("100%");
  90. await clickButtonByLabels(["放大", "Zoom in"]);
  91. expect((await readPreview()).zoom).toBe("150%");
  92. await clickButtonByLabels(["下一张图片", "Next image"]);
  93. expect((await readPreview()).alt).toBe("MIG three");
  94. expect((await readPreview()).zoom).toBe("100%");
  95. await browser.keys("ArrowRight");
  96. expect((await readPreview()).alt).toBe("MIG one");
  97. await browser.keys("ArrowLeft");
  98. expect((await readPreview()).alt).toBe("MIG three");
  99. expect((await readPreview()).zoom).toBe("100%");
  100. await closePreview();
  101. });
  102. it("MIG05/MIG07: 本地图片可缩放拖拽,关闭后恢复原缩略图焦点", async () => {
  103. const source = await readFile(join(IMAGE_DIR, "one.svg"), "utf8");
  104. const renderedSource = await readGroupedThumbnailSource(0);
  105. expect(renderedSource).toBe(
  106. `data:image/svg+xml;base64,${Buffer.from(source).toString("base64")}`,
  107. );
  108. await clickGroupedThumbnail(0);
  109. await clickButtonByLabels(["放大", "Zoom in"]);
  110. await clickButtonByLabels(["放大", "Zoom in"]);
  111. const zoomed = await readPreview();
  112. expect(zoomed.zoom).toBe("200%");
  113. await dragPreview(120, 80);
  114. const dragged = await readPreview();
  115. expect(dragged.transform).not.toBe(zoomed.transform);
  116. await browser.keys("Escape");
  117. await waitForPreviewClosed();
  118. await browser.waitUntil(
  119. async () =>
  120. browser.execute(() => {
  121. const focused = document.activeElement;
  122. return (
  123. Array.from(
  124. document.querySelectorAll<HTMLButtonElement>(
  125. "[data-markdown-image-gallery] [data-markdown-image-trigger]",
  126. ),
  127. ).indexOf(focused as HTMLButtonElement) === 0
  128. );
  129. }),
  130. {
  131. timeout: 10000,
  132. timeoutMsg: "关闭预览后焦点没有回到原 Markdown 缩略图",
  133. },
  134. );
  135. });
  136. it("MIG08: 下载当前本地预览图片通过 native Save As 原样落盘", async () => {
  137. showSaveDialogMock = await browser.electron.mock("dialog", "showSaveDialog");
  138. await showSaveDialogMock.mockResolvedValueOnce({
  139. canceled: false,
  140. filePath: SAVED_IMAGE_PATH,
  141. });
  142. await clickGroupedThumbnail(0);
  143. await clickButtonByLabels(["下载图片", "Download image"]);
  144. await browser.waitUntil(
  145. async () => {
  146. try {
  147. return (await readFile(SAVED_IMAGE_PATH, "utf8")).includes("one.svg");
  148. } catch {
  149. return false;
  150. }
  151. },
  152. { timeout: 15000, timeoutMsg: "native Save As 没有写出当前预览 SVG" },
  153. );
  154. expect(await readFile(SAVED_IMAGE_PATH, "utf8")).toBe(
  155. await readFile(join(IMAGE_DIR, "one.svg"), "utf8"),
  156. );
  157. await closePreview();
  158. await rm(SAVED_IMAGE_PATH, { force: true });
  159. await showSaveDialogMock.mockResolvedValueOnce({
  160. canceled: true,
  161. filePath: "",
  162. });
  163. await clickGroupedThumbnail(0);
  164. await clickButtonByLabels(["下载图片", "Download image"]);
  165. await browser.pause(500);
  166. await expectFileMissing(SAVED_IMAGE_PATH);
  167. await closePreview();
  168. });
  169. });
  170. async function prepareReplayConversation() {
  171. await prepareV4ConversationE2E();
  172. }
  173. async function setRendererViewport(width: number, height: number) {
  174. // 桌面 BrowserWindow 的产品最小宽度是 480px;390px case 验证的是共享
  175. // renderer 响应式 CSS,因此用 CDP 模拟 viewport,不篡改桌面窗口产品约束。
  176. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  177. deviceScaleFactor: 1,
  178. height,
  179. mobile: false,
  180. width,
  181. });
  182. await browser.waitUntil(
  183. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  184. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  185. );
  186. }
  187. async function clearRendererViewport() {
  188. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  189. }
  190. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  191. const sent = await browser.electron.execute(
  192. async (electron, command, commandParams) => {
  193. const window = electron.BrowserWindow.getAllWindows().find(
  194. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  195. );
  196. if (!window) return false;
  197. const devtools = window.webContents.debugger;
  198. if (!devtools.isAttached()) devtools.attach("1.3");
  199. await devtools.sendCommand(command, commandParams);
  200. return true;
  201. },
  202. method,
  203. params,
  204. );
  205. if (!sent) throw new Error(`没有找到可执行 ${method} 的 Electron 窗口`);
  206. }
  207. async function writeImageFixtures() {
  208. await mkdir(IMAGE_DIR, { recursive: true });
  209. const colors = ["#ef4444", "#22c55e", "#3b82f6", "#a855f7"];
  210. await Promise.all(
  211. IMAGE_NAMES.map((name, index) =>
  212. writeFile(
  213. join(IMAGE_DIR, name),
  214. `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800"><rect width="1200" height="800" fill="${colors[index]}"/><text x="80" y="420" font-size="96" fill="white">${name}</text></svg>`,
  215. "utf8",
  216. ),
  217. ),
  218. );
  219. }
  220. async function waitForImagesLoaded() {
  221. await browser.waitUntil(
  222. async () =>
  223. browser.execute(() => {
  224. const images = Array.from(
  225. document.querySelectorAll<HTMLImageElement>("img[data-markdown-image]"),
  226. ).filter((image) => image.alt.startsWith("MIG "));
  227. return (
  228. images.length === 4 &&
  229. images.every((image) => image.complete && image.naturalWidth === 1200)
  230. );
  231. }),
  232. { timeout: 30000, timeoutMsg: "Markdown 本地图片没有全部加载完成" },
  233. );
  234. }
  235. async function readGroupedThumbnailSource(index: number) {
  236. return browser.execute((targetIndex) => {
  237. const images = Array.from(
  238. document.querySelectorAll<HTMLImageElement>(
  239. "[data-markdown-image-gallery] img[data-markdown-image]",
  240. ),
  241. );
  242. return images[targetIndex]?.src ?? "";
  243. }, index);
  244. }
  245. async function readGalleryLayout() {
  246. return browser.execute(() => {
  247. const gallery = document.querySelector<HTMLElement>("[data-markdown-image-gallery]");
  248. const grouped = Array.from(
  249. gallery?.querySelectorAll<HTMLButtonElement>("[data-markdown-image-trigger]") ?? [],
  250. );
  251. const all = Array.from(
  252. document.querySelectorAll<HTMLButtonElement>("[data-markdown-image-trigger]"),
  253. ).filter((button) => button.querySelector("img")?.getAttribute("alt")?.startsWith("MIG "));
  254. const standalone = all.filter((button) => !button.closest("[data-markdown-image-gallery]"));
  255. const galleryRect = gallery?.getBoundingClientRect();
  256. return {
  257. galleryCount: document.querySelectorAll("[data-markdown-image-gallery]").length,
  258. groupedCount: grouped.length,
  259. standaloneCount: standalone.length,
  260. groupedHeights: grouped.map((button) => Math.round(button.getBoundingClientRect().height)),
  261. radii: all.map(
  262. (button) => getComputedStyle(button.querySelector("img") as HTMLImageElement).borderRadius,
  263. ),
  264. standaloneAtMostHalfWidth: standalone.every(
  265. (button) => button.getBoundingClientRect().width <= (galleryRect?.width ?? 0) / 2 + 1,
  266. ),
  267. galleryHorizontalOverflow: Boolean(gallery && gallery.scrollWidth > gallery.clientWidth + 1),
  268. documentHorizontalOverflow:
  269. document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
  270. };
  271. });
  272. }
  273. async function waitForResponsiveColumns(expectedColumns: number) {
  274. let latest = {
  275. columns: 0,
  276. galleryHorizontalOverflow: true,
  277. documentHorizontalOverflow: true,
  278. };
  279. await browser.waitUntil(
  280. async () => {
  281. latest = await browser.execute(() => {
  282. const gallery = document.querySelector<HTMLElement>("[data-markdown-image-gallery]");
  283. const triggers = Array.from(
  284. gallery?.querySelectorAll<HTMLElement>("[data-markdown-image-trigger]") ?? [],
  285. );
  286. const columns = new Set(triggers.map((item) => Math.round(item.getBoundingClientRect().x)))
  287. .size;
  288. return {
  289. columns,
  290. galleryHorizontalOverflow: Boolean(
  291. gallery && gallery.scrollWidth > gallery.clientWidth + 1,
  292. ),
  293. documentHorizontalOverflow:
  294. document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
  295. };
  296. });
  297. return latest.columns === expectedColumns;
  298. },
  299. {
  300. timeout: 15000,
  301. timeoutMsg: `图片 gallery 没有收敛到 ${expectedColumns} 列: ${JSON.stringify(latest)}`,
  302. },
  303. );
  304. return latest;
  305. }
  306. async function clickGroupedThumbnail(index: number) {
  307. const clicked = await browser.execute((targetIndex) => {
  308. const buttons = Array.from(
  309. document.querySelectorAll<HTMLButtonElement>(
  310. "[data-markdown-image-gallery] [data-markdown-image-trigger]",
  311. ),
  312. );
  313. buttons[targetIndex]?.click();
  314. return Boolean(buttons[targetIndex]);
  315. }, index);
  316. expect(clicked).toBe(true);
  317. await browser.waitUntil(async () => (await readPreview()).exists, {
  318. timeout: 10000,
  319. timeoutMsg: "共享图片预览没有打开",
  320. });
  321. }
  322. async function clickStandaloneThumbnail() {
  323. const clicked = await browser.execute(() => {
  324. const button = Array.from(
  325. document.querySelectorAll<HTMLButtonElement>("[data-markdown-image-trigger]"),
  326. ).find(
  327. (candidate) =>
  328. !candidate.closest("[data-markdown-image-gallery]") &&
  329. candidate.querySelector("img")?.getAttribute("alt") === "MIG standalone",
  330. );
  331. button?.click();
  332. return Boolean(button);
  333. });
  334. expect(clicked).toBe(true);
  335. await browser.waitUntil(async () => (await readPreview()).exists, {
  336. timeout: 10000,
  337. timeoutMsg: "独立图片预览没有打开",
  338. });
  339. }
  340. async function countPreviewNavigationButtons() {
  341. return browser.execute(() => {
  342. const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
  343. return Array.from(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? []).filter(
  344. (button) =>
  345. /^(Previous image|Next image|上一张图片|下一张图片)$/u.test(
  346. button.getAttribute("aria-label") ?? "",
  347. ),
  348. ).length;
  349. });
  350. }
  351. async function readPreview() {
  352. return browser.execute(() => {
  353. const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
  354. const image = dialog?.querySelector<HTMLImageElement>("img");
  355. // 百分比已改为可重置缩放的按钮;旧 span 选择器会把正常缩放误报为空。
  356. const zoom =
  357. dialog
  358. ?.querySelector<HTMLButtonElement>('button[title="重置缩放"], button[title="Reset zoom"]')
  359. ?.textContent?.trim() ?? "";
  360. return {
  361. alt: image?.alt ?? "",
  362. exists: Boolean(dialog && image),
  363. transform:
  364. dialog?.querySelector<HTMLElement>("[data-image-preview-surface]")?.style.transform ?? "",
  365. zoom,
  366. };
  367. });
  368. }
  369. async function clickButtonByLabels(labels: string[]) {
  370. let latest: string[] = [];
  371. await browser.waitUntil(
  372. async () => {
  373. const result = await browser.execute((expectedLabels) => {
  374. const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
  375. const buttons = Array.from(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? []);
  376. const labels = buttons.map((button) => button.getAttribute("aria-label") ?? "");
  377. const target = buttons.find((button) =>
  378. expectedLabels.includes(button.getAttribute("aria-label") ?? ""),
  379. );
  380. target?.click();
  381. return { clicked: Boolean(target), labels };
  382. }, labels);
  383. latest = result.labels;
  384. return result.clicked;
  385. },
  386. {
  387. timeout: 10000,
  388. timeoutMsg: `共享预览没有找到按钮 ${labels.join("/")}: ${latest.join(", ")}`,
  389. },
  390. );
  391. }
  392. async function dragPreview(deltaX: number, deltaY: number) {
  393. const image = await $('[role="dialog"] img');
  394. const location = await image.getLocation();
  395. const size = await image.getSize();
  396. await browser.performActions([
  397. {
  398. type: "pointer",
  399. id: "mouse",
  400. parameters: { pointerType: "mouse" },
  401. actions: [
  402. {
  403. type: "pointerMove",
  404. duration: 0,
  405. origin: "viewport",
  406. x: Math.round(location.x + size.width / 2),
  407. y: Math.round(location.y + size.height / 2),
  408. },
  409. { type: "pointerDown", button: 0 },
  410. {
  411. type: "pointerMove",
  412. duration: 300,
  413. origin: "pointer",
  414. x: deltaX,
  415. y: deltaY,
  416. },
  417. { type: "pointerUp", button: 0 },
  418. ],
  419. },
  420. ]);
  421. await browser.releaseActions();
  422. }
  423. async function closePreview() {
  424. await browser.keys("Escape");
  425. await waitForPreviewClosed();
  426. }
  427. async function waitForPreviewClosed() {
  428. await browser.waitUntil(async () => !(await readPreview()).exists, {
  429. timeout: 10000,
  430. timeoutMsg: "共享图片预览没有关闭",
  431. });
  432. }
  433. async function expectFileMissing(path: string) {
  434. let exists = true;
  435. try {
  436. await readFile(path);
  437. } catch {
  438. exists = false;
  439. }
  440. expect(exists).toBe(false);
  441. }