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

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