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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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. if (/conversation|对话/iu.test(label)) return "selection";
  380. return "unknown";
  381. };
  382. const filePills = pillChildren.filter((item) => classify(item) === "file");
  383. const areaRect = area?.getBoundingClientRect();
  384. const bubbleRect = bubble?.getBoundingClientRect();
  385. const rowRect = row?.getBoundingClientRect();
  386. return {
  387. areaBeforeBubble: Boolean(
  388. area && bubble && area.compareDocumentPosition(bubble) & Node.DOCUMENT_POSITION_FOLLOWING,
  389. ),
  390. areaInsideBubble: Boolean(area && bubble?.contains(area)),
  391. emptyUserRows: Array.from(document.querySelectorAll<HTMLElement>("[data-v4-row-id]"))
  392. .filter((candidate) => candidate.classList.contains("group/user-row"))
  393. .filter(
  394. (candidate) =>
  395. !candidate.querySelector(
  396. "[data-v4-user-input-attachments], [data-v4-user-input-bubble]",
  397. ),
  398. ).length,
  399. fileNames: filePills
  400. .map((pill) => pill.textContent ?? "")
  401. .flatMap((text) => [longFile, secondFile].filter((name) => text.includes(name))),
  402. filePillsAreRoundAndBorderless: filePills.every((pill) => {
  403. const style = getComputedStyle(pill);
  404. return (
  405. parseFloat(style.borderRadius) >= 999 ||
  406. (style.borderStyle === "none" && parseFloat(style.borderRadius) >= 16)
  407. );
  408. }),
  409. mediaBeforePills: Boolean(
  410. media && pills && media.compareDocumentPosition(pills) & Node.DOCUMENT_POSITION_FOLLOWING,
  411. ),
  412. mediaKinds: Array.from(media?.children ?? []).map((item) =>
  413. item.querySelector("video") ? "video" : "image",
  414. ),
  415. bubbleWidth: bubbleRect?.width ?? 0,
  416. pillOrder: pillChildren.map(classify).filter((kind) => kind !== "unknown"),
  417. rightEdgesAligned: Boolean(
  418. areaRect && bubbleRect && Math.abs(areaRect.right - bubbleRect.right) <= 2,
  419. ),
  420. rowWidth: rowRect?.width ?? 0,
  421. };
  422. },
  423. TID_V4_ROW_ATTACHMENTS,
  424. LONG_FILE,
  425. SECOND_FILE,
  426. );
  427. }
  428. async function assertContextHoverAlignment(surface: "composer" | "sent") {
  429. const selector =
  430. surface === "composer"
  431. ? "[data-composer-context-attachments-row] > [role='button']"
  432. : "[data-v4-user-input-attachment-pills] > [role='button']";
  433. const trigger = await $(selector);
  434. await trigger.waitForExist({ timeout: 15_000 });
  435. await trigger.moveTo();
  436. const content = await $("[data-slot='hover-card-content']");
  437. await content.waitForDisplayed({ timeout: 5_000 });
  438. const [triggerRect, contentRect] = await Promise.all([
  439. trigger
  440. .getElement()
  441. .then((element) => browser.execute((item) => item.getBoundingClientRect().toJSON(), element)),
  442. content
  443. .getElement()
  444. .then((element) => browser.execute((item) => item.getBoundingClientRect().toJSON(), element)),
  445. ]);
  446. if (surface === "composer")
  447. expect(Math.abs(triggerRect.left - contentRect.left)).toBeLessThanOrEqual(3);
  448. else expect(Math.abs(triggerRect.right - contentRect.right)).toBeLessThanOrEqual(3);
  449. await browser.keys("Escape");
  450. }
  451. async function assertNarrowSentWrap() {
  452. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  453. deviceScaleFactor: 1,
  454. height: 800,
  455. mobile: false,
  456. width: 520,
  457. });
  458. const state = await browser.execute(() => {
  459. const row = document.querySelector<HTMLElement>("[data-v4-user-input-attachment-pills]");
  460. const userRow = row?.closest<HTMLElement>("[data-row-id]");
  461. const bubble = userRow?.querySelector<HTMLElement>("[data-v4-user-input-bubble]");
  462. const children = Array.from(row?.children ?? []) as HTMLElement[];
  463. const tops = new Set(children.map((item) => Math.round(item.getBoundingClientRect().top)));
  464. const right = row?.getBoundingClientRect().right ?? 0;
  465. const bubbleWidth = bubble?.getBoundingClientRect().width ?? 0;
  466. const userRowWidth = userRow?.getBoundingClientRect().width ?? 0;
  467. return {
  468. bubbleWithinContainer: bubbleWidth > 0 && bubbleWidth <= userRowWidth + 2,
  469. noDocumentOverflow:
  470. document.documentElement.scrollWidth <= document.documentElement.clientWidth,
  471. rightAligned: children.every((item) => item.getBoundingClientRect().right <= right + 1),
  472. wrapped: tops.size > 1,
  473. };
  474. });
  475. expect(state).toEqual({
  476. bubbleWithinContainer: true,
  477. noDocumentOverflow: true,
  478. rightAligned: true,
  479. wrapped: true,
  480. });
  481. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  482. }
  483. async function assertDesktopAndTouchActions() {
  484. const copy = await $("[data-testid^='v4-copy-']");
  485. await copy.waitForExist({ timeout: 15_000 });
  486. const actions = await copy.parentElement();
  487. await browser.action("pointer").move({ x: 4, y: 4 }).perform();
  488. await browser.waitUntil(
  489. async () => Number(await actions.getCSSProperty("opacity").then((value) => value.value)) === 0,
  490. { timeout: 5_000, timeoutMsg: "desktop 非 hover 状态下消息操作栏没有隐藏" },
  491. );
  492. const row = await actions.parentElement();
  493. await row.moveTo();
  494. await browser.waitUntil(
  495. async () => Number(await actions.getCSSProperty("opacity").then((value) => value.value)) === 1,
  496. { timeout: 5_000, timeoutMsg: "desktop hover 后消息操作栏没有显示" },
  497. );
  498. }
  499. async function waitForEditLayout() {
  500. let snapshot = await readEditLayout();
  501. await browser.waitUntil(
  502. async () => {
  503. snapshot = await readEditLayout();
  504. return snapshot.contextCount === 4 && snapshot.attachmentKinds.length === 3;
  505. },
  506. { timeout: 15_000, timeoutMsg: "composer 编辑态附件/context 布局没有收敛" },
  507. );
  508. return snapshot;
  509. }
  510. function readEditLayout() {
  511. return browser.execute(
  512. (composerTestId, attachmentPrefix, inputTestId) => {
  513. const composer = document.querySelector<HTMLElement>(`[data-testid="${composerTestId}"]`);
  514. const cards = Array.from(
  515. composer?.querySelectorAll<HTMLElement>(
  516. `[data-testid^="${attachmentPrefix}-"][data-upload-status]`,
  517. ) ?? [],
  518. );
  519. const contextRow = composer?.querySelector<HTMLElement>(
  520. "[data-composer-context-attachments-row]",
  521. );
  522. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  523. const visibleText = input?.innerText?.trim() ?? input?.textContent?.trim() ?? "";
  524. return {
  525. attachmentHeights: cards.map((card) => Math.round(card.getBoundingClientRect().height)),
  526. attachmentKinds: cards.map(
  527. (card) => card.getAttribute("data-composer-attachment-kind") ?? "",
  528. ),
  529. containsProtocolText:
  530. /# userselect:|# Code comments:|# Web page elements:|# Presentation/iu.test(visibleText),
  531. contextCount: contextRow?.children.length ?? 0,
  532. visibleText,
  533. };
  534. },
  535. TID_V4_COMPOSER,
  536. TID_V4_ATTACHMENT,
  537. TID_V4_COMPOSER_INPUT,
  538. );
  539. }
  540. async function removeEditWebContext() {
  541. const removed = await browser.execute(() => {
  542. const row = document.querySelector<HTMLElement>("[data-composer-context-attachments-row]");
  543. const pill = Array.from(row?.children ?? []).find((item) =>
  544. /web|网页/iu.test(item.getAttribute("aria-label") ?? ""),
  545. );
  546. const button = pill?.querySelector<HTMLButtonElement>("button");
  547. button?.click();
  548. return Boolean(button);
  549. });
  550. expect(removed).toBe(true);
  551. }
  552. function readLastUserRowStructure() {
  553. return browser.execute(() => {
  554. const rows = Array.from(document.querySelectorAll<HTMLElement>("[data-row-id]")).filter(
  555. (candidate) => candidate.classList.contains("group/user-row"),
  556. );
  557. const row = rows.at(-1);
  558. return {
  559. hasAttachmentArea: Boolean(row?.querySelector("[data-v4-user-input-attachments]")),
  560. hasBubble: Boolean(row?.querySelector("[data-v4-user-input-bubble]")),
  561. text: row?.innerText ?? "",
  562. };
  563. });
  564. }
  565. async function installImageObjectUrlFailureForBlobSize(expectedBlobSize: number) {
  566. const installed = await browser.electron.execute(async (electron, targetBlobSize) => {
  567. const target = electron.BrowserWindow.getAllWindows().find(
  568. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  569. );
  570. if (!target) return false;
  571. // Bug 原因:WebDriver executeScript 位于隔离 world,覆盖的 URL.createObjectURL
  572. // 不会影响 React 所在的 renderer main world。通过 webContents 注入真实页面 world。
  573. return target.webContents.executeJavaScript(
  574. `(() => {
  575. const host = window;
  576. if (host.__e2eOriginalCreateObjectURL) return false;
  577. const original = URL.createObjectURL.bind(URL);
  578. host.__e2eOriginalCreateObjectURL = original;
  579. host.__e2eObjectUrlBlobObservations = [];
  580. URL.createObjectURL = (object) => {
  581. if (
  582. object instanceof Blob &&
  583. object.type.startsWith("image/") &&
  584. object.size === ${targetBlobSize}
  585. ) {
  586. throw new Error("E2E forced image object URL failure");
  587. }
  588. if (object instanceof Blob && object.type.startsWith("image/")) {
  589. host.__e2eObjectUrlBlobObservations.push({ size: object.size, type: object.type });
  590. }
  591. return original(object);
  592. };
  593. return true;
  594. })()`,
  595. true,
  596. );
  597. }, expectedBlobSize);
  598. expect(installed).toBe(true);
  599. }
  600. async function restoreObjectUrlFactory() {
  601. await browser.electron.execute(async (electron) => {
  602. const target = electron.BrowserWindow.getAllWindows().find(
  603. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  604. );
  605. if (!target) return;
  606. await target.webContents.executeJavaScript(
  607. `(() => {
  608. const host = window;
  609. if (!host.__e2eOriginalCreateObjectURL) return;
  610. URL.createObjectURL = host.__e2eOriginalCreateObjectURL;
  611. delete host.__e2eOriginalCreateObjectURL;
  612. delete host.__e2eObjectUrlBlobObservations;
  613. })()`,
  614. true,
  615. );
  616. });
  617. }
  618. async function waitForFailedSentImage() {
  619. let state = await readFailedSentImage();
  620. try {
  621. await browser.waitUntil(
  622. async () => {
  623. state = await readFailedSentImage();
  624. return state.exists && state.title !== "" && !state.hasImage;
  625. },
  626. { timeout: 15_000, timeoutMsg: "图片读取失败后没有降级为不可预览静态占位" },
  627. );
  628. } catch (error) {
  629. const observations = await browser.electron.execute(async (electron) => {
  630. const target = electron.BrowserWindow.getAllWindows().find(
  631. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  632. );
  633. if (!target) return [];
  634. return target.webContents.executeJavaScript(
  635. "window.__e2eObjectUrlBlobObservations ?? []",
  636. true,
  637. );
  638. });
  639. throw new Error(`图片读取失败 mock 未命中,实际 Blob: ${JSON.stringify(observations)}`, {
  640. cause: error,
  641. });
  642. }
  643. return state;
  644. }
  645. function readFailedSentImage() {
  646. return browser.execute((marker) => {
  647. const row = Array.from(document.querySelectorAll<HTMLElement>("[data-row-id]")).find(
  648. (candidate) =>
  649. candidate.classList.contains("group/user-row") && candidate.innerText.includes(marker),
  650. );
  651. const card = row?.querySelector<HTMLElement>("[data-v4-user-input-media-attachment='true']");
  652. return {
  653. exists: Boolean(card),
  654. hasImage: Boolean(card?.querySelector("img")),
  655. role: card?.getAttribute("role") ?? null,
  656. title: card?.getAttribute("title") ?? "",
  657. };
  658. }, FAILED_IMAGE_MARKER);
  659. }
  660. async function openFirstSentImage() {
  661. const opened = await browser.execute((filename) => {
  662. const card = Array.from(
  663. document.querySelectorAll<HTMLElement>("[data-v4-user-input-media-attachment='true']"),
  664. ).find((candidate) => candidate.querySelector<HTMLImageElement>(`img[alt="${filename}"]`));
  665. card?.click();
  666. return Boolean(card);
  667. }, IMAGE_FILE);
  668. expect(opened).toBe(true);
  669. await browser.waitUntil(
  670. () => browser.execute(() => Boolean(document.querySelector("[role='dialog']"))),
  671. { timeout: 10_000, timeoutMsg: "首条消息图片没有打开 gallery" },
  672. );
  673. }
  674. function readOpenGalleryState() {
  675. return browser.execute(() => {
  676. const dialog = document.querySelector<HTMLElement>("[role='dialog']");
  677. const labels = Array.from(dialog?.querySelectorAll("button[aria-label]") ?? []).map(
  678. (button) => button.getAttribute("aria-label") ?? "",
  679. );
  680. return {
  681. hasNext: labels.some((label) => label === "Next image" || label === "下一张图片"),
  682. hasPrevious: labels.some((label) => label === "Previous image" || label === "上一张图片"),
  683. title: dialog?.querySelector("h2")?.textContent?.trim() ?? "",
  684. };
  685. });
  686. }
  687. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  688. const sent = await browser.electron.execute(
  689. async (electron, command, commandParams) => {
  690. const window = electron.BrowserWindow.getAllWindows().find(
  691. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  692. );
  693. if (!window) return false;
  694. const devtools = window.webContents.debugger;
  695. if (!devtools.isAttached()) devtools.attach("1.3");
  696. await devtools.sendCommand(command, commandParams);
  697. return true;
  698. },
  699. method,
  700. params,
  701. );
  702. expect(sent).toBe(true);
  703. }
  704. async function clearRendererEmulation() {
  705. await sendRendererEmulationCommand("Emulation.setTouchEmulationEnabled", {
  706. enabled: false,
  707. }).catch(() => {});
  708. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride").catch(() => {});
  709. }