permission-full-access.test.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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/permission-full-access.fixture.tsx";
  12. let server, browser, origin;
  13. const artifacts = join(root, "packages/desktop/.e2e-artifacts/permission-full-access-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-permission-full-access"),
  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: { host: "127.0.0.1", port: 0 },
  42. });
  43. await server.listen();
  44. origin = server.resolvedUrls.local[0];
  45. browser = await chromium.launch(
  46. process.env.CHROME_EXECUTABLE_PATH
  47. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  48. : { channel: "chrome" },
  49. );
  50. });
  51. after(async () => {
  52. await browser?.close();
  53. await server?.close();
  54. });
  55. for (const proof of ["ack", "queryOnly"])
  56. test(`归属未就绪时已发送审批,${proof} 凭据仅在归属确定后写回`, async () => {
  57. const page = await browser.newPage();
  58. try {
  59. await page.goto(`${origin}fixture?grant=won&holdScope&${proof}`);
  60. await page.getByTestId("permission-allow-switch").click();
  61. await page.getByRole("button", { name: "New A" }).waitFor({ timeout: 3000 });
  62. assert.equal(await page.getByTestId("sent-options").textContent(), "allowAndSwitchGuarded");
  63. assert.deepEqual(
  64. await page.evaluate(() =>
  65. Object.keys(localStorage).filter((k) => k.startsWith("zcode-composer-recent:")),
  66. ),
  67. [],
  68. );
  69. await page.getByRole("button", { name: "Release scope" }).click();
  70. await page.waitForFunction(() =>
  71. Object.keys(localStorage).some((k) => k.startsWith("zcode-composer-recent:")),
  72. );
  73. await page.getByRole("button", { name: "New A" }).click();
  74. assert.equal(await page.getByTestId("draft-mode").textContent(), "guarded");
  75. } finally {
  76. await page.close();
  77. }
  78. });
  79. for (const current of ["build", "guarded"])
  80. test(`项目归属失败仍提交批准: ${current}`, async () => {
  81. const page = await browser.newPage();
  82. try {
  83. await page.goto(`${origin}fixture?grant=won&scopeError=1&current=${current}`);
  84. await page.getByTestId("permission-allow-switch").click();
  85. if (current === "guarded") {
  86. await page.getByTestId("yolo-confirmation-risk").click();
  87. await page.getByTestId("yolo-confirmation-confirm").click();
  88. }
  89. await page.getByRole("button", { name: "New A" }).waitFor({ timeout: 5000 });
  90. assert.deepEqual(
  91. await page.evaluate(() =>
  92. Object.keys(localStorage).filter((key) => key.startsWith("zcode-composer-recent:")),
  93. ),
  94. [],
  95. );
  96. assert.equal(
  97. await page.getByTestId("sent-options").textContent(),
  98. current === "guarded" ? "fullAccess" : "allowAndSwitchGuarded",
  99. );
  100. await page.getByRole("button", { name: "New A" }).click();
  101. assert.equal(await page.getByTestId("draft-mode").textContent(), "build");
  102. } finally {
  103. await page.close();
  104. }
  105. });
  106. for (const saved of ["guarded", "yolo"])
  107. test(`重试只允许提交 Agent 已保存的模式: ${saved}`, async () => {
  108. const page = await browser.newPage();
  109. try {
  110. await page.goto(`${origin}fixture?grant=won&mismatch=${saved}`);
  111. if (saved === "guarded") {
  112. await page.getByTestId("permission-target-picker").click();
  113. await page.getByTestId("permission-target-yolo").click();
  114. await page.getByRole("menu").waitFor({ state: "hidden" });
  115. }
  116. const action = page.getByTestId("permission-allow-switch");
  117. await action.click();
  118. const confirmRisk = async () => {
  119. await page.getByTestId("yolo-confirmation-risk").click();
  120. await page.getByTestId("yolo-confirmation-confirm").click();
  121. };
  122. if (saved === "guarded") await confirmRisk();
  123. const alert = page.getByRole("alert");
  124. await alert.waitFor();
  125. const name = saved === "guarded" ? "自主模式" : "完全访问";
  126. assert.ok((await alert.textContent()).includes(name));
  127. assert.equal(await page.getByTestId("permission-target-picker").count(), 0);
  128. assert.ok((await action.getAttribute("aria-label")).includes(name));
  129. await action.click();
  130. if (saved === "yolo") await confirmRisk();
  131. await page.getByRole("button", { name: "New A" }).click();
  132. assert.equal(await page.getByTestId("draft-mode").textContent(), saved);
  133. assert.equal(
  134. await page.getByTestId("sent-options").textContent(),
  135. saved === "guarded"
  136. ? "fullAccess,allowAndSwitchGuarded"
  137. : "allowAndSwitchGuarded,fullAccess",
  138. );
  139. } finally {
  140. await page.close();
  141. }
  142. });
  143. test("日语按独立动作和模式展示,完整无障碍名称遵循译文语序", async () => {
  144. const page = await browser.newPage();
  145. try {
  146. await page.goto(`${origin}fixture?grant=won&locale=ja-JP`);
  147. const action = page.getByTestId("permission-allow-switch");
  148. await action.waitFor();
  149. assert.ok((await action.innerText()).includes("許可してモードを変更"));
  150. const mode = (await page.getByTestId("permission-target-picker").innerText()).trim();
  151. assert.equal(await action.getAttribute("aria-label"), mode + "に切り替えて許可");
  152. } finally {
  153. await page.close();
  154. }
  155. });
  156. for (const [locale, label] of [
  157. ["ja-JP", "フルアクセスに切り替えて許可"],
  158. ["ko-KR", "허용하고 모드 전환: 전체 액세스"],
  159. ["ru-RU", "Разрешить и переключить режим на Полный доступ"],
  160. ])
  161. test(`固定模式使用完整译文语序 ${locale}`, async () => {
  162. const page = await browser.newPage();
  163. try {
  164. await page.goto(`${origin}fixture?grant=won&current=guarded&locale=${locale}`);
  165. const action = page.getByTestId("permission-allow-switch");
  166. await action.waitFor();
  167. assert.equal(await action.getAttribute("aria-label"), label);
  168. assert.equal(
  169. (await action.textContent()).replace(/^\s*\d+\.\s*/, "").replace(/\s+/g, ""),
  170. label.replace(/\s+/g, ""),
  171. );
  172. } finally {
  173. await page.close();
  174. }
  175. });
  176. for (const [grant, expected, width, theme] of [
  177. ["won", "guarded", 390, "dark"],
  178. ["stale", "build", 390, "light"],
  179. ["won", "guarded", 1200, "light"],
  180. ["won", "guarded", 1200, "dark"],
  181. ]) {
  182. test(`new project session after ${grant} approval ${width}/${theme}`, async () => {
  183. const page = await browser.newPage({
  184. viewport: { width, height: 844 },
  185. isMobile: width === 390,
  186. });
  187. try {
  188. await page.goto(`${origin}fixture?grant=${grant}&theme=${theme}`);
  189. const picker = page.getByTestId("permission-target-picker");
  190. const checkMode = async (icon, token) => {
  191. assert.equal(await picker.locator(`svg.lucide-${icon}`).count(), 1);
  192. assert.ok(
  193. await picker.evaluate((element, color) => {
  194. const probe = document.createElement("span");
  195. probe.style.color = `var(--color-${color})`;
  196. element.append(probe);
  197. const matches = getComputedStyle(element).color === getComputedStyle(probe).color;
  198. probe.remove();
  199. return matches;
  200. }, token),
  201. );
  202. };
  203. await picker.waitFor();
  204. await checkMode("shield-check", "icon-blue");
  205. await picker.click();
  206. await page.getByTestId("permission-target-yolo").waitFor();
  207. if (grant === "won" && width === 390)
  208. await page.screenshot({
  209. path: join(artifacts, "switch-mode-mobile.png"),
  210. animations: "disabled",
  211. });
  212. await page.getByTestId("permission-target-yolo").click();
  213. await page.getByRole("menu").waitFor({ state: "hidden" });
  214. await checkMode("shield-alert", "warning");
  215. assert.equal(await page.getByTestId("yolo-confirmation-dialog").count(), 0);
  216. await picker.click();
  217. await page.getByTestId("permission-target-guarded").click();
  218. await page.getByRole("menu").waitFor({ state: "hidden" });
  219. await page.getByRole("option", { name: "允许,并切换为自主模式" }).click();
  220. await page.getByRole("button", { name: "New A" }).click();
  221. assert.equal(await page.getByTestId("draft-mode").textContent(), expected);
  222. await page.getByRole("button", { name: "New B" }).click();
  223. assert.equal(await page.getByTestId("draft-mode").textContent(), "build");
  224. } finally {
  225. await page.close();
  226. }
  227. });
  228. }
  229. test("自主模式只显示切到完全访问的动作", async () => {
  230. const page = await browser.newPage();
  231. try {
  232. await page.goto(`${origin}fixture?grant=won&current=guarded`);
  233. const action = page.getByRole("option", { name: "允许,并切换为完全访问" });
  234. await action.waitFor();
  235. assert.equal(await page.getByTestId("permission-target-picker").count(), 0);
  236. await action.click();
  237. await page.getByTestId("yolo-confirmation-dialog").getByRole("checkbox").check();
  238. await page.getByTestId("yolo-confirmation-confirm").click();
  239. await page.getByRole("button", { name: "New A" }).click();
  240. assert.equal(await page.getByTestId("draft-mode").textContent(), "yolo");
  241. } finally {
  242. await page.close();
  243. }
  244. });
  245. for (const width of [390, 1200])
  246. for (const theme of ["light", "dark"]) {
  247. test(`PA158 shared approval UI ${width}/${theme}`, async () => {
  248. const page = await browser.newPage({ viewport: { width, height: 1000 } });
  249. const errors = [];
  250. page.on("pageerror", (error) => errors.push(error.message));
  251. try {
  252. const mobile = width === 390;
  253. await page.goto(`${origin}fixture?theme=${theme}&locale=${mobile ? "zh-CN" : "en-US"}`);
  254. const options = page.getByRole("option");
  255. await options.first().waitFor();
  256. assert.equal(await options.count(), 4);
  257. assert.equal(
  258. await options.nth(1).getAttribute("aria-label"),
  259. mobile ? "始终允许此命令" : "Always allow this command",
  260. );
  261. assert.equal(
  262. await options.nth(2).getAttribute("aria-label"),
  263. mobile ? "完全访问" : "Full access",
  264. );
  265. await options.first().focus();
  266. await page.keyboard.press("5");
  267. // 权限选项通过 RAF 转移焦点,等待真实焦点落点,避免在同帧抢先断言。
  268. await page.waitForFunction(() => document.activeElement?.tagName === "TEXTAREA");
  269. assert.equal(
  270. await page.getByRole("textbox").evaluate((el) => document.activeElement === el),
  271. true,
  272. );
  273. assert.equal(await page.getByTestId("response").textContent(), "");
  274. assert.equal(
  275. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  276. true,
  277. );
  278. await page.screenshot({ path: join(artifacts, `${width}-${theme}.png`), fullPage: true });
  279. await options.first().focus();
  280. await page.keyboard.press("3");
  281. await page.getByTestId("yolo-confirmation-dialog").waitFor();
  282. assert.equal(await page.getByTestId("response").textContent(), "");
  283. assert.equal(await page.getByTestId("yolo-confirmation-confirm").isDisabled(), true);
  284. await page.getByTestId("yolo-confirmation-dialog").getByRole("checkbox").check();
  285. await page.getByTestId("yolo-confirmation-confirm").click();
  286. await page.waitForFunction(
  287. () => document.querySelector('[data-testid="response"]')?.textContent === "fullAccess",
  288. );
  289. assert.deepEqual(errors, []);
  290. } finally {
  291. await page.close();
  292. }
  293. });
  294. }
  295. for (const width of [390, 1200])
  296. for (const theme of ["light", "dark"]) {
  297. test(`long permission command ${width}/${theme}`, async () => {
  298. const page = await browser.newPage({ viewport: { width, height: 900 } });
  299. try {
  300. await page.goto(`${origin}fixture?theme=${theme}&command=long`);
  301. const command = page.getByTestId("execute-command");
  302. await command.waitFor();
  303. assert.equal(await page.getByText("没有输出。", { exact: true }).count(), 0);
  304. const toggle = page.getByRole("button", { name: "展开命令", exact: true });
  305. await toggle.waitFor();
  306. assert.equal(await toggle.getAttribute("aria-expanded"), "false");
  307. assert.equal(
  308. await toggle.evaluate(
  309. (el) => el.previousElementSibling?.getAttribute("data-testid") === "execute-command",
  310. ),
  311. true,
  312. );
  313. const alignment = await toggle.evaluate((el) => {
  314. const text = el.parentElement.querySelector("pre");
  315. const range = document.createRange();
  316. range.selectNodeContents(el.firstChild);
  317. return Math.abs(range.getBoundingClientRect().left - text.getBoundingClientRect().left);
  318. });
  319. assert.ok(alignment < 0.1, `command toggle text alignment: ${alignment}`);
  320. assert.equal(
  321. await command.evaluate(
  322. (el) => el.clientHeight / Number.parseFloat(getComputedStyle(el).lineHeight),
  323. ),
  324. 3,
  325. );
  326. assert.match(
  327. await toggle.evaluate((el) => getComputedStyle(el).backgroundColor),
  328. /^rgba\([^,]+, [^,]+, [^,]+, 0\)$/,
  329. );
  330. assert.equal(await toggle.locator("svg").count(), 1);
  331. assert.deepEqual(
  332. await toggle.evaluate((el) => {
  333. const style = getComputedStyle(el);
  334. return [
  335. el.dataset.variant,
  336. style.paddingLeft,
  337. style.paddingRight,
  338. style.borderLeftWidth,
  339. style.borderRightWidth,
  340. ];
  341. }),
  342. ["link", "0px", "0px", "0px", "0px"],
  343. );
  344. await page.screenshot({
  345. path: join(artifacts, `command-collapsed-${width}-${theme}.png`),
  346. fullPage: true,
  347. });
  348. await page.waitForFunction(() => document.activeElement?.getAttribute("role") === "option");
  349. await page.keyboard.press("Shift+Tab");
  350. assert.equal(await toggle.evaluate((el) => document.activeElement === el), true);
  351. await page.keyboard.press("Enter");
  352. assert.equal(
  353. await page
  354. .getByRole("button", { name: "收起", exact: true })
  355. .getAttribute("aria-expanded"),
  356. "true",
  357. );
  358. assert.equal(await page.getByTestId("response").textContent(), "");
  359. await page.keyboard.press("Tab");
  360. assert.equal(
  361. await page
  362. .getByRole("option")
  363. .first()
  364. .evaluate((el) => document.activeElement === el),
  365. true,
  366. );
  367. await page.keyboard.press("Shift+Tab");
  368. await page.keyboard.press("Shift+Tab");
  369. assert.equal(await command.evaluate((el) => document.activeElement === el), true);
  370. const collapse = page.getByRole("button", { name: "收起", exact: true });
  371. await page.waitForFunction(() => {
  372. const button = document.querySelector('button[aria-expanded="true"]');
  373. return (
  374. button &&
  375. /^rgba\([^,]+, [^,]+, [^,]+, 0\)$/.test(getComputedStyle(button).backgroundColor)
  376. );
  377. });
  378. assert.equal(await collapse.locator("svg.rotate-180").count(), 1);
  379. const collapseBefore = await collapse.boundingBox();
  380. const geometry = await command.evaluate((el) => {
  381. const card = el.closest('[data-testid="execute-detail"]');
  382. const style = getComputedStyle(card);
  383. const rightInset =
  384. card.getBoundingClientRect().right -
  385. Number.parseFloat(style.borderRightWidth) -
  386. el.getBoundingClientRect().right;
  387. const prompt = el.querySelector('[data-testid="execute-command-prompt"]');
  388. if (!prompt) throw new Error("Command prompt must be inside the viewport");
  389. const promptTop = prompt.getBoundingClientRect().top;
  390. el.scrollTop = el.scrollHeight;
  391. const promptScrolled =
  392. prompt.getBoundingClientRect().top < el.getBoundingClientRect().top;
  393. el.scrollTop = 0;
  394. const promptRestored = prompt.getBoundingClientRect().top === promptTop;
  395. el.scrollTop = el.scrollHeight;
  396. return {
  397. promptScrolled,
  398. promptRestored,
  399. rightInset,
  400. end: el.scrollTop + el.clientHeight >= el.scrollHeight - 1,
  401. overflow: getComputedStyle(el).overflowY,
  402. complete: el.textContent.endsWith('COMMAND_END"'),
  403. };
  404. });
  405. assert.deepEqual(geometry, {
  406. rightInset: 4,
  407. end: true,
  408. overflow: "auto",
  409. complete: true,
  410. promptScrolled: true,
  411. promptRestored: true,
  412. });
  413. assert.deepEqual(await collapse.boundingBox(), collapseBefore);
  414. assert.equal(
  415. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  416. true,
  417. );
  418. await page.screenshot({
  419. path: join(artifacts, `command-${width}-${theme}.png`),
  420. fullPage: true,
  421. });
  422. await page.getByRole("button", { name: "收起", exact: true }).click();
  423. await page.getByRole("button", { name: "展开命令", exact: true }).waitFor();
  424. await page.getByRole("option").first().click();
  425. assert.equal(await page.getByTestId("response").textContent(), "allowOnce");
  426. await page.goto(`${origin}fixture?theme=${theme}`);
  427. await page.getByRole("option").first().waitFor();
  428. assert.equal(await page.getByRole("button", { name: "展开命令", exact: true }).count(), 0);
  429. } finally {
  430. await page.close();
  431. }
  432. });
  433. }