presentation-checks.ts 18 KB

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