browser-design-mode.test.ts 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. import { chmod, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
  2. import type { Server } from "node:http";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { pathToFileURL } from "node:url";
  6. import { Key } from "webdriverio";
  7. import {
  8. TID_BROWSER_DESIGN_INSPECTOR,
  9. TID_BROWSER_DESIGN_PANEL_BUTTON,
  10. TID_BROWSER_DESIGN_SLIDE_COUNTER,
  11. TID_BROWSER_DESIGN_SLIDE_NEXT,
  12. TID_BROWSER_DESIGN_SOURCE_STATUS,
  13. TID_BROWSER_DESIGN_TOOLBAR,
  14. TID_BROWSER_ELEMENT_PICKER_BUTTON,
  15. TID_BROWSER_REFRESH_BUTTON,
  16. TID_SIDE_PANE_FULL_VIEW_HOST,
  17. TID_WEB_ELEMENT_CONTEXT_CHIP,
  18. } from "@zcode/shared/test-ids";
  19. import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  20. import {
  21. clickCloseButton,
  22. openFirstBrowserTab,
  23. readBrowserTabIds,
  24. waitForTabCount,
  25. } from "#e2e/helpers/browser-side-pane";
  26. import {
  27. enableDesignPlugin,
  28. clickGuestElement,
  29. ELEMENT_TOKEN_SELECTOR,
  30. closeFixtureServer,
  31. countElementTokens,
  32. deleteLastElementToken,
  33. guestEval,
  34. hasReadyAttachment,
  35. holdGuestCapture,
  36. navigateBrowser,
  37. pressGuestUndo,
  38. readHeldCaptureCalls,
  39. releaseHeldCapture,
  40. selectGuestElement,
  41. startFixtureServer,
  42. typeAfterLastElementToken,
  43. readDataCount,
  44. waitForElementTokens,
  45. waitForReadyAttachment,
  46. waitForTestIdText,
  47. } from "#e2e/helpers/browser-design-mode";
  48. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  49. import { clickV4Send, prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  50. // 内置浏览器设计工具(docs/browser-use/2026-11-03-browser-design-mode-spec.md):
  51. // 普通页面不出设计工具行;设计稿页面自动出现。点选 = 选中元素作为网页元素引用进输入框(Shift 多选、普通点击替换),
  52. // 属性面板改数值直接写回本机 HTML 源文件、页面不刷新,Cmd/Ctrl + Z 撤销、加 Shift 重做。
  53. // 页面里的点击用 main 侧 sendInputEvent 发真实鼠标事件,与用户在 guest 里点击同一条路径。
  54. const MOD = process.platform === "darwin" ? Key.Command : Key.Control;
  55. /** 本机 HTML 经 zcode-html:// 预览协议加载 */
  56. const LOCAL_GUEST_PREFIX = "zcode-html://";
  57. const PLAIN_HTML = `<!doctype html><html><head><title>E2E plain page</title></head>
  58. <body><p id="plain">E2E_PLAIN</p></body></html>`;
  59. const FIXTURE_HTML = `<!doctype html>
  60. <html data-zcode-design><head><title>E2E design mode</title>
  61. <style>
  62. :root { --brand: #ff6b35; --title-size: 40px; --veil: rgba(34, 85, 238, 0.5); }
  63. body { margin: 0; font-family: sans-serif; }
  64. section.slide { height: 100vh; padding: 40px; box-sizing: border-box; }
  65. h1 { font-size: var(--title-size); }
  66. .cta { padding: 12px 20px; background: var(--brand); border-radius: 12px; color: #fff; border: 0; }
  67. #imp { font-size: 30px !important; }
  68. </style></head>
  69. <body>
  70. <section class="slide" id="s1"><h1 id="title">E2E_DESIGN_TITLE</h1><button class="cta" id="cta">E2E_DESIGN_CTA</button><p id="note" style="color: /* brand */ #111; /* note; a: b */ padding: 8px">E2E_NOTE</p><p id="todo" style="color: #222; /* todo">E2E_TODO</p><p id="imp" style="font-size: 18px !important">E2E_IMP</p><button id="bgimp" style="background: red !important">E2E_BGIMP</button></section>
  71. <section class="slide" id="s2"><h2>Second</h2></section>
  72. <section class="slide" id="s3"><h2>Third</h2></section>
  73. </body></html>`;
  74. let fixtureServer: Server | null = null;
  75. let fixtureOrigin = "";
  76. let fixtureUrl = "";
  77. let localDir = "";
  78. let localFile = "";
  79. /** 属性面板里的选中数;没有选中时面板收起、读不到,按 0 算 */
  80. async function readInspectorSelectedCount(): Promise<string> {
  81. return (await browser.execute(
  82. (id) =>
  83. document.querySelector(`[data-testid="${id}"]`)?.getAttribute("data-selected-count") ?? "0",
  84. TID_BROWSER_DESIGN_INSPECTOR,
  85. )) as string;
  86. }
  87. /** 同一个 app 里连跑多条用例:关掉当前界面上的浏览器 tab,下一条从一个 tab 起步,也不留隐藏的旧地址栏、旧页面。 */
  88. async function closeBrowserTabs(): Promise<void> {
  89. for (const tabId of await readBrowserTabIds()) await clickCloseButton(tabId);
  90. await waitForTabCount(0);
  91. }
  92. async function openFreshBrowserTab(): Promise<void> {
  93. await closeBrowserTabs();
  94. await clearElementTokens();
  95. await openFirstBrowserTab();
  96. }
  97. /** 草稿输入框跨用例保留:像用户一样全选删掉上一条留下的元素引用(程序改写不撤元素上下文,新选中时旧引用会被补回来) */
  98. async function clearElementTokens(): Promise<void> {
  99. for (let attempt = 0; attempt < 5 && (await countElementTokens()) > 0; attempt += 1) {
  100. await browser.execute((selector) => {
  101. document.querySelector(selector)?.closest<HTMLElement>("[contenteditable=true]")?.focus();
  102. }, ELEMENT_TOKEN_SELECTOR);
  103. await browser.keys([MOD, "a"]);
  104. await browser.keys("Backspace");
  105. await browser.pause(300);
  106. }
  107. await waitForElementTokens(0, "清空输入框后不应还留着元素引用");
  108. }
  109. describe("BU-E2E-021:内置浏览器设计工具", () => {
  110. before(async () => {
  111. ({ server: fixtureServer, origin: fixtureOrigin } = await startFixtureServer(
  112. (request, response) => {
  113. response.setHeader("content-type", "text/html; charset=utf-8");
  114. response.end(request.url?.startsWith("/plain") ? PLAIN_HTML : FIXTURE_HTML);
  115. },
  116. ));
  117. fixtureUrl = `${fixtureOrigin}/design`;
  118. localDir = await mkdtemp(join(tmpdir(), "zcode-e2e-design-"));
  119. localFile = join(localDir, "design.html");
  120. });
  121. // 首发后界面在新任务里,它的浏览器会常驻(隐藏):在这里关掉,后面用例的 $() 才不会拿到它的元素
  122. afterEach(async () => {
  123. // 先在还开着的输入框里删掉引用,再关 tab:关掉后那份引用就看不到、删不着了
  124. await clearElementTokens().catch(() => undefined);
  125. await closeBrowserTabs().catch(() => undefined);
  126. });
  127. after(async () => {
  128. await closeFixtureServer(fixtureServer);
  129. fixtureServer = null;
  130. if (localDir) await rm(localDir, { recursive: true, force: true });
  131. await clearAppData();
  132. });
  133. it("设计工具随页面出现;点选元素进输入框成引用(Shift 多选、普通点击替换),翻页,首发带引用与截图", async function () {
  134. this.timeout(240_000);
  135. await prepareV4ConversationE2E();
  136. await enableDesignPlugin();
  137. await openFreshBrowserTab();
  138. // 普通页面:没有设计稿信号,不出设计工具行。
  139. await navigate(`${fixtureOrigin}/plain`, "E2E plain page");
  140. await browser.pause(1_500);
  141. if (await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).isExisting()) {
  142. throw new Error("普通页面不应出现设计工具行");
  143. }
  144. // 本机 HTML 没有 data-zcode-design、只有 :root 变量:经 zcode-html:// 预览打开也算本机页面,自动出现设计工具(!3450 CR-01)
  145. const variablesFile = join(localDir, "variables.html");
  146. await writeFile(
  147. variablesFile,
  148. `<!doctype html><html><head><title>E2E local variables</title><style>:root { --brand: #ff6b35; }</style></head><body><p>E2E_VARIABLES</p></body></html>`,
  149. "utf-8",
  150. );
  151. await navigateBrowser(
  152. pathToFileURL(variablesFile).href,
  153. "E2E local variables",
  154. LOCAL_GUEST_PREFIX,
  155. );
  156. await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).waitForDisplayed({
  157. timeout: 15_000,
  158. timeoutMsg: "本机带 :root 变量的页面应自动出现设计工具行",
  159. });
  160. // 设计稿页面:自动出现设计工具行与翻页。
  161. await navigate(fixtureUrl, "E2E design mode");
  162. await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).waitForDisplayed({
  163. timeout: 15_000,
  164. timeoutMsg: "设计稿页面没有自动出现设计工具行",
  165. });
  166. await waitForTestIdText(TID_BROWSER_DESIGN_SLIDE_COUNTER, "1 / 3");
  167. // 点 #cta:属性面板打开,输入框出现 1 个元素引用 + element-1.png
  168. await selectGuestElement(fixtureOrigin, "#cta");
  169. await waitForElementTokens(1, "点选后输入框没有出现元素引用");
  170. // 选中元素不把对话挤成浮窗:留在半屏,面板在画布右侧打开(11-11 用户反馈)
  171. await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForDisplayed({
  172. timeout: 10_000,
  173. timeoutMsg: "设计稿选中元素后应打开调整面板",
  174. });
  175. await browser.pause(1_000);
  176. await waitForFullView(false, "选中元素后不应进完整视图");
  177. await waitForReadyAttachment("element-1.png");
  178. // http 页面不是本机文件:面板写明不能直接写回
  179. await browser.waitUntil(
  180. async () =>
  181. (await $(`[data-testid="${TID_BROWSER_DESIGN_SOURCE_STATUS}"]`).getAttribute(
  182. "data-writable",
  183. )) === "false",
  184. { timeout: 10_000, timeoutMsg: "http 页面不应能写回源文件" },
  185. );
  186. // Shift + 点 #title:两个元素都在
  187. await selectGuestElement(fixtureOrigin, "#title", { shift: true, selectedCount: "2" });
  188. await waitForElementTokens(2, "Shift 点选后输入框不是 2 个元素");
  189. await waitForReadyAttachment("element-2.png");
  190. // 普通点 #cta:替换选中,#title 的引用和截图撤回
  191. await selectGuestElement(fixtureOrigin, "#cta");
  192. await waitForElementTokens(1, "普通点击后应只剩 1 个元素引用");
  193. await browser.waitUntil(
  194. async () =>
  195. !(await hasReadyAttachment("element-2.png")) && (await hasReadyAttachment("element-1.png")),
  196. { timeout: 10_000, timeoutMsg: "替换选中后截图没有对应:应只剩 element-1.png" },
  197. );
  198. // 翻页:下一页 → 计数 2 / 3,页面滚到第二个 slide。
  199. await clickTestIdByDom(TID_BROWSER_DESIGN_SLIDE_NEXT);
  200. await waitForTestIdText(TID_BROWSER_DESIGN_SLIDE_COUNTER, "2 / 3");
  201. await browser.waitUntil(
  202. async () =>
  203. Number(
  204. await guestEval(
  205. fixtureOrigin,
  206. "Math.round(document.getElementById('s2').getBoundingClientRect().top)",
  207. ),
  208. ) === 0,
  209. { timeout: 10_000, timeoutMsg: "翻页后页面没有滚到第二个 slide" },
  210. );
  211. // 草稿首发:上游请求带元素引用块与截图附件占位(E2E 模型不支持图片时 CLI 只留占位)
  212. await typeAfterLastElementToken(" E2E_DESIGN_SEND make it bigger");
  213. await clickV4Send();
  214. await waitForUpstreamRequest(
  215. {
  216. includes: [
  217. "E2E_DESIGN_SEND",
  218. "# Web page elements:",
  219. "E2E_DESIGN_CTA",
  220. "](zcode-element://",
  221. "[Attached image/png: element-1.png]",
  222. ],
  223. },
  224. "草稿首发的上游请求里没有元素引用或 element-1.png 截图附件",
  225. 45_000,
  226. );
  227. });
  228. it("截图在途时换了选中:不加已取消选中的元素,只引用最后选中的", async function () {
  229. this.timeout(120_000);
  230. await prepareV4ConversationE2E();
  231. await enableDesignPlugin();
  232. await openFreshBrowserTab();
  233. await navigate(fixtureUrl, "E2E design mode");
  234. await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).waitForDisplayed({ timeout: 15_000 });
  235. await holdGuestCapture(fixtureOrigin);
  236. try {
  237. await selectGuestElement(fixtureOrigin, "#cta");
  238. await browser.waitUntil(async () => (await readHeldCaptureCalls()) >= 1, {
  239. timeout: 10_000,
  240. timeoutMsg: "点选后没有开始截图",
  241. });
  242. await selectGuestElement(fixtureOrigin, "#title");
  243. } finally {
  244. await releaseHeldCapture();
  245. }
  246. await waitForElementTokens(1, "截图回来后应只引用 #title");
  247. await browser.pause(1_500);
  248. const tokens = await countElementTokens();
  249. if (tokens !== 1) throw new Error(`截图在途时取消选中的元素不应进输入框,实际 ${tokens} 个`);
  250. });
  251. it("属性面板改数值直接写回本机 HTML,页面不刷新;Cmd/Ctrl + Z 撤销、Shift 重做;页面变量写 :root;脚本生成的元素只读", async function () {
  252. this.timeout(240_000);
  253. await writeFile(localFile, FIXTURE_HTML, "utf-8");
  254. await prepareV4ConversationE2E();
  255. await enableDesignPlugin();
  256. await openFreshBrowserTab();
  257. await navigateBrowser(pathToFileURL(localFile).href, "E2E design mode", LOCAL_GUEST_PREFIX);
  258. await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eMark = 1");
  259. await selectGuestElement(LOCAL_GUEST_PREFIX, "#title");
  260. await waitForWritable("true", "本机 HTML 里的标题应能写回");
  261. await fillField("[data-design-field=fontSize]", "46");
  262. await waitForSource(
  263. (source) =>
  264. source ===
  265. FIXTURE_HTML.replace('<h1 id="title">', '<h1 id="title" style="font-size: 46px">'),
  266. "改字号后源文件应只多了标题的 style",
  267. );
  268. await waitForGuest("getComputedStyle(document.getElementById('title')).fontSize", "46px");
  269. // 焦点还在字段上(没有未提交的输入):Cmd/Ctrl + Z 撤销的是写回
  270. await browser.keys([MOD, "z"]);
  271. await waitForSource((source) => source === FIXTURE_HTML, "撤销后源文件应回到原样");
  272. await waitForGuest("getComputedStyle(document.getElementById('title')).fontSize", "40px");
  273. await waitForFieldValue("[data-design-field=fontSize]", "40");
  274. await browser.keys([MOD, Key.Shift, "z"]);
  275. await waitForSource(
  276. (source) => source.includes('<h1 id="title" style="font-size: 46px">'),
  277. "重做后源文件应再次是 46px",
  278. );
  279. // 页面上的真实 Cmd/Ctrl + Z(guest preload 收 isTrusted 按键,!3450 CR-01):焦点在页面空白处时撤销 / 重做写回
  280. const WRITTEN = FIXTURE_HTML.replace(
  281. '<h1 id="title">',
  282. '<h1 id="title" style="font-size: 46px">',
  283. );
  284. await pressGuestUndo(LOCAL_GUEST_PREFIX);
  285. await waitForSource((source) => source === FIXTURE_HTML, "页面上按撤销应还原源文件");
  286. await pressGuestUndo(LOCAL_GUEST_PREFIX, { redo: true });
  287. await waitForSource((source) => source === WRITTEN, "页面上按重做应再次写回");
  288. // 页面脚本伪造的按键(isTrusted 为 false)不触发写回
  289. await guestEval(
  290. LOCAL_GUEST_PREFIX,
  291. `(() => { for (const target of [window, document, document.body]) target.dispatchEvent(new KeyboardEvent("keydown", { key: "z", metaKey: true, ctrlKey: true, bubbles: true })); return true; })()`,
  292. );
  293. await browser.pause(1_500);
  294. if ((await readFile(localFile, "utf-8")) !== WRITTEN) {
  295. throw new Error("页面伪造的撤销按键不应改动源文件");
  296. }
  297. // 焦点在页面自己的输入框里(含 open Shadow DOM 里的):Cmd/Ctrl + Z 归页面撤销输入,不撤写回
  298. await guestEval(
  299. LOCAL_GUEST_PREFIX,
  300. `(() => { const input = document.createElement("input"); input.id = "e2e-page-input"; document.body.prepend(input); const host = document.createElement("div"); host.id = "e2e-shadow-host"; document.body.prepend(host); host.attachShadow({ mode: "open", delegatesFocus: true }).append(document.createElement("input")); return true; })()`,
  301. );
  302. await pressGuestUndo(LOCAL_GUEST_PREFIX, { focusSelector: "#e2e-page-input" });
  303. await pressGuestUndo(LOCAL_GUEST_PREFIX, { focusSelector: "#e2e-shadow-host" });
  304. await browser.pause(1_500);
  305. if ((await readFile(localFile, "utf-8")) !== WRITTEN) {
  306. throw new Error("焦点在页面输入框里时按撤销不应改动源文件");
  307. }
  308. // 插进去的两个节点要删掉:写回按 <html> 往下每级的兄弟数对源码,多出节点后整页元素都会判成写不回
  309. await guestEval(
  310. LOCAL_GUEST_PREFIX,
  311. `(() => { document.getElementById("e2e-page-input")?.remove(); document.getElementById("e2e-shadow-host")?.remove(); return true; })()`,
  312. );
  313. // 多选后改圆角:两个元素都写回
  314. await selectGuestElement(LOCAL_GUEST_PREFIX, "#cta", { shift: true, selectedCount: "2" });
  315. await waitForWritable("true", "两个元素都应能写回");
  316. await fillField("[data-design-field=borderRadius]", "4");
  317. await waitForSource(
  318. (source) =>
  319. source.includes('<h1 id="title" style="font-size: 46px; border-radius: 4px">') &&
  320. source.includes('<button class="cta" id="cta" style="border-radius: 4px">'),
  321. "多选改圆角应写到两个元素上",
  322. );
  323. // 填充的不透明度:写成 rgba()
  324. await selectGuestElement(LOCAL_GUEST_PREFIX, "#cta");
  325. await fillField("[data-design-alpha=background]", "50");
  326. await waitForSource(
  327. (source) => source.includes("background-color: rgba(255, 107, 53, 0.5)"),
  328. "改填充不透明度应写成 rgba()",
  329. );
  330. // 页面变量::root 里那条声明的值改掉
  331. await fillField('[data-design-variable="--title-size"]', "52");
  332. await waitForSource(
  333. (source) => source.includes("--title-size: 52px;"),
  334. "改页面变量应改 :root 里的声明",
  335. );
  336. // 字段里输入新值按 Esc:放弃输入,源文件不变、字段显示原值(!3450 CR-03)
  337. const beforeEscape = await readFile(localFile, "utf-8");
  338. // 完整视图里浮动输入框可能盖住面板下沿,按 DOM 聚焦,不靠坐标点击
  339. await browser.execute(() => {
  340. const field = document.querySelector<HTMLInputElement>(
  341. '[data-design-variable="--title-size"]',
  342. );
  343. field?.focus();
  344. field?.select();
  345. });
  346. await browser.keys("61".split(""));
  347. await browser.keys("Escape");
  348. await waitForFieldValue('[data-design-variable="--title-size"]', "52");
  349. await browser.pause(1_000);
  350. if ((await readFile(localFile, "utf-8")) !== beforeEscape) {
  351. throw new Error("按 Esc 放弃的输入不应写进源文件");
  352. }
  353. // 变量用自定义取色器改色:预览会先改掉字段值,关弹层时仍要写回(!3450 CR-02)
  354. const brandSwatch = await $('[data-design-variable="--brand"]').parentElement().$("button");
  355. await brandSwatch.click();
  356. await browser.execute(() => {
  357. const picker = document.querySelector<HTMLInputElement>('input[type="color"]');
  358. if (!picker) throw new Error("自定义取色器没有出现");
  359. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
  360. picker,
  361. "#2255ee",
  362. );
  363. picker.dispatchEvent(new Event("input", { bubbles: true }));
  364. });
  365. await browser.keys("Escape");
  366. await waitForSource(
  367. (source) => source.includes("--brand: #2255EE;"),
  368. "自定义取色后关弹层应把颜色写进 :root",
  369. );
  370. // 透明的原色:取色器里换一个颜色再选回原色(取色器给大写 hex)后关弹层,不写回、预览还原成透明(!3450 SG-01)
  371. await fillField('[data-design-alpha="--brand"]', "0");
  372. await waitForSource(
  373. (source) => source.includes("--brand: rgba(34, 85, 238, 0);"),
  374. "把不透明度改成 0 应写成透明的 rgba()",
  375. );
  376. const beforeRepick = await readFile(localFile, "utf-8");
  377. await brandSwatch.click();
  378. await browser.execute(() => {
  379. const picker = document.querySelector<HTMLInputElement>('input[type="color"]');
  380. if (!picker) throw new Error("自定义取色器没有出现");
  381. const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  382. for (const color of ["#ff0000", "#2255ee"]) {
  383. setValue?.call(picker, color);
  384. picker.dispatchEvent(new Event("input", { bubbles: true }));
  385. }
  386. });
  387. await browser.keys("Escape");
  388. await waitForGuest(
  389. "getComputedStyle(document.documentElement).getPropertyValue('--brand').trim()",
  390. "rgba(34, 85, 238, 0)",
  391. );
  392. await browser.pause(1_000);
  393. if ((await readFile(localFile, "utf-8")) !== beforeRepick) {
  394. throw new Error("选回原色关弹层不应写回源文件");
  395. }
  396. // 取色器先取到色板上某个颜色(含吸管取到同色),再点这个色块:仍要写回(!3450 SG-01)
  397. await brandSwatch.click();
  398. const paletteHex = (await browser.execute(() => {
  399. const swatch = [...document.querySelectorAll<HTMLButtonElement>("button[aria-label]")].find(
  400. (button) =>
  401. /#[0-9A-F]{6}$/iu.test(button.getAttribute("aria-label") ?? "") &&
  402. !/2255ee/iu.test(button.getAttribute("aria-label") ?? ""),
  403. );
  404. const picker = document.querySelector<HTMLInputElement>('input[type="color"]');
  405. if (!swatch || !picker) throw new Error("色板或自定义取色器没有出现");
  406. const hex = (swatch.getAttribute("aria-label") ?? "").slice(-7);
  407. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
  408. picker,
  409. hex.toLowerCase(),
  410. );
  411. picker.dispatchEvent(new Event("input", { bubbles: true }));
  412. swatch.setAttribute("data-e2e-palette", "1");
  413. return hex;
  414. })) as string;
  415. await $('[data-e2e-palette="1"]').click();
  416. await waitForSource(
  417. (source) => source.toLowerCase().includes(`--brand: ${paletteHex.toLowerCase()};`),
  418. "取色器取到色板同色后点色块应写回",
  419. );
  420. // 取色器预览成别的颜色后,再点当前原色的色块:不写回,页面预览还原成原值(!3450 CR-01)
  421. const brandBefore = (await guestEval(
  422. LOCAL_GUEST_PREFIX,
  423. "getComputedStyle(document.documentElement).getPropertyValue('--brand').trim()",
  424. )) as string;
  425. const beforeSwatchBack = await readFile(localFile, "utf-8");
  426. // 上一步点色块后弹层可能还开着:先关掉,再从关闭状态打开
  427. await browser.keys("Escape");
  428. await brandSwatch.click();
  429. await browser.execute((original) => {
  430. const picker = document.querySelector<HTMLInputElement>('input[type="color"]');
  431. const swatch = [...document.querySelectorAll<HTMLButtonElement>("button[aria-label]")].find(
  432. (button) =>
  433. (button.getAttribute("aria-label") ?? "").toLowerCase().endsWith(original.toLowerCase()),
  434. );
  435. if (!picker || !swatch) throw new Error("色板或自定义取色器没有出现");
  436. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
  437. picker,
  438. "#ff0000",
  439. );
  440. picker.dispatchEvent(new Event("input", { bubbles: true }));
  441. swatch.setAttribute("data-e2e-palette-back", "1");
  442. }, paletteHex);
  443. await $('[data-e2e-palette-back="1"]').click();
  444. await waitForGuest(
  445. "getComputedStyle(document.documentElement).getPropertyValue('--brand').trim()",
  446. brandBefore,
  447. );
  448. await browser.pause(1_000);
  449. if ((await readFile(localFile, "utf-8")) !== beforeSwatchBack) {
  450. throw new Error("预览后点回原色色块不应写回源文件");
  451. }
  452. await browser.keys("Escape");
  453. // 同一个弹层里先点色块写回,再用取色器回到点之前的颜色、关弹层:写回取色器的颜色,页面与源码一致(!3450 CR-01)
  454. await brandSwatch.click();
  455. const otherHex = (await browser.execute((original) => {
  456. const other = [...document.querySelectorAll<HTMLButtonElement>("button[aria-label]")].find(
  457. (button) => {
  458. const label = (button.getAttribute("aria-label") ?? "").toLowerCase();
  459. return /#[0-9a-f]{6}$/u.test(label) && !label.endsWith(original.toLowerCase());
  460. },
  461. );
  462. if (!other) throw new Error("色板里没有别的颜色");
  463. other.click();
  464. return (other.getAttribute("aria-label") ?? "").slice(-7);
  465. }, paletteHex)) as string;
  466. await browser.waitUntil(
  467. async () =>
  468. (await $('[data-design-variable="--brand"]').getValue()).toLowerCase() ===
  469. otherHex.slice(1).toLowerCase(),
  470. { timeout: 10_000, timeoutMsg: "点色块写回后字段应显示色块的颜色" },
  471. );
  472. await browser.execute((original) => {
  473. const picker = document.querySelector<HTMLInputElement>('input[type="color"]');
  474. if (!picker) throw new Error("自定义取色器没有出现");
  475. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
  476. picker,
  477. original.toLowerCase(),
  478. );
  479. picker.dispatchEvent(new Event("input", { bubbles: true }));
  480. }, paletteHex);
  481. await browser.keys("Escape");
  482. await waitForSource(
  483. (source) => source.toLowerCase().includes(`--brand: ${paletteHex.toLowerCase()};`),
  484. "色块写回后再用取色器回到原色,关弹层应写回取色器的颜色",
  485. );
  486. await waitForGuest(
  487. "getComputedStyle(document.documentElement).getPropertyValue('--brand').trim().toLowerCase()",
  488. paletteHex.toLowerCase(),
  489. );
  490. // 半透明的页面变量:面板显示原来的不透明度,只改颜色写回仍是半透明(!3450 CR-02)
  491. // 上一个弹层关闭有动画,等它卸掉再开下一个,免得拿到它的取色器
  492. await browser.waitUntil(
  493. async () =>
  494. (await browser.execute(() => document.querySelectorAll('input[type="color"]').length)) ===
  495. 0,
  496. { timeout: 5_000, timeoutMsg: "上一个颜色弹层没有关掉" },
  497. );
  498. await waitForFieldValue('[data-design-alpha="--veil"]', "50");
  499. // 这一格在面板下沿,完整视图里会被浮动输入框盖住:滚到中间再按 DOM 点开
  500. await browser.execute(() => {
  501. const trigger = document
  502. .querySelector('[data-design-variable="--veil"]')
  503. ?.parentElement?.querySelector<HTMLButtonElement>("button");
  504. trigger?.scrollIntoView({ block: "center" });
  505. trigger?.click();
  506. });
  507. await browser.execute(() => {
  508. const picker = document.querySelector<HTMLInputElement>(
  509. '[data-state="open"] input[type="color"]',
  510. );
  511. if (!picker) throw new Error("自定义取色器没有出现");
  512. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
  513. picker,
  514. "#ff0000",
  515. );
  516. picker.dispatchEvent(new Event("input", { bubbles: true }));
  517. });
  518. await browser.keys("Escape");
  519. await waitForSource(
  520. (source) => source.includes("--veil: rgba(255, 0, 0, 0.5);"),
  521. "半透明变量只改颜色,写回应保留 0.5 的不透明度",
  522. );
  523. // 内联 style 里有 CSS 注释(声明之间的带分号、冒号,值里也有一段):改别的属性,注释和其余声明原样保留(!3450 CR-03)
  524. await selectGuestElement(LOCAL_GUEST_PREFIX, "#note");
  525. await waitForWritable("true", "带注释 style 的元素应能写回");
  526. await fillField("[data-design-field=fontSize]", "20");
  527. await waitForSource(
  528. (source) =>
  529. source.includes(
  530. '<p id="note" style="color: /* brand */ #111; /* note; a: b */ padding: 8px; font-size: 20px">',
  531. ),
  532. "带注释的内联 style 写回后注释与其余声明应原样保留",
  533. );
  534. await waitForGuest("getComputedStyle(document.getElementById('note')).paddingTop", "8px");
  535. await waitForGuest(
  536. "getComputedStyle(document.getElementById('note')).color",
  537. "rgb(17, 17, 17)",
  538. );
  539. // 尾部注释没闭合:补上 */ 再追加,追加的声明不能被吞进注释(源码里也要生效,!3450 SG-01)
  540. // 原来带 !important 的内联声明:改值保留 !important,页面上仍压过样式表里的 !important(!3450 CR-01)
  541. await selectGuestElement(LOCAL_GUEST_PREFIX, "#imp");
  542. await waitForWritable("true", "带 !important 的元素应能写回");
  543. await fillField("[data-design-field=fontSize]", "22");
  544. await waitForSource(
  545. (source) => source.includes('<p id="imp" style="font-size: 22px !important">'),
  546. "改带 !important 的声明,写回应保留 !important",
  547. );
  548. await waitForGuest("getComputedStyle(document.getElementById('imp')).fontSize", "22px");
  549. // 简写带 !important(background: red !important)时改填充:新值也带 !important 并写在后面,源码渲染与预览一致(!3450 SG-01)
  550. await selectGuestElement(LOCAL_GUEST_PREFIX, "#bgimp");
  551. await waitForWritable("true", "简写带 !important 的元素应能写回");
  552. await fillField("[data-design-field=background]", "0000FF");
  553. await waitForSource(
  554. (source) =>
  555. source.includes(
  556. '<button id="bgimp" style="background: red !important; background-color: #0000FF !important">',
  557. ),
  558. "改填充时简写带 !important,新值应带 !important 写在后面",
  559. );
  560. await waitForGuest(
  561. "getComputedStyle(document.getElementById('bgimp')).backgroundColor",
  562. "rgb(0, 0, 255)",
  563. );
  564. const beforeTodo = await readFile(localFile, "utf-8");
  565. await selectGuestElement(LOCAL_GUEST_PREFIX, "#todo");
  566. await waitForWritable("true", "带未闭合注释 style 的元素应能写回");
  567. await fillField("[data-design-field=fontSize]", "21");
  568. await waitForSource(
  569. (source) => source.includes('<p id="todo" style="color: #222; /* todo */ font-size: 21px">'),
  570. "未闭合注释应补上结尾,追加的字号写在注释外面",
  571. );
  572. await waitForGuest("getComputedStyle(document.getElementById('todo')).fontSize", "21px");
  573. await waitForGuest(
  574. "getComputedStyle(document.getElementById('todo')).color",
  575. "rgb(34, 34, 34)",
  576. );
  577. // 自己写的改动不触发自动刷新
  578. await browser.pause(1_500);
  579. if ((await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eMark")) !== 1) {
  580. throw new Error("写回源文件后页面不应自动刷新");
  581. }
  582. // 外部把文件改回更早的一次自写版本:已不是本 tab 待确认的写入,照常刷新,页面跟源码走(!3450 CR-01)
  583. await writeFile(localFile, beforeTodo, "utf-8");
  584. await browser.waitUntil(
  585. async () => (await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eMark")) !== 1,
  586. { timeout: 15_000, timeoutMsg: "外部改回更早的自写版本后页面应自动刷新" },
  587. );
  588. await waitForGuest("getComputedStyle(document.getElementById('todo')).fontSize", "16px");
  589. // 外部写入同尺寸的内容、mtime 又被改回原值:只看 mtime + size 会当成没变;主 HTML 带内容哈希,照常刷新(!3450 CR-02)
  590. // 先把 mtime 定到整秒(这次 touch 本身会刷新一次),等页面重新加载完再做同尺寸改动并把 mtime 改回同一个整秒
  591. const fixedSeconds = Math.floor(Date.now() / 1000) - 60;
  592. await utimes(localFile, fixedSeconds, fixedSeconds);
  593. await browser.pause(2_000);
  594. await waitForGuest("document.getElementById('todo').textContent", "E2E_TODO");
  595. await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eMark = 2");
  596. const beforeSameSize = await readFile(localFile, "utf-8");
  597. await writeFile(localFile, beforeSameSize.replace("E2E_TODO", "E2E_TODX"), "utf-8");
  598. await utimes(localFile, fixedSeconds, fixedSeconds);
  599. if ((await stat(localFile)).mtimeMs !== fixedSeconds * 1000) {
  600. throw new Error("没能把 mtime 改回原值,这一步验不了同尺寸改动");
  601. }
  602. await browser.waitUntil(
  603. async () => (await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eMark")) !== 2,
  604. { timeout: 15_000, timeoutMsg: "同尺寸、mtime 不变的外部改动后页面应自动刷新" },
  605. );
  606. await waitForGuest("document.getElementById('todo').textContent", "E2E_TODX");
  607. // 脚本插入的元素:源码里对不上,面板只读;插入后它后面的兄弟也对不上(不能按序号写到别的元素上)
  608. await guestEval(
  609. LOCAL_GUEST_PREFIX,
  610. "(() => { const d = document.createElement('div'); d.id = 'generated'; d.textContent = 'E2E_GENERATED'; document.getElementById('s1').prepend(d); return true; })()",
  611. );
  612. await selectGuestElement(LOCAL_GUEST_PREFIX, "#generated");
  613. await waitForWritable("false", "脚本生成的元素不应能写回");
  614. if (!(await $("[data-design-field=fontSize]").getAttribute("disabled"))) {
  615. throw new Error("写不回的元素,数值框应只读");
  616. }
  617. await selectGuestElement(LOCAL_GUEST_PREFIX, "#title");
  618. await waitForWritable("false", "兄弟节点被脚本改过后不应按序号写回");
  619. });
  620. it("写回的边界:非 UTF-8 文件只读且字节不变;带内联子元素的文字不能双击改;写回失败时页面撤回到源码的样子", async function () {
  621. this.timeout(180_000);
  622. await prepareV4ConversationE2E();
  623. await enableDesignPlugin();
  624. await openFreshBrowserTab();
  625. // GBK 文件(!3450 CR-01):严格按 UTF-8 解码失败,面板只读,文件一个字节都不动
  626. const gbkFile = join(localDir, "gbk.html");
  627. const gbkBytes = Buffer.concat([
  628. Buffer.from(
  629. '<!doctype html><html data-zcode-design><head><meta charset="gbk"><title>E2E gbk</title></head><body><h1 id="gbk">',
  630. ),
  631. Buffer.from([0xd6, 0xd0, 0xce, 0xc4]), // 「中文」的 GBK 编码
  632. Buffer.from("</h1></body></html>"),
  633. ]);
  634. await writeFile(gbkFile, gbkBytes);
  635. await navigateBrowser(pathToFileURL(gbkFile).href, "E2E gbk", LOCAL_GUEST_PREFIX);
  636. await selectGuestElement(LOCAL_GUEST_PREFIX, "#gbk");
  637. await waitForWritable("false", "非 UTF-8 文件不应能写回");
  638. if (!(await $("[data-design-field=fontSize]").getAttribute("disabled"))) {
  639. throw new Error("非 UTF-8 文件的数值框应只读");
  640. }
  641. if (!(await readFile(gbkFile)).equals(gbkBytes)) throw new Error("非 UTF-8 文件不应被改动");
  642. // 带 <strong> 的段落(!3450 SG-01):样式能写回,但面板不出文字框;只含文字的段落在面板里改字并写回
  643. const richFile = join(localDir, "rich.html");
  644. await writeFile(
  645. richFile,
  646. '<!doctype html><html data-zcode-design><head><title>E2E rich</title></head><body><p id="rich">E2E <strong>RICH</strong></p><p id="plaintext">E2E_PLAIN_TEXT</p></body></html>',
  647. "utf-8",
  648. );
  649. await navigateBrowser(pathToFileURL(richFile).href, "E2E rich", LOCAL_GUEST_PREFIX);
  650. await selectGuestElement(LOCAL_GUEST_PREFIX, "#rich");
  651. await waitForWritable("true", "带内联子元素的段落样式仍能写回");
  652. await browser.pause(500);
  653. if (await $("[data-design-field=text]").isExisting()) {
  654. throw new Error("源码里不是只含文字的元素,面板不应出文字框");
  655. }
  656. await selectGuestElement(LOCAL_GUEST_PREFIX, "#plaintext");
  657. await waitForWritable("true", "只含文字的段落应能写回");
  658. await fillField("[data-design-field=text]", "E2E_PANEL_TEXT");
  659. await browser.waitUntil(
  660. async () =>
  661. (await readFile(richFile, "utf-8")).includes('<p id="plaintext">E2E_PANEL_TEXT</p>'),
  662. { timeout: 10_000, timeoutMsg: "面板改字应写回源码" },
  663. );
  664. // 页面伪造设计运行时消息(!3450 CR-01):页面这边没有能引起写回的事件,文件不变
  665. const beforeForge = await readFile(richFile, "utf-8");
  666. await guestEval(
  667. LOCAL_GUEST_PREFIX,
  668. `(() => { for (const events of [[{ type: "edit-commit", property: "text", value: "E2E_FORGED" }], [{ type: "history", redo: false }]]) window.postMessage({ __zcodeDesign: 1, events }, "*"); return true; })()`,
  669. );
  670. await browser.pause(2_000);
  671. if ((await readFile(richFile, "utf-8")) !== beforeForge) {
  672. throw new Error("页面伪造的消息不应改动源文件");
  673. }
  674. // 写回失败(文件只读,写入报错,!3450 SG-02):页面上的预览撤回到源码的样子,文件不变
  675. await writeFile(localFile, FIXTURE_HTML, "utf-8");
  676. await navigateBrowser(pathToFileURL(localFile).href, "E2E design mode", LOCAL_GUEST_PREFIX);
  677. await selectGuestElement(LOCAL_GUEST_PREFIX, "#title");
  678. await waitForWritable("true", "标题应能写回");
  679. await chmod(localFile, 0o444);
  680. try {
  681. await fillField("[data-design-field=fontSize]", "30");
  682. await waitForGuest("document.getElementById('title').getAttribute('style') ?? ''", "");
  683. await waitForGuest("getComputedStyle(document.getElementById('title')).fontSize", "40px");
  684. if ((await readFile(localFile, "utf-8")) !== FIXTURE_HTML) {
  685. throw new Error("写入失败时源文件不应变化");
  686. }
  687. } finally {
  688. await chmod(localFile, 0o644);
  689. }
  690. });
  691. it("自写之后一起改了 CSS 照常刷新;带 text-transform 的元素改字按源码大小写写回", async function () {
  692. this.timeout(180_000);
  693. await prepareV4ConversationE2E();
  694. await enableDesignPlugin();
  695. await openFreshBrowserTab();
  696. // !3450 CR-01:先用面板写回一次主 HTML,再在同一刻改页面引用的 CSS 和同目录另一个文件(合并成一次变化事件)
  697. const styledFile = join(localDir, "styled.html");
  698. const cssFile = join(localDir, "styled.css");
  699. await writeFile(cssFile, "#box { color: rgb(0, 0, 255); }", "utf-8");
  700. await writeFile(
  701. styledFile,
  702. '<!doctype html><html data-zcode-design><head><title>E2E styled</title><link rel="stylesheet" href="styled.css"></head><body><h1 id="box">E2E_BOX</h1><button id="cta" style="text-transform: uppercase">Submit order</button></body></html>',
  703. "utf-8",
  704. );
  705. await navigateBrowser(pathToFileURL(styledFile).href, "E2E styled", LOCAL_GUEST_PREFIX);
  706. await selectGuestElement(LOCAL_GUEST_PREFIX, "#box");
  707. await waitForWritable("true", "标题应能写回");
  708. await fillField("[data-design-field=fontSize]", "30");
  709. await waitForGuest("getComputedStyle(document.getElementById('box')).fontSize", "30px");
  710. await browser.pause(1_000);
  711. await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eStyledMark = 1");
  712. await Promise.all([
  713. writeFile(cssFile, "#box { color: rgb(255, 0, 0); }", "utf-8"),
  714. writeFile(join(localDir, "styled-other.txt"), "E2E_OTHER", "utf-8"),
  715. ]);
  716. await waitForGuest("getComputedStyle(document.getElementById('box')).color", "rgb(255, 0, 0)");
  717. if ((await guestEval(LOCAL_GUEST_PREFIX, "window.__e2eStyledMark")) === 1) {
  718. throw new Error("自写之后外部改了 CSS,页面应自动刷新");
  719. }
  720. // !3450 SG-01:按钮带 text-transform: uppercase,在面板里改字,源码按原来的大小写写回
  721. await selectGuestElement(LOCAL_GUEST_PREFIX, "#cta");
  722. await waitForWritable("true", "按钮应能写回");
  723. await fillField("[data-design-field=text]", "Submit orders");
  724. await browser.waitUntil(
  725. async () => (await readFile(styledFile, "utf-8")).includes(">Submit orders</button>"),
  726. { timeout: 10_000, timeoutMsg: "面板改字应按输入的大小写写回(不是 SUBMIT ORDERS)" },
  727. );
  728. });
  729. it("输入框不收元素引用时,每轮点选只提示一次:写回重读选中不再弹,退出点选后再选会再提示", async function () {
  730. this.timeout(180_000);
  731. await prepareV4ConversationE2E();
  732. await enableDesignPlugin();
  733. await openFreshBrowserTab();
  734. const noticeFile = join(localDir, "notice.html");
  735. await writeFile(
  736. noticeFile,
  737. '<!doctype html><html data-zcode-design><head><title>E2E notice</title></head><body><h1 id="a" style="font-size: 30px">E2E_A</h1><h2 id="b">E2E_B</h2></body></html>',
  738. "utf-8",
  739. );
  740. await navigateBrowser(pathToFileURL(noticeFile).href, "E2E notice", LOCAL_GUEST_PREFIX);
  741. // !3548 第五轮 CR-01:「加引用」一律按输入框不收处理;同时数提示弹了几次
  742. await browser.execute(() => {
  743. const w = window as unknown as {
  744. __e2eNotices: number;
  745. __e2eDispatch: typeof window.dispatchEvent;
  746. };
  747. w.__e2eNotices = 0;
  748. w.__e2eDispatch = window.dispatchEvent.bind(window);
  749. // 「加引用」事件不派发、按没人收下返回(dispatchEvent 未被 preventDefault 时返回 true)
  750. window.dispatchEvent = (event: Event) =>
  751. event.type === "zcode:web-element-context-add-to-chat" ? true : w.__e2eDispatch(event);
  752. new MutationObserver((records) => {
  753. for (const record of records) {
  754. for (const node of record.addedNodes) {
  755. const text = node.textContent ?? "";
  756. if (/当前没有可接收的输入框|No composer can receive/.test(text)) w.__e2eNotices += 1;
  757. }
  758. }
  759. }).observe(document.body, { childList: true, subtree: true });
  760. });
  761. const readNotices = async () =>
  762. (await browser.execute(
  763. () => (window as unknown as { __e2eNotices: number }).__e2eNotices,
  764. )) as number;
  765. await selectGuestElement(LOCAL_GUEST_PREFIX, "#a");
  766. await browser.waitUntil(async () => (await readNotices()) >= 1, {
  767. timeout: 10_000,
  768. timeoutMsg: "输入框不收引用时应提示一次",
  769. });
  770. await waitForWritable("true", "标题应能写回");
  771. await fillField("[data-design-field=fontSize]", "31");
  772. await waitForGuest("getComputedStyle(document.getElementById('a')).fontSize", "31px");
  773. await fillField("[data-design-field=fontSize]", "32");
  774. await waitForGuest("getComputedStyle(document.getElementById('a')).fontSize", "32px");
  775. await browser.pause(1_500);
  776. if ((await readNotices()) !== 1) {
  777. throw new Error(`同一轮点选里写回后不应再提示,实际弹了 ${await readNotices()} 次`);
  778. }
  779. // 退出点选再进来选:新一轮,再提示一次
  780. await clickTestIdByDom(TID_BROWSER_ELEMENT_PICKER_BUTTON);
  781. await selectGuestElement(LOCAL_GUEST_PREFIX, "#b");
  782. await browser.waitUntil(async () => (await readNotices()) === 2, {
  783. timeout: 10_000,
  784. timeoutMsg: "退出点选后重新选中应再提示一次",
  785. });
  786. // 只拒一部分(#b):#a 进了输入框、#b 被拒时提示一次,之后写回重读选中仍不再弹(一次性提示的 guard)。
  787. // 注:从界面点选每次对账只新增一个元素,同一次对账「有收有拒」走不到,accepted && !rejected 那条分支这里测不到。
  788. await browser.execute(() => {
  789. const w = window as unknown as { __e2eDispatch: typeof window.dispatchEvent };
  790. window.dispatchEvent = (event: Event) =>
  791. event.type === "zcode:web-element-context-add-to-chat" &&
  792. JSON.stringify((event as CustomEvent).detail ?? {}).includes("E2E_B")
  793. ? true
  794. : w.__e2eDispatch(event);
  795. });
  796. await clickTestIdByDom(TID_BROWSER_ELEMENT_PICKER_BUTTON);
  797. await selectGuestElement(LOCAL_GUEST_PREFIX, "#a");
  798. await selectGuestElement(LOCAL_GUEST_PREFIX, "#b", { shift: true, selectedCount: "2" });
  799. await browser.waitUntil(async () => (await readNotices()) === 3, {
  800. timeout: 10_000,
  801. timeoutMsg: "部分不收时应提示一次",
  802. });
  803. await fillField("[data-design-field=fontSize]", "33");
  804. await waitForGuest("getComputedStyle(document.getElementById('b')).fontSize", "33px");
  805. await fillField("[data-design-field=fontSize]", "34");
  806. await waitForGuest("getComputedStyle(document.getElementById('b')).fontSize", "34px");
  807. await browser.pause(1_500);
  808. if ((await readNotices()) !== 3) {
  809. throw new Error(`部分收下时写回后不应再提示,实际累计 ${await readNotices()} 次`);
  810. }
  811. await browser.execute(() => {
  812. const w = window as unknown as { __e2eDispatch: typeof window.dispatchEvent };
  813. window.dispatchEvent = w.__e2eDispatch;
  814. });
  815. });
  816. it("再点一次「选择元素」退出点选:页面点击不再被拦截、引用留在输入框;普通网页也是同一套点选,调整面板只读", async function () {
  817. this.timeout(180_000);
  818. await prepareV4ConversationE2E();
  819. await enableDesignPlugin();
  820. await openFreshBrowserTab();
  821. await navigate(fixtureUrl, "E2E design mode");
  822. await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).waitForDisplayed({ timeout: 15_000 });
  823. // 在输入框正文里删掉元素 token:页面上同步取消选中
  824. await selectGuestElement(fixtureOrigin, "#title");
  825. await waitForElementTokens(1, "点选后没有元素引用");
  826. await deleteLastElementToken();
  827. await browser.waitUntil(async () => (await readInspectorSelectedCount()) === "0", {
  828. timeout: 5_000,
  829. timeoutMsg: "在输入框删掉引用后页面上应取消选中",
  830. });
  831. await selectGuestElement(fixtureOrigin, "#cta");
  832. await waitForElementTokens(1, "点选后没有元素引用");
  833. await clickTestIdByDom(TID_BROWSER_ELEMENT_PICKER_BUTTON);
  834. await browser.waitUntil(
  835. async () => (await guestEval(fixtureOrigin, "document.documentElement.style.cursor")) === "",
  836. { timeout: 5_000, timeoutMsg: "再点「选择元素」后页面仍停在选择状态" },
  837. );
  838. await browser.waitUntil(async () => (await readInspectorSelectedCount()) === "0", {
  839. timeout: 5_000,
  840. timeoutMsg: "退出点选后应取消选中",
  841. });
  842. await waitForElementTokens(1, "退出点选后输入框里的引用应留着");
  843. await guestEval(
  844. fixtureOrigin,
  845. "window.__e2eClicks = 0; document.getElementById('cta').addEventListener('click', (e) => { if (!e.defaultPrevented) window.__e2eClicks += 1; }); true",
  846. );
  847. await clickGuestElement(fixtureOrigin, "#cta");
  848. await browser.waitUntil(
  849. async () => (await guestEval(fixtureOrigin, "window.__e2eClicks")) === 1,
  850. {
  851. timeout: 5_000,
  852. timeoutMsg: "退出点选后页面按钮的点击被拦截了",
  853. },
  854. );
  855. // 普通网页:不出设计工具行;「选择元素」和设计稿是同一套点选(11-06 统一):
  856. // 元素进输入框正文成 token、不出原来的元素标签,调整面板只读并说明交给 Agent
  857. await navigate(`${fixtureOrigin}/plain`, "E2E plain page");
  858. await browser.pause(1_000);
  859. const tokensBefore = await countElementTokens();
  860. await selectGuestElement(fixtureOrigin, "#plain", { plainPage: true });
  861. await waitForElementTokens(tokensBefore + 1, "普通网页点选后元素应进输入框成 token");
  862. if ((await readDataCount(TID_WEB_ELEMENT_CONTEXT_CHIP)) !== null) {
  863. throw new Error("普通网页点选后不应再出原来的元素标签");
  864. }
  865. if (await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).isExisting()) {
  866. throw new Error("普通网页不应出现设计工具行");
  867. }
  868. // 普通网页点选只为加进聊天:不进完整视图、不弹调整面板挡页面(11-11 用户反馈)
  869. await browser.pause(1_000);
  870. await waitForFullView(false, "普通网页点选后不应进完整视图");
  871. if (await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).isExisting()) {
  872. throw new Error("普通网页点选后不应打开调整面板");
  873. }
  874. // 点选开着换页:退出点选、面板收起,新页面不再拦截点击(!3548 CR-01)
  875. await navigate(fixtureUrl, "E2E design mode");
  876. await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForExist({
  877. reverse: true,
  878. timeout: 10_000,
  879. timeoutMsg: "换页后调整面板应收起",
  880. });
  881. await browser.waitUntil(
  882. async () =>
  883. (await $(`[data-testid="${TID_BROWSER_ELEMENT_PICKER_BUTTON}"]`).getAttribute(
  884. "aria-pressed",
  885. )) === "false",
  886. { timeout: 5_000, timeoutMsg: "换页后应退出点选" },
  887. );
  888. // 设计稿 A 选中后换到同样结构的设计稿 B 再刷新:不能把 A 的选中按选择器推回 B(!3548 第二轮 CR-01)
  889. await selectGuestElement(fixtureOrigin, "#cta");
  890. await navigate(`${fixtureOrigin}/design-b`, "E2E design mode");
  891. await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForExist({
  892. reverse: true,
  893. timeout: 10_000,
  894. timeoutMsg: "换到设计稿 B 后调整面板应收起",
  895. });
  896. await clickTestIdByDom(TID_BROWSER_REFRESH_BUTTON);
  897. await browser.pause(2_000);
  898. // 重新进点选、手动打开调整面板看宿主记着的选中:只能是 0 个
  899. await clickTestIdByDom(TID_BROWSER_ELEMENT_PICKER_BUTTON);
  900. await clickTestIdByDom(TID_BROWSER_DESIGN_PANEL_BUTTON);
  901. await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForExist({
  902. timeout: 10_000,
  903. timeoutMsg: "点工具行的「调整面板」后面板没有打开",
  904. });
  905. if ((await readInspectorSelectedCount()) !== "0") {
  906. throw new Error("刷新设计稿 B 后宿主还留着设计稿 A 的选中");
  907. }
  908. // 单页应用换路由(pushState)不重新注入:同样要退出点选、收起面板(!3548 第三轮)
  909. await selectGuestElement(fixtureOrigin, "#cta");
  910. await guestEval(fixtureOrigin, "history.pushState({}, '', '/design-c'); true");
  911. await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForExist({
  912. reverse: true,
  913. timeout: 10_000,
  914. timeoutMsg: "单页换路由后调整面板应收起",
  915. });
  916. await browser.waitUntil(
  917. async () =>
  918. (await $(`[data-testid="${TID_BROWSER_ELEMENT_PICKER_BUTTON}"]`).getAttribute(
  919. "aria-pressed",
  920. )) === "false",
  921. { timeout: 5_000, timeoutMsg: "单页换路由后应退出点选" },
  922. );
  923. // 前进 / 后退(popstate)同样退出:后退回 /design-b
  924. await selectGuestElement(fixtureOrigin, "#cta");
  925. await guestEval(fixtureOrigin, "history.back(); true");
  926. await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForExist({
  927. reverse: true,
  928. timeout: 10_000,
  929. timeoutMsg: "后退后调整面板应收起",
  930. });
  931. await browser.waitUntil(
  932. async () =>
  933. (await $(`[data-testid="${TID_BROWSER_ELEMENT_PICKER_BUTTON}"]`).getAttribute(
  934. "aria-pressed",
  935. )) === "false",
  936. { timeout: 5_000, timeoutMsg: "后退后应退出点选" },
  937. );
  938. });
  939. });
  940. const navigate = (url: string, title: string) => navigateBrowser(url, title, fixtureOrigin);
  941. async function waitForWritable(expected: "true" | "false", timeoutMsg: string): Promise<void> {
  942. await browser.waitUntil(
  943. async () =>
  944. (await $(`[data-testid="${TID_BROWSER_DESIGN_SOURCE_STATUS}"]`).getAttribute(
  945. "data-writable",
  946. )) === expected,
  947. { timeout: 10_000, timeoutMsg },
  948. );
  949. }
  950. /** 面板字段里输入值后回车提交(焦点留在字段上) */
  951. async function fillField(selector: string, value: string): Promise<void> {
  952. const field = await $(selector);
  953. await field.waitForEnabled({ timeout: 10_000, timeoutMsg: `${selector} 不可编辑` });
  954. // 刚用 Esc 关掉的取色弹层收起时会把焦点还给它的触发按钮:等弹层真正卸掉再聚焦,免得敲到一半焦点被拿走
  955. await browser.waitUntil(
  956. async () =>
  957. (await browser.execute(
  958. () => document.querySelector("[data-radix-popper-content-wrapper]") === null,
  959. )) as boolean,
  960. { timeout: 5_000, timeoutMsg: "取色弹层没有收起" },
  961. );
  962. // 完整视图里浮动输入框可能盖住面板下沿,按 DOM 聚焦并全选,不靠坐标点击
  963. // 焦点可能刚被页面(webview)或收起的弹层拿走:聚焦后停一下,焦点还在这个字段上再敲字
  964. await browser.waitUntil(
  965. async () => {
  966. await browser.execute((target) => {
  967. const input = document.querySelector<HTMLInputElement>(target);
  968. input?.scrollIntoView({ block: "center" });
  969. input?.focus();
  970. input?.select();
  971. }, selector);
  972. await browser.pause(150);
  973. return (await browser.execute(
  974. (target) => document.activeElement === document.querySelector(target),
  975. selector,
  976. )) as boolean;
  977. },
  978. { timeout: 5_000, timeoutMsg: `${selector} 拿不到焦点` },
  979. );
  980. await browser.keys(value.split(""));
  981. await browser.keys("Enter");
  982. }
  983. async function waitForFullView(expected: boolean, timeoutMsg: string): Promise<void> {
  984. await browser.waitUntil(
  985. async () => {
  986. const mode = await $(`[data-testid="${TID_SIDE_PANE_FULL_VIEW_HOST}"]`).getAttribute(
  987. "data-side-pane-full-view-host",
  988. );
  989. return (mode !== null && mode !== "normal") === expected;
  990. },
  991. { timeout: 10_000, timeoutMsg },
  992. );
  993. }
  994. async function waitForFieldValue(selector: string, value: string): Promise<void> {
  995. await browser.waitUntil(async () => (await $(selector).getValue()) === value, {
  996. timeout: 10_000,
  997. timeoutMsg: `${selector} 应显示 ${value}`,
  998. });
  999. }
  1000. async function waitForSource(
  1001. predicate: (source: string) => boolean,
  1002. timeoutMsg: string,
  1003. ): Promise<void> {
  1004. let last = "";
  1005. try {
  1006. await browser.waitUntil(
  1007. async () => {
  1008. last = await readFile(localFile, "utf-8");
  1009. return predicate(last);
  1010. },
  1011. { timeout: 10_000 },
  1012. );
  1013. } catch {
  1014. throw new Error(`${timeoutMsg};当前源文件:\n${last}`);
  1015. }
  1016. }
  1017. async function waitForGuest(expression: string, expected: string): Promise<void> {
  1018. await browser.waitUntil(
  1019. async () => (await guestEval(LOCAL_GUEST_PREFIX, expression)) === expected,
  1020. { timeout: 10_000, timeoutMsg: `页面上 ${expression} 应为 ${expected}` },
  1021. );
  1022. }