yolo-confirmation.test.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import assert from "node:assert/strict";
  2. import { before, after, test } from "node:test";
  3. import { mkdir } from "node:fs/promises";
  4. import { fileURLToPath } from "node:url";
  5. import { join } from "node:path";
  6. import { createServer } from "vite";
  7. import react from "@vitejs/plugin-react";
  8. import tailwindcss from "@tailwindcss/vite";
  9. import { chromium } from "playwright-core";
  10. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  11. const entry = "/packages/ui/test/browser/manual-review/pending/yolo-confirmation.fixture.tsx";
  12. let server, browser, origin;
  13. const artifacts = join(root, "packages/desktop/.e2e-artifacts/yolo-confirmation-browser");
  14. before(async () => {
  15. await mkdir(artifacts, { recursive: true });
  16. server = await createServer({
  17. root,
  18. configFile: false,
  19. cacheDir: join(root, "node_modules/.vite-yolo-confirmation"),
  20. plugins: [
  21. react(),
  22. tailwindcss(),
  23. {
  24. name: "permission-fixture",
  25. configureServer(vite) {
  26. vite.middlewares.use(async (req, res, next) => {
  27. if (!req.url?.startsWith("/fixture?")) return next();
  28. res.setHeader("Content-Type", "text/html");
  29. res.end(
  30. await vite.transformIndexHtml(
  31. req.url,
  32. `<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  33. ),
  34. );
  35. });
  36. },
  37. },
  38. ],
  39. resolve: { alias: { "@": `${root}packages/ui/src` } },
  40. optimizeDeps: { entries: [entry.slice(1)] },
  41. server: {
  42. host: "127.0.0.1",
  43. port: 0,
  44. hmr: false,
  45. watch: { ignored: ["**/packages/desktop/out/**", "**/.e2e-artifacts/**"] },
  46. },
  47. });
  48. await server.listen();
  49. origin = server.resolvedUrls.local[0];
  50. browser = await chromium.launch(
  51. process.env.CHROME_EXECUTABLE_PATH
  52. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  53. : { channel: "chrome" },
  54. );
  55. });
  56. after(async () => {
  57. await browser?.close();
  58. await server?.close();
  59. });
  60. const dialog = (page) => page.getByTestId("yolo-confirmation-dialog");
  61. const state = async (page) => JSON.parse(await page.getByTestId("state").textContent());
  62. async function assertRiskUnchecked(page) {
  63. await dialog(page).waitFor();
  64. assert.equal(await page.getByTestId("yolo-confirmation-confirm").isDisabled(), true);
  65. assert.equal(await dialog(page).getByRole("checkbox").isChecked(), false);
  66. }
  67. async function acknowledgeRisk(page) {
  68. await assertRiskUnchecked(page);
  69. await dialog(page).getByRole("checkbox").check();
  70. assert.equal(await page.getByTestId("yolo-confirmation-confirm").isEnabled(), true);
  71. }
  72. async function assertReadablePermissionDetails(page) {
  73. const layout = await dialog(page).evaluate((element) => {
  74. const bodySize = Number.parseFloat(
  75. getComputedStyle(element).getPropertyValue("--ui-font-size"),
  76. );
  77. const details = [...element.querySelectorAll("li p:last-child, :scope > p")];
  78. const actions = [...element.querySelectorAll("[data-slot='alert-dialog-footer'] button")];
  79. const description = element.querySelector("[data-slot='alert-dialog-description']");
  80. const risk = element.querySelector(":scope > p");
  81. const acknowledgement = element.querySelector(":scope > label");
  82. const title = element.querySelector("[data-slot='alert-dialog-title']");
  83. return {
  84. bodySize,
  85. relaxedLineHeight: Number.parseFloat(
  86. getComputedStyle(element).getPropertyValue("--leading-relaxed"),
  87. ),
  88. mobile: innerWidth < 640,
  89. titleSize: Number.parseFloat(
  90. getComputedStyle(element.querySelector("[data-slot='alert-dialog-title']")).fontSize,
  91. ),
  92. descriptionLineHeight: Number.parseFloat(getComputedStyle(description).lineHeight),
  93. riskLineHeight: Number.parseFloat(getComputedStyle(risk).lineHeight),
  94. riskColor: getComputedStyle(risk).color,
  95. acknowledgementSize: Number.parseFloat(getComputedStyle(acknowledgement).fontSize),
  96. acknowledgementColor: getComputedStyle(acknowledgement).color,
  97. primaryColor: getComputedStyle(title).color,
  98. separateAcknowledgement:
  99. risk.getBoundingClientRect().bottom <= acknowledgement.getBoundingClientRect().top &&
  100. acknowledgement.getBoundingClientRect().bottom <= actions[0].getBoundingClientRect().top,
  101. actionGap: Number.parseFloat(
  102. getComputedStyle(element.querySelector("[data-slot='alert-dialog-footer']")).columnGap,
  103. ),
  104. actionSizes: actions.map((action) => ({
  105. width: Number.parseFloat(getComputedStyle(action).width),
  106. height: Number.parseFloat(getComputedStyle(action).height),
  107. })),
  108. minimumDetailSize: bodySize - (innerWidth >= 640 ? 2 : 0),
  109. detailSizes: details.map((detail) => Number.parseFloat(getComputedStyle(detail).fontSize)),
  110. fitsWidth: element.scrollWidth <= element.clientWidth,
  111. actionPositions: actions.map((action) => action.getBoundingClientRect().top),
  112. };
  113. });
  114. assert.equal(layout.detailSizes.length, 4);
  115. assert.equal(layout.acknowledgementColor, layout.primaryColor, "勾选文案使用主文字颜色");
  116. assert.notEqual(layout.riskColor, layout.primaryColor, "原风险说明保留辅助文字颜色");
  117. assert.equal(layout.acknowledgementSize, layout.bodySize, "勾选标签使用通用正文层级");
  118. assert.ok(layout.separateAcknowledgement, "风险小字、勾选标签、操作按钮按顺序独立排布");
  119. assert.ok(
  120. layout.detailSizes.every((size) => size >= layout.minimumDetailSize),
  121. `权限说明应遵守 APP 的手机正文/桌面辅助字号:${JSON.stringify(layout)}`,
  122. );
  123. assert.ok(layout.fitsWidth, "放大字号后权限说明不应横向溢出");
  124. assert.equal(layout.actionPositions.length, 2);
  125. assert.ok(
  126. Math.abs(layout.actionPositions[0] - layout.actionPositions[1]) < 1,
  127. "确认和取消应同排显示,避免手机底部出现两条铺满宽度的色块",
  128. );
  129. assert.equal(layout.titleSize, layout.bodySize + 2, "标题应遵守通用弹窗字号");
  130. if (layout.mobile) {
  131. const expectedLineHeight = layout.bodySize * layout.relaxedLineHeight;
  132. assert.equal(layout.descriptionLineHeight, expectedLineHeight, "手机说明行高应随字号缩放");
  133. assert.equal(layout.riskLineHeight, expectedLineHeight, "手机风险说明行高应随字号缩放");
  134. assert.ok(
  135. layout.actionSizes.every(({ height }) => height >= 44),
  136. "手机按钮触控高度至少 44px",
  137. );
  138. assert.ok(
  139. Math.abs(layout.actionSizes[0].width - layout.actionSizes[1].width) < 1,
  140. "手机操作区应为双列等宽按钮",
  141. );
  142. assert.equal(layout.actionGap, 12, "手机按钮间距沿用切换账号弹窗");
  143. } else {
  144. assert.ok(
  145. layout.actionSizes.every(({ height }) => height === 36),
  146. "桌面按钮保持 36px 高",
  147. );
  148. assert.equal(layout.actionGap, 8, "桌面按钮间距保持 8px");
  149. }
  150. }
  151. async function choose(page, mode) {
  152. await page.getByTestId("chat-mode-select-trigger").click();
  153. const item = page.getByTestId(`chat-mode-select-item-${mode}`);
  154. await item.click();
  155. await item.waitFor({ state: "hidden" });
  156. }
  157. for (const width of [390, 1200])
  158. for (const theme of ["light", "dark"])
  159. for (const locale of ["zh-CN", "en-US"]) {
  160. test(`YC01–07 ${width}/${theme}/${locale}`, async () => {
  161. const page = await browser.newPage({
  162. viewport: { width, height: 800 },
  163. hasTouch: width === 390,
  164. });
  165. const errors = [];
  166. page.on("pageerror", (error) => errors.push(error.message));
  167. const url = `${origin}fixture?theme=${theme}&locale=${locale}`;
  168. try {
  169. for (const previous of ["build", "guarded", "edit"]) {
  170. await page.goto(`${url}&mode=${previous}`);
  171. await choose(page, "yolo");
  172. await dialog(page).waitFor();
  173. assert.equal((await state(page)).mode, previous);
  174. await page.waitForFunction(
  175. () =>
  176. document.activeElement?.getAttribute("data-testid") === "yolo-confirmation-cancel",
  177. );
  178. await assertRiskUnchecked(page);
  179. const riskLabel =
  180. locale === "zh-CN"
  181. ? "我已了解风险,并对自己的数据安全负责。"
  182. : "I understand the risks and take responsibility for my data security.";
  183. assert.equal(
  184. await dialog(page).locator(":scope > p").textContent(),
  185. locale === "zh-CN"
  186. ? "这些操作可能造成数据丢失或泄露。请仅在信任任务内容时启用。你可以随时切回其他权限模式。"
  187. : "These actions may cause data loss or disclosure. Enable only for tasks you trust. You can switch to another permission mode at any time.",
  188. );
  189. const checkbox = dialog(page).getByRole("checkbox", { name: riskLabel });
  190. assert.equal(
  191. await page.getByTestId("yolo-confirmation-confirm").textContent(),
  192. locale === "en-US" ? "Confirm" : "确认启用",
  193. );
  194. await checkbox.focus();
  195. await page.keyboard.press("Enter");
  196. await assertRiskUnchecked(page);
  197. await page.keyboard.press("Space");
  198. assert.equal(await checkbox.isChecked(), true);
  199. assert.equal((await state(page)).commits, 0);
  200. await page.keyboard.press("Space");
  201. await assertRiskUnchecked(page);
  202. await dialog(page).getByText(riskLabel, { exact: true }).click();
  203. assert.equal(await checkbox.isChecked(), true);
  204. await assertReadablePermissionDetails(page);
  205. await page.keyboard.press("Control+Shift+M");
  206. await page.keyboard.press("Control+t");
  207. assert.equal((await state(page)).commits, 0);
  208. await page.keyboard.press("Escape");
  209. await dialog(page).waitFor({ state: "hidden" });
  210. assert.equal((await state(page)).mode, previous);
  211. await choose(page, "yolo");
  212. await acknowledgeRisk(page);
  213. await page.getByTestId("yolo-confirmation-cancel").click();
  214. assert.equal((await state(page)).commits, 0);
  215. await choose(page, "yolo");
  216. await acknowledgeRisk(page);
  217. await page.getByTestId("yolo-confirmation-confirm").click();
  218. assert.deepEqual(await state(page), {
  219. mode: "yolo",
  220. planEnabled: true,
  221. commits: 1,
  222. response: "",
  223. });
  224. await choose(page, "yolo");
  225. assert.equal(await dialog(page).count(), 0);
  226. }
  227. await choose(page, "guarded");
  228. await page.keyboard.press("Control+Shift+M");
  229. await dialog(page).waitFor();
  230. await assertRiskUnchecked(page);
  231. await dialog(page).evaluate((element) =>
  232. Promise.all(element.getAnimations().map((animation) => animation.finished)),
  233. );
  234. await page.screenshot({ path: join(artifacts, `${width}-${theme}-${locale}.png`) });
  235. const rect = await dialog(page).boundingBox();
  236. if (width === 1200)
  237. assert.ok(rect.width <= 448, "桌面弹窗不应超过通用确认框的 448px 上限");
  238. assert.ok(
  239. rect.x >= 0 &&
  240. rect.x + rect.width <= width &&
  241. rect.y >= 0 &&
  242. rect.y + rect.height <= 800,
  243. );
  244. await page.evaluate(() =>
  245. document.documentElement.style.setProperty("--ui-font-size", "18px"),
  246. );
  247. await assertReadablePermissionDetails(page);
  248. for (const action of ["cancel", "confirm"]) {
  249. const button = page.getByTestId(`yolo-confirmation-${action}`);
  250. await button.scrollIntoViewIfNeeded();
  251. const bounds = await button.boundingBox();
  252. assert.ok(bounds.y >= 0 && bounds.y + bounds.height <= 800);
  253. }
  254. await page.evaluate(() =>
  255. document.documentElement.style.removeProperty("--ui-font-size"),
  256. );
  257. await acknowledgeRisk(page);
  258. await page.evaluate(() => window.changeYoloTarget());
  259. await dialog(page).waitFor({ state: "hidden" });
  260. assert.equal((await state(page)).mode, "guarded");
  261. await choose(page, "yolo");
  262. await assertRiskUnchecked(page);
  263. await page.getByTestId("yolo-confirmation-cancel").click();
  264. await page.goto(`${url}&mode=yolo`);
  265. assert.equal(await dialog(page).count(), 0);
  266. await choose(page, "yolo");
  267. assert.equal(await dialog(page).count(), 0);
  268. await choose(page, "build");
  269. await page.evaluate(() => window.syncYoloMode("yolo"));
  270. assert.equal(await dialog(page).count(), 0);
  271. for (const surface of ["automation", "offpeak"]) {
  272. await page.goto(`${url}&surface=${surface}`);
  273. const trigger = page.getByTestId("chat-mode-select-trigger");
  274. await trigger.waitFor();
  275. const before = await trigger.textContent();
  276. await choose(page, "yolo");
  277. await dialog(page).waitFor();
  278. assert.equal(await trigger.textContent(), before);
  279. await acknowledgeRisk(page);
  280. assert.equal(await trigger.textContent(), before);
  281. await page.getByTestId("yolo-confirmation-cancel").click();
  282. assert.equal(await trigger.textContent(), before);
  283. await choose(page, "yolo");
  284. await acknowledgeRisk(page);
  285. await page.getByTestId("yolo-confirmation-confirm").click();
  286. assert.notEqual(await trigger.textContent(), before);
  287. await choose(page, "build");
  288. await choose(page, "yolo");
  289. await page.evaluate(() => window.changeYoloTarget());
  290. await dialog(page).waitFor({ state: "hidden" });
  291. assert.equal(await trigger.textContent(), before);
  292. }
  293. await page.goto(`${url}&surface=approval`);
  294. await page.getByRole("option").nth(1).click();
  295. await dialog(page).waitFor();
  296. await page.waitForFunction(
  297. () =>
  298. document.activeElement?.getAttribute("data-testid") === "yolo-confirmation-cancel",
  299. );
  300. assert.equal((await state(page)).response, "");
  301. await acknowledgeRisk(page);
  302. assert.equal((await state(page)).response, "");
  303. await page.keyboard.press("Escape");
  304. await dialog(page).waitFor({ state: "hidden" });
  305. await page.getByRole("option").first().click();
  306. assert.equal((await state(page)).response, "allowOnce");
  307. await page.goto(`${url}&surface=approval`);
  308. await page.getByRole("option").nth(1).click();
  309. await acknowledgeRisk(page);
  310. assert.equal((await state(page)).response, "");
  311. await page.getByTestId("yolo-confirmation-confirm").click();
  312. assert.equal((await state(page)).response, "fullAccess");
  313. await page.goto(`${url}&surface=approval`);
  314. await page.getByRole("option").nth(1).click();
  315. await page.evaluate(() => window.changeYoloTarget());
  316. await dialog(page).waitFor({ state: "hidden" });
  317. assert.equal((await state(page)).response, "");
  318. assert.deepEqual(errors, []);
  319. } catch (error) {
  320. await page.screenshot({
  321. path: join(artifacts, `failure-${width}-${theme}-${locale}.png`),
  322. });
  323. throw new Error(`${page.url()}: ${String(error)}`, { cause: error });
  324. } finally {
  325. await page.close();
  326. }
  327. });
  328. }