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

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