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

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