presentation-checks.ts 18 KB

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