conversation-session-native-file-picker-attachments.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { basename, join } from "node:path";
  4. import { TID_CHAT_ATTACHMENT_BUTTON, TID_CHAT_ATTACHMENT_MENU_ITEM } from "@zcode/shared/test-ids";
  5. import { clearAppData } from "#e2e/helpers/desktop-app";
  6. import {
  7. pickV4ComposerFiles,
  8. prepareV4ConversationE2E,
  9. startNewV4Draft,
  10. } from "#e2e/helpers/v4-conversation";
  11. const NATIVE_FILE_PICKER_TIMEOUT_MS = 180000;
  12. const ATTACHMENT_LIMIT = 8;
  13. describe("会话区 native 文件选择器附件数量边界 E2E", () => {
  14. const fixtureRoot = join(tmpdir(), `zcode-e2e-native-file-picker-attachments-${Date.now()}`);
  15. before(async function () {
  16. this.timeout(NATIVE_FILE_PICKER_TIMEOUT_MS);
  17. await prepareV4ConversationE2E();
  18. await createFixtureFiles(fixtureRoot);
  19. });
  20. after(async () => {
  21. await browser.electron.restoreAllMocks();
  22. await rm(fixtureRoot, { force: true, recursive: true });
  23. await clearAppData();
  24. });
  25. beforeEach(async function () {
  26. this.timeout(NATIVE_FILE_PICKER_TIMEOUT_MS);
  27. await startNewV4Draft();
  28. await clearComposerAttachments();
  29. await assertAttachmentLimitWarningVisible(false);
  30. });
  31. it("T01: native picker 返回单个文件时 composer 应保留附件图标", async function () {
  32. this.timeout(NATIVE_FILE_PICKER_TIMEOUT_MS);
  33. const selectedPaths = [fixturePath(fixtureRoot, "single-config.json")];
  34. const expectedFilenames = selectedPaths.map((path) => basename(path));
  35. await pickV4ComposerFiles(selectedPaths);
  36. await assertComposerAttachments(expectedFilenames, {
  37. iconIncludes: ["material-icons/json.svg"],
  38. });
  39. await assertAttachmentLimitWarningVisible(false);
  40. });
  41. it("T02: native picker 一次返回多个文件时应按顺序全部进入 composer", async function () {
  42. this.timeout(NATIVE_FILE_PICKER_TIMEOUT_MS);
  43. const selectedPaths = [
  44. fixturePath(fixtureRoot, "multi-config.json"),
  45. fixturePath(fixtureRoot, "multi-notes.md"),
  46. fixturePath(fixtureRoot, "multi-script.ts"),
  47. ];
  48. const expectedFilenames = selectedPaths.map((path) => basename(path));
  49. await pickV4ComposerFiles(selectedPaths);
  50. await assertComposerAttachments(expectedFilenames, {
  51. iconIncludes: ["material-icons/json.svg", "material-icons/markdown.svg"],
  52. });
  53. await assertAttachmentLimitWarningVisible(false);
  54. });
  55. it("T03: native picker 一次返回超过 8 个文件时只接受前 8 个并提示", async function () {
  56. this.timeout(NATIVE_FILE_PICKER_TIMEOUT_MS);
  57. const selectedPaths = Array.from({ length: 9 }, (_, index) =>
  58. fixturePath(fixtureRoot, `limit-${String(index + 1).padStart(2, "0")}.json`),
  59. );
  60. const acceptedFilenames = selectedPaths
  61. .slice(0, ATTACHMENT_LIMIT)
  62. .map((path) => basename(path));
  63. const rejectedFilename = basename(selectedPaths[ATTACHMENT_LIMIT] ?? "");
  64. await pickV4ComposerFiles(selectedPaths);
  65. await assertComposerAttachments(acceptedFilenames, {
  66. iconIncludes: ["material-icons/json.svg"],
  67. rejectedFilenames: [rejectedFilename],
  68. });
  69. await assertAttachmentLimitWarningVisible(true);
  70. });
  71. it("满 8 个后选择、重复粘贴均弹出提示,删除后可继续添加", async function () {
  72. this.timeout(NATIVE_FILE_PICKER_TIMEOUT_MS);
  73. const paths = Array.from({ length: 8 }, (_, index) =>
  74. fixturePath(fixtureRoot, `limit-${String(index + 1).padStart(2, "0")}.json`),
  75. );
  76. await pickV4ComposerFiles(paths);
  77. await assertComposerAttachments(paths.map((path) => basename(path)));
  78. // 满额时应在打开系统选择器前拦截,监听真实 input click 而非已清空的 files。
  79. await browser.execute(() => {
  80. const input = document.querySelector<HTMLInputElement>('input[type="file"]');
  81. if (!input) throw new Error("缺少附件文件输入框");
  82. input.dataset.e2eClickCount = "0";
  83. input.addEventListener(
  84. "click",
  85. (event) => {
  86. event.preventDefault();
  87. input.dataset.e2eClickCount = "1";
  88. },
  89. { capture: true, once: true },
  90. );
  91. });
  92. await clickAttachmentMenuItem();
  93. await assertAttachmentLimitWarningVisible(true);
  94. expect(
  95. await browser.execute(() => {
  96. const input = document.querySelector<HTMLInputElement>('input[type="file"]');
  97. return input?.dataset.e2eClickCount;
  98. }),
  99. ).toBe("0");
  100. for (let attempt = 0; attempt < 2; attempt++) {
  101. await assertAttachmentLimitWarningVisible(false);
  102. await browser.execute(() => {
  103. const input = document.querySelector<HTMLElement>('[data-testid="v4-composer-input"]');
  104. if (!input) throw new Error("缺少输入框");
  105. const clipboardData = new DataTransfer();
  106. clipboardData.items.add(new File(["extra"], "rejected-paste.txt", { type: "text/plain" }));
  107. input.focus();
  108. input.dispatchEvent(
  109. new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData }),
  110. );
  111. });
  112. await assertAttachmentLimitWarningVisible(true);
  113. await assertComposerAttachments(
  114. paths.map((path) => basename(path)),
  115. { rejectedFilenames: ["rejected-paste.txt"] },
  116. );
  117. }
  118. await browser.execute(() => {
  119. const remove = [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) =>
  120. /Remove attachment|移除附件/.test(button.getAttribute("aria-label") ?? ""),
  121. );
  122. if (!remove) throw new Error("缺少附件删除按钮");
  123. remove.click();
  124. });
  125. const replacement = fixturePath(fixtureRoot, "single-config.json");
  126. await pickV4ComposerFiles([replacement]);
  127. await assertComposerAttachments(
  128. [...paths.slice(1), replacement].map((path) => basename(path)),
  129. { rejectedFilenames: [basename(paths[0]!)] },
  130. );
  131. });
  132. });
  133. async function createFixtureFiles(root: string) {
  134. await mkdir(root, { recursive: true });
  135. const files = [
  136. "single-config.json",
  137. "multi-config.json",
  138. "multi-notes.md",
  139. "multi-script.ts",
  140. ...Array.from({ length: 9 }, (_, index) => `limit-${String(index + 1).padStart(2, "0")}.json`),
  141. ];
  142. await Promise.all(
  143. files.map((filename) =>
  144. writeFile(
  145. fixturePath(root, filename),
  146. `E2E native file picker fixture: ${filename}\n`,
  147. "utf8",
  148. ),
  149. ),
  150. );
  151. }
  152. function fixturePath(root: string, filename: string) {
  153. return join(root, filename);
  154. }
  155. async function clickAttachmentMenuItem() {
  156. const trigger = await $(`[data-testid="${TID_CHAT_ATTACHMENT_BUTTON}"]`);
  157. await trigger.waitForClickable({
  158. timeout: 15000,
  159. timeoutMsg: "附件菜单按钮没有出现",
  160. });
  161. await trigger.click();
  162. const menuItem = await $(`[data-testid="${TID_CHAT_ATTACHMENT_MENU_ITEM}"]`);
  163. await menuItem.waitForClickable({
  164. timeout: 10000,
  165. timeoutMsg: "附件菜单项没有出现",
  166. });
  167. await menuItem.click();
  168. }
  169. async function assertComposerAttachments(
  170. expectedFilenames: string[],
  171. options: {
  172. iconIncludes?: string[];
  173. rejectedFilenames?: string[];
  174. } = {},
  175. ) {
  176. await browser.waitUntil(
  177. async () => {
  178. const snapshot = await getAttachmentDomSnapshot();
  179. return (
  180. containsAll(snapshot.bodyText, expectedFilenames) &&
  181. excludesAll(snapshot.bodyText, options.rejectedFilenames ?? []) &&
  182. containsAll(snapshot.iconSrcs.join("\n"), options.iconIncludes ?? [])
  183. );
  184. },
  185. {
  186. timeout: 15000,
  187. timeoutMsg: `composer 附件状态不符合预期: ${expectedFilenames.join(", ")}`,
  188. },
  189. );
  190. const snapshot = await getAttachmentDomSnapshot();
  191. expectContainsInOrder(snapshot.bodyText, expectedFilenames);
  192. }
  193. async function clearComposerAttachments() {
  194. await browser.waitUntil(
  195. async () => {
  196. const removedCount = await browser.execute(() => {
  197. const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>("button"));
  198. const removeButtons = buttons.filter((button) => {
  199. const label = button.getAttribute("aria-label") ?? "";
  200. return label.includes("Remove attachment") || label.includes("移除附件");
  201. });
  202. // startNewTask 不保证清空 composer 本地草稿附件;这里显式清理,避免数量边界 case 互相污染。
  203. for (const button of removeButtons) {
  204. button.click();
  205. }
  206. return removeButtons.length;
  207. });
  208. return removedCount === 0;
  209. },
  210. {
  211. timeout: 10000,
  212. timeoutMsg: "没有清空 composer 遗留附件",
  213. },
  214. );
  215. }
  216. async function assertAttachmentLimitWarningVisible(expected: boolean) {
  217. await browser.waitUntil(
  218. async () => {
  219. const snapshot = await getAttachmentLimitWarningSnapshot();
  220. return expected ? snapshot.visible : !snapshot.visible;
  221. },
  222. {
  223. timeout: 10000,
  224. timeoutMsg: expected ? "没有显示附件数量上限 warning" : "不应显示附件数量上限 warning",
  225. },
  226. );
  227. if (!expected) {
  228. return;
  229. }
  230. const snapshot = await getAttachmentLimitWarningSnapshot();
  231. expect(snapshot.className).toContain("bg-toast/60");
  232. expect(snapshot.hasInfoIcon).toBe(true);
  233. }
  234. async function getAttachmentDomSnapshot() {
  235. return browser.execute(() => ({
  236. bodyText: document.body.innerText.replace(/\u00a0/g, " "),
  237. iconSrcs: Array.from(document.querySelectorAll<HTMLImageElement>("img")).map(
  238. (image) => image.src,
  239. ),
  240. }));
  241. }
  242. async function getAttachmentLimitWarningSnapshot() {
  243. return browser.execute(() => {
  244. const candidates = Array.from(
  245. document.querySelectorAll<HTMLElement>("#zcode-toast-host .rounded-2xl"),
  246. );
  247. const warning = candidates.find((element) => {
  248. const text = element.innerText.replace(/\u00a0/g, " ");
  249. return (
  250. text.includes("最多只能添加 8 个附件") ||
  251. text.includes("You can attach up to 8 attachments")
  252. );
  253. });
  254. return {
  255. className: warning?.className ?? "",
  256. hasInfoIcon: Boolean(warning?.querySelector("svg")),
  257. visible: Boolean(
  258. warning &&
  259. getComputedStyle(warning).opacity === "1" &&
  260. warning.getBoundingClientRect().top >= 0 &&
  261. warning.getBoundingClientRect().bottom <= window.innerHeight,
  262. ),
  263. };
  264. });
  265. }
  266. function containsAll(value: string, expected: string[]) {
  267. return expected.every((item) => value.includes(item));
  268. }
  269. function excludesAll(value: string, rejected: string[]) {
  270. return rejected.every((item) => !value.includes(item));
  271. }
  272. function expectContainsInOrder(value: string, expected: string[]) {
  273. let offset = 0;
  274. for (const item of expected) {
  275. const nextIndex = value.indexOf(item, offset);
  276. expect(nextIndex).toBeGreaterThanOrEqual(0);
  277. offset = nextIndex + item.length;
  278. }
  279. }