browser-design-mode.test.ts 52 KB

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