conversation-session-v4-attachment-layout.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. import {
  2. TID_V4_ATTACHMENT,
  3. TID_V4_COMPOSER,
  4. TID_V4_COMPOSER_INPUT,
  5. TID_V4_ROW_ATTACHMENTS,
  6. } from "@zcode/shared/test-ids";
  7. import { clearAppData } from "#e2e/helpers/desktop-app";
  8. import {
  9. beginFirstV4UserQueryEdit,
  10. clickV4Send,
  11. pasteV4ComposerFileAttachment,
  12. prepareV4ConversationE2E,
  13. setV4ComposerText,
  14. waitForV4Pane,
  15. waitForV4TimelineContaining,
  16. } from "#e2e/helpers/v4-conversation";
  17. const MARKER = "E2E_ATTACHMENT_LAYOUT_VISIBLE";
  18. const LONG_FILE = "e2e-attachment-layout-a-very-long-filename-for-truncation.txt";
  19. const SECOND_FILE = "e2e-attachment-layout-second.txt";
  20. const IMAGE_FILE = "e2e-attachment-layout-image.png";
  21. const FAILED_IMAGE_FILE = "e2e-attachment-layout-failed.png";
  22. const FAILED_IMAGE_MARKER = "E2E_ATTACHMENT_FAILED_IMAGE";
  23. const FAILED_IMAGE_PNG_BASE64 =
  24. "iVBORw0KGgoAAAANSUhEUgAAAEAAAAAgCAYAAACinX6EAAAATUlEQVR4AeXBMQEAIAzAsK43KlCBf2NMSJM5933CJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJE7iJG4B7pwBpTup40wAAAAASUVORK5CYII=";
  25. const FAILED_IMAGE_BLOB_SIZE = 134;
  26. describe("AL01-AL20:附件界面改版", () => {
  27. after(async () => {
  28. await restoreObjectUrlFactory().catch(() => {});
  29. await clearRendererEmulation();
  30. await browser.electron.restoreAllMocks();
  31. await clearAppData();
  32. });
  33. it("Composer → sent → edit 覆盖附件结构、context、响应式、主题与序列化", async function () {
  34. this.timeout(180_000);
  35. await prepareV4ConversationE2E();
  36. await setV4ComposerText(
  37. `${MARKER}\n\n# userselect:\n\`\`\`userselect\n[{"text":"E2E selection"}]\n\`\`\``,
  38. );
  39. // 故意先加文件再加媒体,产品展示仍必须按“媒体 → 文件”分层;同类文件保持添加顺序。
  40. await pasteV4ComposerFileAttachment(LONG_FILE, {
  41. base64: "Zmlyc3Q=",
  42. mimeType: "application/octet-stream",
  43. });
  44. await pasteV4ComposerFileAttachment(IMAGE_FILE);
  45. await pasteV4ComposerFileAttachment(SECOND_FILE, {
  46. base64: "c2Vjb25k",
  47. mimeType: "application/octet-stream",
  48. });
  49. await dispatchComposerContexts();
  50. const composer = await waitForComposerLayout();
  51. expect(composer.kinds).toEqual(["image", "file", "file"]);
  52. expect(composer.filenames).toEqual([IMAGE_FILE, LONG_FILE, SECOND_FILE]);
  53. expect(composer.mediaSize).toEqual({ height: 48, width: 48 });
  54. expect(composer.fileHeights.every((height) => height === 48)).toBe(true);
  55. expect(composer.longFileTitle).toBe(LONG_FILE);
  56. expect(composer.longFileTruncated).toBe(true);
  57. expect(composer.contextLabels).toHaveLength(3);
  58. expect(composer.hasSeparateContextRow).toBe(true);
  59. await assertComposerRemoveVisibility();
  60. await assertContextHoverAlignment("composer");
  61. await assertThemeSurfaces();
  62. await assertNarrowComposerWrap();
  63. await clickV4Send();
  64. await waitForV4TimelineContaining("V4_ATTACHMENT_LAYOUT_SEND_OK", 45_000);
  65. await waitForV4Pane(
  66. (state) => !state.canStop && state.sessionId !== null && state.sessionId !== "draft",
  67. "附件布局首发后没有回到 idle",
  68. 45_000,
  69. );
  70. const sent = await waitForSentLayout();
  71. expect(sent.areaBeforeBubble).toBe(true);
  72. expect(sent.areaInsideBubble).toBe(false);
  73. expect(sent.mediaBeforePills).toBe(true);
  74. expect(sent.mediaKinds).toEqual(["image"]);
  75. expect(sent.fileNames).toEqual([LONG_FILE, SECOND_FILE]);
  76. expect(sent.filePillsAreRoundAndBorderless).toBe(true);
  77. expect(sent.pillOrder).toEqual(["file", "file", "comment", "web", "pptx", "selection"]);
  78. expect(sent.rightEdgesAligned).toBe(true);
  79. expect(sent.bubbleWidth).toBeLessThan(sent.rowWidth - 8);
  80. expect(sent.emptyUserRows).toBe(0);
  81. await assertContextHoverAlignment("sent");
  82. await assertNarrowSentWrap();
  83. await assertDesktopAndTouchActions();
  84. // composer 编辑态载入原附件与上下文 chip,复用 composer 的 48px 卡片(AL13)。
  85. await beginFirstV4UserQueryEdit(MARKER);
  86. const edit = await waitForEditLayout();
  87. expect(edit.attachmentKinds).toEqual(["image", "file", "file"]);
  88. expect(edit.attachmentHeights.every((height) => height === 48)).toBe(true);
  89. expect(edit.contextCount).toBe(4);
  90. expect(edit.visibleText).toBe(MARKER);
  91. expect(edit.containsProtocolText).toBe(false);
  92. await removeEditWebContext();
  93. await clickV4Send();
  94. await waitForV4TimelineContaining("V4_ATTACHMENT_LAYOUT_EDIT_OK", 45_000);
  95. const edited = await waitForSentLayout();
  96. expect(edited.pillOrder).toEqual(["file", "file", "comment", "pptx", "selection"]);
  97. // 仅 context 的消息不渲染空气泡;同时证明协议正文不会泄漏到可见消息。
  98. await setV4ComposerText(
  99. '# userselect:\n```userselect\n[{"text":"E2E_ATTACHMENT_CONTEXT_ONLY"}]\n```',
  100. );
  101. await clickV4Send();
  102. await waitForV4TimelineContaining("V4_ATTACHMENT_CONTEXT_ONLY_OK", 45_000);
  103. const contextOnly = await readLastUserRowStructure();
  104. expect(contextOnly.hasAttachmentArea).toBe(true);
  105. expect(contextOnly.hasBubble).toBe(false);
  106. expect(contextOnly.text).not.toContain("# userselect:");
  107. // 缩略图读取成功、但 renderer 无法建立 Blob URL 时必须降级为静态占位,
  108. // 并从当前消息的 gallery 中排除,避免展示无效点击入口。
  109. await setV4ComposerText(FAILED_IMAGE_MARKER);
  110. await pasteV4ComposerFileAttachment(FAILED_IMAGE_FILE, {
  111. pngBase64: FAILED_IMAGE_PNG_BASE64,
  112. });
  113. await waitForComposerMediaReady(FAILED_IMAGE_FILE);
  114. await installImageObjectUrlFailureForBlobSize(FAILED_IMAGE_BLOB_SIZE);
  115. await clickV4Send();
  116. await waitForV4TimelineContaining("V4_ATTACHMENT_FAILED_IMAGE_OK", 45_000);
  117. await waitForV4Pane((state) => !state.canStop, "失败图片 case 发送后没有回到 idle", 45_000);
  118. const failedImage = await waitForFailedSentImage();
  119. expect(failedImage.role).toBeNull();
  120. expect(failedImage.title).not.toBe("");
  121. expect(failedImage.hasImage).toBe(false);
  122. await restoreObjectUrlFactory();
  123. // 第一条消息只有一个可预览媒体;后续消息即使也含媒体,gallery 也不得跨消息拼接。
  124. await openFirstSentImage();
  125. const gallery = await readOpenGalleryState();
  126. expect(gallery.title).toBe(IMAGE_FILE);
  127. expect(gallery.hasPrevious).toBe(false);
  128. expect(gallery.hasNext).toBe(false);
  129. await browser.keys("Escape");
  130. });
  131. });
  132. async function dispatchComposerContexts(): Promise<void> {
  133. const dispatched = await browser.execute(() => {
  134. const tabState = (
  135. window as typeof window & {
  136. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath?: string } };
  137. }
  138. ).__zcodeTabStoreE2E?.getState();
  139. const workspacePath = tabState?.activeWorkspacePath;
  140. if (!workspacePath) return false;
  141. window.dispatchEvent(
  142. new CustomEvent("zcode:code-comment-add-to-chat", {
  143. cancelable: true,
  144. detail: {
  145. id: "e2e-comment",
  146. workspacePath,
  147. sourcePath: `${workspacePath}/src/app.ts`,
  148. sourceTitle: "app.ts",
  149. selectedText: "const answer = 42",
  150. comment: "E2E comment",
  151. startLine: 1,
  152. endLine: 1,
  153. },
  154. }),
  155. );
  156. window.dispatchEvent(
  157. new CustomEvent("zcode:web-element-context-add-to-chat", {
  158. detail: {
  159. id: "e2e-web",
  160. workspacePath,
  161. pageUrl: "https://e2e.example.test/page",
  162. pageTitle: "E2E Docs",
  163. tagName: "button",
  164. text: "Submit",
  165. capturedAt: Date.now(),
  166. },
  167. }),
  168. );
  169. window.dispatchEvent(
  170. new CustomEvent("zcode:pptx-element-reference-add-to-chat", {
  171. detail: {
  172. id: "e2e-pptx",
  173. workspacePath,
  174. sourcePath: `${workspacePath}/deck.pptx`,
  175. sourceTitle: "deck.pptx",
  176. sourceFingerprint: `sha256:${"a".repeat(64)}`,
  177. slideIndex: 0,
  178. slidePart: "ppt/slides/slide1.xml",
  179. nodeId: "7",
  180. nodeName: "Title",
  181. nodeType: "shape",
  182. bounds: { x: 0, y: 0, width: 100, height: 30 },
  183. zIndex: 1,
  184. capturedAt: Date.now(),
  185. },
  186. }),
  187. );
  188. return true;
  189. });
  190. expect(dispatched).toBe(true);
  191. }
  192. async function waitForComposerMediaReady(filename: string): Promise<void> {
  193. await browser.waitUntil(
  194. () =>
  195. browser.execute((targetFilename) => {
  196. const image = Array.from(
  197. document.querySelectorAll<HTMLImageElement>(
  198. '[data-composer-attachment-kind="image"][data-upload-status="ready"] img[alt]',
  199. ),
  200. ).find((candidate) => candidate.alt === targetFilename);
  201. return Boolean(image?.src.startsWith("blob:"));
  202. }, filename),
  203. {
  204. timeout: 15000,
  205. // Bug 原因:paste 事件只保证进入异步上传流程;若过早安装 createObjectURL mock,
  206. // composer 自己会先消费故障,sent row 的缩略图重建反而不会失败。
  207. timeoutMsg: `目标图片在 composer 中没有完成 Blob 缩略图与上传:${filename}`,
  208. },
  209. );
  210. }
  211. async function waitForComposerLayout() {
  212. let snapshot = await readComposerLayout();
  213. await browser.waitUntil(
  214. async () => {
  215. snapshot = await readComposerLayout();
  216. return snapshot.kinds.length === 3 && snapshot.contextLabels.length === 3;
  217. },
  218. { timeout: 30_000, timeoutMsg: "Composer 附件与 context 没有收敛" },
  219. );
  220. return snapshot;
  221. }
  222. function readComposerLayout() {
  223. return browser.execute(
  224. (imageFile, longFile, secondFile) => {
  225. const row = document.querySelector<HTMLElement>("[data-composer-file-attachments-row]");
  226. const contextRow = document.querySelector<HTMLElement>(
  227. "[data-composer-context-attachments-row]",
  228. );
  229. const cards = Array.from(row?.children ?? []) as HTMLElement[];
  230. const media = cards.find((card) => card.dataset.composerAttachmentKind === "image");
  231. const files = cards.filter((card) => card.dataset.composerAttachmentKind === "file");
  232. const longName = files.find((file) => file.textContent?.includes("a-very-long-filename"));
  233. const longLabel = longName?.querySelector<HTMLElement>("[title]");
  234. return {
  235. contextLabels: Array.from(contextRow?.children ?? []).map(
  236. (item) => item.getAttribute("aria-label") ?? "",
  237. ),
  238. fileHeights: files.map((file) => Math.round(file.getBoundingClientRect().height)),
  239. filenames: cards.map(
  240. (card) =>
  241. [imageFile, longFile, secondFile].find(
  242. (filename) =>
  243. card.querySelector<HTMLImageElement>("img[alt]")?.alt === filename ||
  244. card.textContent?.includes(filename),
  245. ) ?? "",
  246. ),
  247. hasSeparateContextRow: Boolean(
  248. row && contextRow && row.parentElement === contextRow.parentElement,
  249. ),
  250. kinds: cards.map((card) => card.dataset.composerAttachmentKind ?? ""),
  251. longFileTitle: longLabel?.getAttribute("title") ?? "",
  252. longFileTruncated: Boolean(longLabel && longLabel.scrollWidth > longLabel.clientWidth),
  253. mediaSize: media
  254. ? {
  255. height: Math.round(media.getBoundingClientRect().height),
  256. width: Math.round(media.getBoundingClientRect().width),
  257. }
  258. : null,
  259. };
  260. },
  261. IMAGE_FILE,
  262. LONG_FILE,
  263. SECOND_FILE,
  264. );
  265. }
  266. async function assertComposerRemoveVisibility() {
  267. const first = await $("[data-composer-attachment-kind] [data-composer-attachment-remove]");
  268. await first.waitForExist({ timeout: 15_000 });
  269. expect(Number(await first.getCSSProperty("opacity").then((value) => value.value))).toBe(0);
  270. await first.moveTo();
  271. const card = await first.parentElement();
  272. await card.moveTo();
  273. await browser.waitUntil(
  274. async () => Number(await first.getCSSProperty("opacity").then((value) => value.value)) === 1,
  275. { timeout: 5_000, timeoutMsg: "桌面 hover 后删除按钮没有显示" },
  276. );
  277. await browser.execute((element) => (element as HTMLElement).focus(), first);
  278. expect(Number(await first.getCSSProperty("opacity").then((value) => value.value))).toBe(1);
  279. await sendRendererEmulationCommand("Emulation.setTouchEmulationEnabled", {
  280. enabled: true,
  281. maxTouchPoints: 1,
  282. });
  283. await browser.waitUntil(
  284. async () => browser.execute(() => window.matchMedia("(hover: none)").matches),
  285. { timeout: 5_000, timeoutMsg: "renderer 没有进入 touch/hover:none 模式" },
  286. );
  287. expect(Number(await first.getCSSProperty("opacity").then((value) => value.value))).toBe(1);
  288. await sendRendererEmulationCommand("Emulation.setTouchEmulationEnabled", { enabled: false });
  289. }
  290. async function assertThemeSurfaces() {
  291. for (const theme of ["zai-light", "zai-dark"] as const) {
  292. const changed = await browser.execute((nextTheme) => {
  293. const setTheme = (window as typeof window & { __testActions?: Record<string, unknown> })
  294. .__testActions?.setTheme;
  295. if (typeof setTheme !== "function") return false;
  296. (setTheme as (value: string) => void)(nextTheme);
  297. return true;
  298. }, theme);
  299. expect(changed).toBe(true);
  300. await browser.waitUntil(
  301. () =>
  302. browser.execute(() => {
  303. const card = document.querySelector<HTMLElement>("[data-composer-attachment-kind]");
  304. const pill = document.querySelector<HTMLElement>(
  305. "[data-composer-context-attachments-row] > [role='button']",
  306. );
  307. return [card, pill].every((element) => {
  308. if (!element) return false;
  309. const color = getComputedStyle(element).backgroundColor;
  310. return color !== "rgba(0, 0, 0, 0)" && color !== "transparent";
  311. });
  312. }),
  313. { timeout: 5_000, timeoutMsg: `${theme} 附件 surface 不可见` },
  314. );
  315. }
  316. }
  317. async function assertNarrowComposerWrap() {
  318. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  319. deviceScaleFactor: 1,
  320. height: 800,
  321. mobile: false,
  322. width: 520,
  323. });
  324. await browser.waitUntil(() => browser.execute(() => window.innerWidth === 520), {
  325. timeout: 5_000,
  326. timeoutMsg: "窄 viewport 未生效",
  327. });
  328. const state = await browser.execute(() => {
  329. const rows = [
  330. document.querySelector<HTMLElement>("[data-composer-file-attachments-row]"),
  331. document.querySelector<HTMLElement>("[data-composer-context-attachments-row]"),
  332. ];
  333. return {
  334. noDocumentOverflow:
  335. document.documentElement.scrollWidth <= document.documentElement.clientWidth,
  336. rowsContainedByComposer: rows.every((row) => {
  337. const composer = row?.closest("form")?.getBoundingClientRect();
  338. const rect = row?.getBoundingClientRect();
  339. return Boolean(
  340. composer && rect && rect.left >= composer.left - 1 && rect.right <= composer.right + 1,
  341. );
  342. }),
  343. };
  344. });
  345. expect(state).toEqual({ noDocumentOverflow: true, rowsContainedByComposer: true });
  346. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  347. }
  348. async function waitForSentLayout() {
  349. let snapshot = await readSentLayout();
  350. await browser.waitUntil(
  351. async () => {
  352. snapshot = await readSentLayout();
  353. return snapshot.pillOrder.includes("selection") && snapshot.mediaKinds.length > 0;
  354. },
  355. { timeout: 30_000, timeoutMsg: "sent 附件布局没有收敛" },
  356. );
  357. return snapshot;
  358. }
  359. function readSentLayout() {
  360. return browser.execute(
  361. (prefix, longFile, secondFile) => {
  362. const areas = Array.from(
  363. document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}-"]`),
  364. );
  365. const area = areas.find((item) =>
  366. item.querySelector("[data-v4-user-input-media-attachments]"),
  367. );
  368. const row = area?.parentElement;
  369. const bubble = row?.querySelector<HTMLElement>("[data-v4-user-input-bubble]");
  370. const media = area?.querySelector<HTMLElement>("[data-v4-user-input-media-attachments]");
  371. const pills = area?.querySelector<HTMLElement>("[data-v4-user-input-attachment-pills]");
  372. const pillChildren = Array.from(pills?.children ?? []) as HTMLElement[];
  373. const classify = (item: HTMLElement) => {
  374. if (item.dataset.v4UserInputAttachmentPill === "true") return "file";
  375. const label = item.getAttribute("aria-label") ?? "";
  376. if (/comment|评论/iu.test(label)) return "comment";
  377. if (/web|网页/iu.test(label)) return "web";
  378. if (/slide|幻灯片/iu.test(label)) return "pptx";
  379. // f6e0c28998:选区 chip 文案由「N 条对话引用」改为「N 条注释」/ "N annotations"。
  380. if (/annotation|注释/iu.test(label)) return "selection";
  381. return "unknown";
  382. };
  383. const filePills = pillChildren.filter((item) => classify(item) === "file");
  384. const areaRect = area?.getBoundingClientRect();
  385. const bubbleRect = bubble?.getBoundingClientRect();
  386. const rowRect = row?.getBoundingClientRect();
  387. return {
  388. areaBeforeBubble: Boolean(
  389. area && bubble && area.compareDocumentPosition(bubble) & Node.DOCUMENT_POSITION_FOLLOWING,
  390. ),
  391. areaInsideBubble: Boolean(area && bubble?.contains(area)),
  392. emptyUserRows: Array.from(document.querySelectorAll<HTMLElement>("[data-v4-row-id]"))
  393. .filter((candidate) => candidate.classList.contains("group/user-row"))
  394. .filter(
  395. (candidate) =>
  396. !candidate.querySelector(
  397. "[data-v4-user-input-attachments], [data-v4-user-input-bubble]",
  398. ),
  399. ).length,
  400. fileNames: filePills
  401. .map((pill) => pill.textContent ?? "")
  402. .flatMap((text) => [longFile, secondFile].filter((name) => text.includes(name))),
  403. filePillsAreRoundAndBorderless: filePills.every((pill) => {
  404. const style = getComputedStyle(pill);
  405. return (
  406. parseFloat(style.borderRadius) >= 999 ||
  407. (style.borderStyle === "none" && parseFloat(style.borderRadius) >= 16)
  408. );
  409. }),
  410. mediaBeforePills: Boolean(
  411. media && pills && media.compareDocumentPosition(pills) & Node.DOCUMENT_POSITION_FOLLOWING,
  412. ),
  413. mediaKinds: Array.from(media?.children ?? []).map((item) =>
  414. item.querySelector("video") ? "video" : "image",
  415. ),
  416. bubbleWidth: bubbleRect?.width ?? 0,
  417. pillOrder: pillChildren.map(classify).filter((kind) => kind !== "unknown"),
  418. rightEdgesAligned: Boolean(
  419. areaRect && bubbleRect && Math.abs(areaRect.right - bubbleRect.right) <= 2,
  420. ),
  421. rowWidth: rowRect?.width ?? 0,
  422. };
  423. },
  424. TID_V4_ROW_ATTACHMENTS,
  425. LONG_FILE,
  426. SECOND_FILE,
  427. );
  428. }
  429. async function assertContextHoverAlignment(surface: "composer" | "sent") {
  430. const selector =
  431. surface === "composer"
  432. ? "[data-composer-context-attachments-row] > [role='button']"
  433. : "[data-v4-user-input-attachment-pills] > [role='button']";
  434. const trigger = await $(selector);
  435. await trigger.waitForExist({ timeout: 15_000 });
  436. await trigger.moveTo();
  437. const content = await $("[data-slot='hover-card-content']");
  438. await content.waitForDisplayed({ timeout: 5_000 });
  439. const [triggerRect, contentRect] = await Promise.all([
  440. trigger
  441. .getElement()
  442. .then((element) => browser.execute((item) => item.getBoundingClientRect().toJSON(), element)),
  443. content
  444. .getElement()
  445. .then((element) => browser.execute((item) => item.getBoundingClientRect().toJSON(), element)),
  446. ]);
  447. if (surface === "composer")
  448. expect(Math.abs(triggerRect.left - contentRect.left)).toBeLessThanOrEqual(3);
  449. else expect(Math.abs(triggerRect.right - contentRect.right)).toBeLessThanOrEqual(3);
  450. await browser.keys("Escape");
  451. }
  452. async function assertNarrowSentWrap() {
  453. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  454. deviceScaleFactor: 1,
  455. height: 800,
  456. mobile: false,
  457. width: 520,
  458. });
  459. const state = await browser.execute(() => {
  460. const row = document.querySelector<HTMLElement>("[data-v4-user-input-attachment-pills]");
  461. const userRow = row?.closest<HTMLElement>("[data-row-id]");
  462. const bubble = userRow?.querySelector<HTMLElement>("[data-v4-user-input-bubble]");
  463. const children = Array.from(row?.children ?? []) as HTMLElement[];
  464. const tops = new Set(children.map((item) => Math.round(item.getBoundingClientRect().top)));
  465. const right = row?.getBoundingClientRect().right ?? 0;
  466. const bubbleWidth = bubble?.getBoundingClientRect().width ?? 0;
  467. const userRowWidth = userRow?.getBoundingClientRect().width ?? 0;
  468. return {
  469. bubbleWithinContainer: bubbleWidth > 0 && bubbleWidth <= userRowWidth + 2,
  470. noDocumentOverflow:
  471. document.documentElement.scrollWidth <= document.documentElement.clientWidth,
  472. rightAligned: children.every((item) => item.getBoundingClientRect().right <= right + 1),
  473. wrapped: tops.size > 1,
  474. };
  475. });
  476. expect(state).toEqual({
  477. bubbleWithinContainer: true,
  478. noDocumentOverflow: true,
  479. rightAligned: true,
  480. wrapped: true,
  481. });
  482. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  483. }
  484. async function assertDesktopAndTouchActions() {
  485. const copy = await $("[data-testid^='v4-copy-']");
  486. await copy.waitForExist({ timeout: 15_000 });
  487. const actions = await copy.parentElement();
  488. await browser.action("pointer").move({ x: 4, y: 4 }).perform();
  489. await browser.waitUntil(
  490. async () => Number(await actions.getCSSProperty("opacity").then((value) => value.value)) === 0,
  491. { timeout: 5_000, timeoutMsg: "desktop 非 hover 状态下消息操作栏没有隐藏" },
  492. );
  493. const row = await actions.parentElement();
  494. await row.moveTo();
  495. await browser.waitUntil(
  496. async () => Number(await actions.getCSSProperty("opacity").then((value) => value.value)) === 1,
  497. { timeout: 5_000, timeoutMsg: "desktop hover 后消息操作栏没有显示" },
  498. );
  499. }
  500. async function waitForEditLayout() {
  501. let snapshot = await readEditLayout();
  502. await browser.waitUntil(
  503. async () => {
  504. snapshot = await readEditLayout();
  505. return snapshot.contextCount === 4 && snapshot.attachmentKinds.length === 3;
  506. },
  507. { timeout: 15_000, timeoutMsg: "composer 编辑态附件/context 布局没有收敛" },
  508. );
  509. return snapshot;
  510. }
  511. function readEditLayout() {
  512. return browser.execute(
  513. (composerTestId, attachmentPrefix, inputTestId) => {
  514. const composer = document.querySelector<HTMLElement>(`[data-testid="${composerTestId}"]`);
  515. const cards = Array.from(
  516. composer?.querySelectorAll<HTMLElement>(
  517. `[data-testid^="${attachmentPrefix}-"][data-upload-status]`,
  518. ) ?? [],
  519. );
  520. const contextRow = composer?.querySelector<HTMLElement>(
  521. "[data-composer-context-attachments-row]",
  522. );
  523. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  524. const visibleText = input?.innerText?.trim() ?? input?.textContent?.trim() ?? "";
  525. return {
  526. attachmentHeights: cards.map((card) => Math.round(card.getBoundingClientRect().height)),
  527. attachmentKinds: cards.map(
  528. (card) => card.getAttribute("data-composer-attachment-kind") ?? "",
  529. ),
  530. containsProtocolText:
  531. /# userselect:|# Code comments:|# Web page elements:|# Presentation/iu.test(visibleText),
  532. contextCount: contextRow?.children.length ?? 0,
  533. visibleText,
  534. };
  535. },
  536. TID_V4_COMPOSER,
  537. TID_V4_ATTACHMENT,
  538. TID_V4_COMPOSER_INPUT,
  539. );
  540. }
  541. async function removeEditWebContext() {
  542. const removed = await browser.execute(() => {
  543. const row = document.querySelector<HTMLElement>("[data-composer-context-attachments-row]");
  544. const pill = Array.from(row?.children ?? []).find((item) =>
  545. /web|网页/iu.test(item.getAttribute("aria-label") ?? ""),
  546. );
  547. const button = pill?.querySelector<HTMLButtonElement>("button");
  548. button?.click();
  549. return Boolean(button);
  550. });
  551. expect(removed).toBe(true);
  552. }
  553. function readLastUserRowStructure() {
  554. return browser.execute(() => {
  555. const rows = Array.from(document.querySelectorAll<HTMLElement>("[data-row-id]")).filter(
  556. (candidate) => candidate.classList.contains("group/user-row"),
  557. );
  558. const row = rows.at(-1);
  559. return {
  560. hasAttachmentArea: Boolean(row?.querySelector("[data-v4-user-input-attachments]")),
  561. hasBubble: Boolean(row?.querySelector("[data-v4-user-input-bubble]")),
  562. text: row?.innerText ?? "",
  563. };
  564. });
  565. }
  566. async function installImageObjectUrlFailureForBlobSize(expectedBlobSize: number) {
  567. const installed = await browser.electron.execute(async (electron, targetBlobSize) => {
  568. const target = electron.BrowserWindow.getAllWindows().find(
  569. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  570. );
  571. if (!target) return false;
  572. // Bug 原因:WebDriver executeScript 位于隔离 world,覆盖的 URL.createObjectURL
  573. // 不会影响 React 所在的 renderer main world。通过 webContents 注入真实页面 world。
  574. return target.webContents.executeJavaScript(
  575. `(() => {
  576. const host = window;
  577. if (host.__e2eOriginalCreateObjectURL) return false;
  578. const original = URL.createObjectURL.bind(URL);
  579. host.__e2eOriginalCreateObjectURL = original;
  580. host.__e2eObjectUrlBlobObservations = [];
  581. URL.createObjectURL = (object) => {
  582. if (
  583. object instanceof Blob &&
  584. object.type.startsWith("image/") &&
  585. object.size === ${targetBlobSize}
  586. ) {
  587. throw new Error("E2E forced image object URL failure");
  588. }
  589. if (object instanceof Blob && object.type.startsWith("image/")) {
  590. host.__e2eObjectUrlBlobObservations.push({ size: object.size, type: object.type });
  591. }
  592. return original(object);
  593. };
  594. return true;
  595. })()`,
  596. true,
  597. );
  598. }, expectedBlobSize);
  599. expect(installed).toBe(true);
  600. }
  601. async function restoreObjectUrlFactory() {
  602. await browser.electron.execute(async (electron) => {
  603. const target = electron.BrowserWindow.getAllWindows().find(
  604. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  605. );
  606. if (!target) return;
  607. await target.webContents.executeJavaScript(
  608. `(() => {
  609. const host = window;
  610. if (!host.__e2eOriginalCreateObjectURL) return;
  611. URL.createObjectURL = host.__e2eOriginalCreateObjectURL;
  612. delete host.__e2eOriginalCreateObjectURL;
  613. delete host.__e2eObjectUrlBlobObservations;
  614. })()`,
  615. true,
  616. );
  617. });
  618. }
  619. async function waitForFailedSentImage() {
  620. let state = await readFailedSentImage();
  621. try {
  622. await browser.waitUntil(
  623. async () => {
  624. state = await readFailedSentImage();
  625. return state.exists && state.title !== "" && !state.hasImage;
  626. },
  627. { timeout: 15_000, timeoutMsg: "图片读取失败后没有降级为不可预览静态占位" },
  628. );
  629. } catch (error) {
  630. const observations = await browser.electron.execute(async (electron) => {
  631. const target = electron.BrowserWindow.getAllWindows().find(
  632. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  633. );
  634. if (!target) return [];
  635. return target.webContents.executeJavaScript(
  636. "window.__e2eObjectUrlBlobObservations ?? []",
  637. true,
  638. );
  639. });
  640. throw new Error(`图片读取失败 mock 未命中,实际 Blob: ${JSON.stringify(observations)}`, {
  641. cause: error,
  642. });
  643. }
  644. return state;
  645. }
  646. function readFailedSentImage() {
  647. return browser.execute((marker) => {
  648. const row = Array.from(document.querySelectorAll<HTMLElement>("[data-row-id]")).find(
  649. (candidate) =>
  650. candidate.classList.contains("group/user-row") && candidate.innerText.includes(marker),
  651. );
  652. const card = row?.querySelector<HTMLElement>("[data-v4-user-input-media-attachment='true']");
  653. return {
  654. exists: Boolean(card),
  655. hasImage: Boolean(card?.querySelector("img")),
  656. role: card?.getAttribute("role") ?? null,
  657. title: card?.getAttribute("title") ?? "",
  658. };
  659. }, FAILED_IMAGE_MARKER);
  660. }
  661. async function openFirstSentImage() {
  662. const opened = await browser.execute((filename) => {
  663. const card = Array.from(
  664. document.querySelectorAll<HTMLElement>("[data-v4-user-input-media-attachment='true']"),
  665. ).find((candidate) => candidate.querySelector<HTMLImageElement>(`img[alt="${filename}"]`));
  666. card?.click();
  667. return Boolean(card);
  668. }, IMAGE_FILE);
  669. expect(opened).toBe(true);
  670. await browser.waitUntil(
  671. () => browser.execute(() => Boolean(document.querySelector("[role='dialog']"))),
  672. { timeout: 10_000, timeoutMsg: "首条消息图片没有打开 gallery" },
  673. );
  674. }
  675. function readOpenGalleryState() {
  676. return browser.execute(() => {
  677. const dialog = document.querySelector<HTMLElement>("[role='dialog']");
  678. const labels = Array.from(dialog?.querySelectorAll("button[aria-label]") ?? []).map(
  679. (button) => button.getAttribute("aria-label") ?? "",
  680. );
  681. return {
  682. hasNext: labels.some((label) => label === "Next image" || label === "下一张图片"),
  683. hasPrevious: labels.some((label) => label === "Previous image" || label === "上一张图片"),
  684. title: dialog?.querySelector("h2")?.textContent?.trim() ?? "",
  685. };
  686. });
  687. }
  688. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  689. const sent = await browser.electron.execute(
  690. async (electron, command, commandParams) => {
  691. const window = electron.BrowserWindow.getAllWindows().find(
  692. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  693. );
  694. if (!window) return false;
  695. const devtools = window.webContents.debugger;
  696. if (!devtools.isAttached()) devtools.attach("1.3");
  697. await devtools.sendCommand(command, commandParams);
  698. return true;
  699. },
  700. method,
  701. params,
  702. );
  703. expect(sent).toBe(true);
  704. }
  705. async function clearRendererEmulation() {
  706. await sendRendererEmulationCommand("Emulation.setTouchEmulationEnabled", {
  707. enabled: false,
  708. }).catch(() => {});
  709. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride").catch(() => {});
  710. }