presentation-checks.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { BrowserWindow, clipboard, nativeImage, type WebContents } from "electron";
  2. import assert from "node:assert/strict";
  3. import { join } from "node:path";
  4. import { writeFile } from "node:fs/promises";
  5. import type { PluginSandboxHandle } from "@zcode/shared/mcp-apps";
  6. import { checkPreviewCorners } from "./preview-corner-checks.js";
  7. import { checkUnifiedStyles } from "./style-checks.js";
  8. async function readClipboardImage() {
  9. // Electron 44 移除了 readImage;夹具读取真实 PNG,保留非空与裁剪尺寸断言。
  10. const items = await clipboard.read();
  11. const image = items.find((item) => item.types.includes("image/png"));
  12. assert.ok(image, "Clipboard does not contain a PNG image");
  13. const png = await image.getType("image/png");
  14. return nativeImage.createFromBuffer(Buffer.from(await png.arrayBuffer()));
  15. }
  16. export async function checkCopyButton(win: BrowserWindow, preview = false) {
  17. if (preview) await checkPreviewCorners(win);
  18. const selector = `${preview ? '[role="dialog"] ' : ""}[data-testid="gen-ui-actions"] button`;
  19. const buttonState = () =>
  20. win.webContents.executeJavaScript(`(() => {
  21. const button = document.querySelector(${JSON.stringify(selector)});
  22. return {title: button.title, label: button.getAttribute('aria-label'),
  23. icon: button.querySelector('svg').outerHTML, disabled: button.disabled};
  24. })()`);
  25. const initial = await buttonState();
  26. assert.equal(initial.disabled, false);
  27. for (let attempt = 0; attempt < 2; attempt++) {
  28. clipboard.clear();
  29. await win.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  30. const button = document.querySelector(${JSON.stringify(selector)});
  31. button.click();
  32. const end = Date.now() + 5000;
  33. const tick = () => {
  34. if (!button.disabled) resolve(true);
  35. else if (Date.now() > end) reject(new Error('Copy button did not become available'));
  36. else requestAnimationFrame(tick);
  37. };
  38. requestAnimationFrame(tick);
  39. })`);
  40. assert.equal((await readClipboardImage()).isEmpty(), false);
  41. assert.deepEqual(await buttonState(), initial);
  42. }
  43. }
  44. export async function checkCapture(
  45. win: BrowserWindow,
  46. guest: WebContents,
  47. latestHandle: PluginSandboxHandle,
  48. root: string,
  49. ) {
  50. await win.webContents.executeJavaScript("window.copy()");
  51. const copied = await readClipboardImage();
  52. assert.equal(copied.isEmpty(), false);
  53. const fullImage = await guest.capturePage();
  54. const viewport = await win.webContents.executeJavaScript(
  55. "document.querySelector('webview').getBoundingClientRect().toJSON()",
  56. );
  57. const copiedSize = copied.getSize();
  58. assert.equal(
  59. copiedSize.width,
  60. Math.floor(((viewport.width - 5) * fullImage.getSize().width) / viewport.width) -
  61. Math.ceil((5 * fullImage.getSize().width) / viewport.width),
  62. );
  63. const request = {
  64. sandboxId: latestHandle.sandboxId,
  65. initId: latestHandle.initId,
  66. viewportSize: { width: viewport.width, height: viewport.height },
  67. captureRect: { x: 5, y: 5, width: viewport.width - 10, height: viewport.height - 10 },
  68. };
  69. const copyRequest = (value: unknown) =>
  70. `window.zcodePluginSandbox.copyImage(${JSON.stringify(value)})`;
  71. await assert.rejects(
  72. win.webContents.executeJavaScript(copyRequest({ ...request, initId: request.initId + 1 })),
  73. /no longer available/,
  74. );
  75. await assert.rejects(
  76. win.webContents.executeJavaScript(
  77. copyRequest({ ...request, captureRect: { ...request.captureRect, x: -1 } }),
  78. ),
  79. /too_small|greater|minimum/,
  80. );
  81. const otherWindow = new BrowserWindow({
  82. show: false,
  83. webPreferences: { preload: join(root, "preload.cjs") },
  84. });
  85. await otherWindow.loadURL("about:blank");
  86. await assert.rejects(
  87. otherWindow.webContents.executeJavaScript(copyRequest(request)),
  88. /no longer available/,
  89. );
  90. otherWindow.destroy();
  91. }
  92. export async function checkStaleCapture(win: BrowserWindow, guest: WebContents) {
  93. const captureStarted = Promise.withResolvers<void>(),
  94. captureGate = Promise.withResolvers<void>();
  95. const nativeCapture = guest.capturePage.bind(guest);
  96. guest.capturePage = async () => {
  97. const image = await nativeCapture();
  98. captureStarted.resolve();
  99. await captureGate.promise;
  100. return image;
  101. };
  102. // Electron 44 的文本读写也改为异步;先完成哨兵写入,才能证明旧捕获没有覆盖它。
  103. await clipboard.writeText("capture-stale-sentinel");
  104. await win.webContents.executeJavaScript(
  105. "window.copyResult=window.copy().then(()=>'',error=>String(error)); 'pending'",
  106. );
  107. await captureStarted.promise;
  108. await win.webContents.executeJavaScript("window.stop()");
  109. captureGate.resolve();
  110. assert.match(await win.webContents.executeJavaScript("window.copyResult"), /no longer available/);
  111. assert.equal(await clipboard.readText(), "capture-stale-sentinel");
  112. }
  113. export async function checkInlineLayout(
  114. win: BrowserWindow,
  115. read: (code: string) => Promise<any>,
  116. artifacts: string,
  117. ) {
  118. await checkParentWidth(win, read);
  119. assert.equal(
  120. await win.webContents.executeJavaScript(
  121. "getComputedStyle(document.querySelector('[data-testid=gen-ui-card]')).borderWidth",
  122. ),
  123. "0px",
  124. );
  125. assert.equal(
  126. await win.webContents.executeJavaScript(
  127. "getComputedStyle(document.querySelector('[data-testid=gen-ui-card]')).backgroundColor",
  128. ),
  129. "rgba(0, 0, 0, 0)",
  130. );
  131. assert.equal(await read("getComputedStyle(document.body).fontSize"), "14px");
  132. await read(
  133. "document.querySelector('#preview').insertAdjacentHTML('beforeend','<small class=\"text-small text-muted\">Units and source</small>')",
  134. );
  135. assert.equal(await read("getComputedStyle(document.querySelector('small')).fontSize"), "12px");
  136. const scrollErrors = await win.webContents.executeJavaScript(`(async () => {
  137. const scroller=document.querySelector('#gen-ui-scroll'), view=document.querySelector('webview');
  138. const initial=view.getBoundingClientRect().top+scroller.scrollTop;
  139. const errors=[];
  140. for(const offset of [0,80,260,40,480,0]) {
  141. scroller.scrollTop=offset;
  142. errors.push(Math.abs(view.getBoundingClientRect().top+scroller.scrollTop-initial));
  143. await new Promise(requestAnimationFrame);
  144. errors.push(Math.abs(view.getBoundingClientRect().top+scroller.scrollTop-initial));
  145. }
  146. return errors;
  147. })()`);
  148. assert.ok(
  149. scrollErrors.every((error: number) => error < 1),
  150. JSON.stringify(scrollErrors),
  151. );
  152. await win.webContents.executeJavaScript("document.querySelector('#root').style.width='380px'");
  153. await read("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))");
  154. assert.equal(await read("document.documentElement.scrollWidth <= innerWidth"), true);
  155. await win.webContents.executeJavaScript("document.querySelector('#root').style.width=''");
  156. await checkNativeScroll(win);
  157. await checkContentSizing(win, read, artifacts);
  158. await checkUnifiedStyles(win, read);
  159. }
  160. async function checkParentWidth(win: BrowserWindow, read: (code: string) => Promise<any>) {
  161. // 修复回归:736/1024 是生成时的设计参考,不应在已经定宽的会话列中再次截断卡片。
  162. const measurements = await win.webContents.executeJavaScript(`(async () => {
  163. const root=document.querySelector('#root'), result=[];
  164. const view=document.querySelector('webview');
  165. for (const mode of ['normal','wide']) {
  166. window.setInlineMode(mode);
  167. for (const width of [1200,900,390,1200]) {
  168. root.style.width=width+'px';
  169. await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
  170. const card=document.querySelector('[data-testid=gen-ui-card]');
  171. const parent=card.parentElement, style=getComputedStyle(parent);
  172. result.push({mode,width,card:card.getBoundingClientRect().width,
  173. available:parent.clientWidth-parseFloat(style.paddingLeft)-parseFloat(style.paddingRight),
  174. retained:document.querySelector('webview')===view});
  175. }
  176. }
  177. root.style.width='';
  178. return result;
  179. })()`);
  180. for (const measured of measurements) {
  181. assert.ok(Math.abs(measured.card - measured.available) < 1, JSON.stringify(measured));
  182. assert.equal(measured.retained, true);
  183. }
  184. await win.webContents.executeJavaScript("document.querySelector('#root').style.width='390px'");
  185. await read("new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))");
  186. assert.equal(await read("document.documentElement.scrollWidth <= innerWidth"), true);
  187. await win.webContents.executeJavaScript("document.querySelector('#root').style.width=''");
  188. }
  189. async function checkNativeScroll(win: BrowserWindow) {
  190. const point = await win.webContents.executeJavaScript(`(() => {
  191. const style=document.createElement('style');
  192. style.textContent='#gen-ui-scroll::-webkit-scrollbar{width:12px}#gen-ui-scroll::-webkit-scrollbar-thumb{background:#888}';
  193. document.head.append(style);
  194. const scroller=document.querySelector('#gen-ui-scroll'); scroller.scrollTop=0;
  195. const rect=scroller.getBoundingClientRect();
  196. return {x:Math.round(rect.right-6), y:Math.round(rect.top+30)};
  197. })()`);
  198. win.webContents.debugger.attach("1.3");
  199. try {
  200. await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  201. type: "mousePressed",
  202. ...point,
  203. button: "left",
  204. buttons: 1,
  205. clickCount: 1,
  206. });
  207. await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  208. type: "mouseMoved",
  209. x: point.x,
  210. y: point.y + 130,
  211. button: "left",
  212. buttons: 1,
  213. });
  214. await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  215. type: "mouseReleased",
  216. x: point.x,
  217. y: point.y + 130,
  218. button: "left",
  219. buttons: 0,
  220. clickCount: 1,
  221. });
  222. const dragged = await win.webContents.executeJavaScript(`new Promise((resolve,reject)=>{
  223. const end=Date.now()+2000; const tick=()=>{
  224. const scroll=document.querySelector('#gen-ui-scroll').scrollTop;
  225. if(scroll>0) resolve(scroll); else if(Date.now()>end) reject(new Error('Native scrollbar did not move')); else requestAnimationFrame(tick);
  226. }; tick();
  227. })`);
  228. assert.ok(dragged > 0);
  229. assert.ok(
  230. await win.webContents.executeJavaScript(
  231. `Math.abs(document.querySelector('[data-testid=gen-ui-anchor]').getBoundingClientRect().top-document.querySelector('webview').getBoundingClientRect().top)<1`,
  232. ),
  233. );
  234. await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  235. type: "mouseWheel",
  236. ...point,
  237. deltaX: 0,
  238. deltaY: -60,
  239. });
  240. await win.webContents.executeJavaScript(`new Promise((resolve,reject)=>{
  241. const end=Date.now()+2000; const tick=()=>{
  242. const scroll=document.querySelector('#gen-ui-scroll').scrollTop;
  243. if(scroll<${dragged}) resolve(scroll); else if(Date.now()>end) reject(new Error('Native wheel did not move')); else requestAnimationFrame(tick);
  244. }; tick();
  245. })`);
  246. } finally {
  247. win.webContents.debugger.detach();
  248. }
  249. await win.webContents.executeJavaScript(
  250. "document.querySelector('#gen-ui-scroll').scrollTop=0; new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))",
  251. );
  252. }
  253. async function checkContentSizing(
  254. win: BrowserWindow,
  255. read: (code: string) => Promise<any>,
  256. artifacts: string,
  257. ) {
  258. const host = (code: string) => win.webContents.executeJavaScript(code);
  259. await read(`(() => {
  260. const originalNodes = [...document.body.childNodes];
  261. window.sizingOriginal = document.createElement('div');
  262. sizingOriginal.hidden = true;
  263. sizingOriginal.setAttribute('role', 'tooltip');
  264. document.body.append(sizingOriginal);
  265. sizingOriginal.append(...originalNodes);
  266. const root = document.createElement('div'); root.dataset.sizingProbe = '';
  267. root.style.cssText = 'display:flex;flex-direction:column;gap:16px';
  268. root.innerHTML = '<nav><button id="size-short">Controls</button><button id="size-tall">Charts</button></nav><section id="size-panel"></section>';
  269. document.body.append(root);
  270. window.sizePanel = (tall) => {
  271. document.querySelector('#size-panel').innerHTML = tall
  272. ? '<svg style="display:block;width:100%;height:auto" viewBox="0 0 1000 300"><path d="M0 250L500 60L1000 120" stroke="currentColor" fill="none" /></svg><div style="height:360.765625px">Chart footer</div>'
  273. : '<div style="height:180.265625px">Controls</div>';
  274. };
  275. document.querySelector('#size-short').onclick = () => sizePanel(false);
  276. document.querySelector('#size-tall').onclick = () => sizePanel(true);
  277. sizePanel(false);
  278. window.sizingRootMutations = 0;
  279. window.sizingObserver = new MutationObserver(records => sizingRootMutations += records.length);
  280. sizingObserver.observe(document.documentElement, {attributes:true,attributeFilter:['style']});
  281. })()`);
  282. const fitted = async () => {
  283. const target =
  284. await host(`({width:document.querySelector('webview').getBoundingClientRect().width,
  285. theme:document.documentElement.classList.contains('dark')?'dark':'light'})`);
  286. return read(`new Promise((resolve,reject) => {
  287. const end = Date.now()+4000;
  288. const tick = () => {
  289. const root = document.querySelector('[data-sizing-probe]'), css = getComputedStyle(document.body);
  290. const expected = Math.ceil(root.getBoundingClientRect().height + parseFloat(css.paddingTop) + parseFloat(css.paddingBottom));
  291. const measured = {expected, height:innerHeight, width:innerWidth, clientWidth:document.documentElement.clientWidth,
  292. scrollbar:getComputedStyle(document.documentElement).scrollbarWidth, scrollY};
  293. if (Math.abs(expected-innerHeight)<=1 && Math.abs(innerWidth-${target.width})<=1 && document.documentElement.dataset.theme===${JSON.stringify(target.theme)}) resolve(measured);
  294. else if(Date.now()>end) reject(new Error('Content height did not settle: '+JSON.stringify(measured)));
  295. else requestAnimationFrame(tick);
  296. }; requestAnimationFrame(tick);
  297. })`);
  298. };
  299. try {
  300. for (const width of [1100, 390]) {
  301. await host(`document.querySelector('#root').style.width='${width}px'`);
  302. for (const theme of ["light", "dark"]) {
  303. await host(`document.documentElement.classList.toggle('dark',${theme === "dark"})`);
  304. for (const tab of ["tall", "short", "tall", "short"]) {
  305. await read(`document.querySelector('#size-${tab}').click()`);
  306. const size = await fitted();
  307. assert.equal(size.scrollbar, "none", JSON.stringify(size));
  308. assert.equal(size.clientWidth, size.width, JSON.stringify(size));
  309. assert.equal(size.scrollY, 0, JSON.stringify(size));
  310. }
  311. }
  312. }
  313. // 修复回归:测量不得临时写 html 高度,影响原生滚动条布局。
  314. await read("new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))");
  315. await read("window.sizingRootMutations=0; document.querySelector('#size-tall').click()");
  316. await fitted();
  317. assert.equal(await read("window.sizingRootMutations"), 0);
  318. await read(
  319. "document.querySelector('#size-panel').insertAdjacentHTML('beforeend','<div id=size-extra style=height:123.5px>More data</div>')",
  320. );
  321. await fitted();
  322. await read("document.querySelector('#size-extra').remove()");
  323. const beforeTooltip = await fitted();
  324. await read(
  325. "document.body.insertAdjacentHTML('beforeend','<div data-sizing-probe role=tooltip style=\"position:absolute;top:2000px\">Tip</div>')",
  326. );
  327. await read("new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))");
  328. assert.equal((await fitted()).height, beforeTooltip.height);
  329. await read("document.querySelector('[role=tooltip][data-sizing-probe]').remove()");
  330. await host("document.querySelector('#root').style.width='1100px'");
  331. await fitted();
  332. await host("new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))");
  333. await writeFile(
  334. join(artifacts, "inline-charts.png"),
  335. (await win.webContents.capturePage()).toPNG(),
  336. );
  337. const point = await host(`(() => {
  338. document.querySelector('#gen-ui-scroll').scrollTop=0;
  339. const rect=document.querySelector('webview').getBoundingClientRect();
  340. return {x:Math.round(rect.left+80), y:Math.round(rect.top+120)};
  341. })()`);
  342. win.webContents.debugger.attach("1.3");
  343. try {
  344. await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  345. type: "mouseWheel",
  346. ...point,
  347. deltaX: 0,
  348. deltaY: 160,
  349. });
  350. await host(`new Promise((resolve,reject)=>{
  351. const end=Date.now()+2000; const tick=()=>{
  352. if(document.querySelector('#gen-ui-scroll').scrollTop>0) resolve(true);
  353. else if(Date.now()>end) reject(new Error('Wheel over the chart did not scroll the conversation'));
  354. else requestAnimationFrame(tick);
  355. };tick();
  356. })`);
  357. assert.equal(await read("scrollY"), 0);
  358. } finally {
  359. win.webContents.debugger.detach();
  360. await host("document.querySelector('#gen-ui-scroll').scrollTop=0");
  361. }
  362. await read("document.querySelector('#size-panel').style.height='calc(100vh + 10px)'");
  363. const feedback = await read(`(async () => {
  364. const heights=[];
  365. for(let i=0;i<24;i++){await new Promise(requestAnimationFrame); heights.push(innerHeight)}
  366. return heights;
  367. })()`);
  368. assert.equal(new Set(feedback.slice(-8)).size, 1, JSON.stringify(feedback));
  369. assert.ok(feedback.at(-1) < 2000, JSON.stringify(feedback));
  370. await read("document.querySelector('#size-panel').style.height='12000px'");
  371. await host(`new Promise((resolve,reject) => {
  372. const end=Date.now()+4000; const tick=()=>{
  373. const height=document.querySelector('[data-testid="gen-ui-anchor"]').style.height;
  374. if(height==='10000px') resolve(true);
  375. else if(Date.now()>end) reject(new Error('Height limit did not settle: '+height));
  376. else requestAnimationFrame(tick);
  377. };tick();
  378. })`);
  379. assert.equal(await read("scrollTo(0,10000); scrollY>0"), true);
  380. await read(
  381. "scrollTo(0,0); document.querySelector('#size-panel').style.height=''; sizePanel(false)",
  382. );
  383. await fitted();
  384. process.stdout.write(
  385. `Gen UI sizing: wide/narrow, light/dark, tabs, nested changes, tooltip and viewport feedback passed\n`,
  386. );
  387. } finally {
  388. await read(
  389. `sizingObserver.disconnect(); document.body.append(...sizingOriginal.childNodes); sizingOriginal.remove(); document.querySelectorAll('[data-sizing-probe]').forEach(node=>node.remove())`,
  390. );
  391. await host(
  392. "document.querySelector('#root').style.width=''; document.documentElement.classList.remove('dark')",
  393. );
  394. }
  395. }