main.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import { checkLoading } from "./preview-corner-checks.js";
  2. import { app, BrowserWindow, ipcMain, protocol, webContents } from "electron";
  3. import {
  4. checkCapture,
  5. checkStaleCapture,
  6. checkInlineLayout,
  7. checkCopyButton,
  8. } from "./presentation-checks.js";
  9. import { checkStandalone } from "./standalone-checks.js";
  10. import { checkExternalLinks } from "./external-links-checks.js";
  11. import { checkFileSummary } from "./file-summary-checks.js";
  12. import {
  13. checkRuntimeWidgets,
  14. checkCalendarAndCarousel,
  15. checkTweakLifecycle,
  16. } from "./runtime-checks.js";
  17. import { checkInheritedOutput, checkRemoteOutput, prepareOutputFiles } from "./output-files.js";
  18. import { installOfflineChecks } from "./offline-checks.js";
  19. import assert from "node:assert/strict";
  20. import { readFile, writeFile } from "node:fs/promises";
  21. import { join } from "node:path";
  22. import {
  23. installPluginSandboxHost,
  24. PLUGIN_SANDBOX_PRIVILEGED_SCHEME,
  25. } from "../../src/main/pluginSandbox/index.js";
  26. import { createGenUiService } from "../../../services/src/gen-ui/node.js";
  27. const root = process.argv[2]!;
  28. app.setPath("userData", join(root, "profile"));
  29. const offline = installOfflineChecks();
  30. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  31. app.on("window-all-closed", () => {});
  32. app.on("web-contents-created", (_, contents) =>
  33. contents.on("console-message", (event) =>
  34. process.stderr.write(`[${contents.getType()}] ${event.message}\n`),
  35. ),
  36. );
  37. const deadline = setTimeout(() => {
  38. process.stderr.write("Gen UI E2E deadline exceeded\n");
  39. app.exit(1);
  40. }, 45_000);
  41. void app
  42. .whenReady()
  43. .then(async () => {
  44. const sandbox = installPluginSandboxHost({
  45. rendererDir: root,
  46. aliasDir: root,
  47. preloadPath: join(root, "guest.cjs"),
  48. logger: { info() {}, warn: (...args) => process.stderr.write(JSON.stringify(args) + "\n") },
  49. });
  50. const win = new BrowserWindow({
  51. show: true,
  52. width: 1100,
  53. height: 820,
  54. webPreferences: {
  55. preload: join(root, "preload.cjs"),
  56. webviewTag: true,
  57. backgroundThrottling: false,
  58. },
  59. });
  60. const pending: string[] = [];
  61. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  62. const result = sandbox.configureGuest({
  63. webPreferences,
  64. params,
  65. ownerWebContentsId: win.webContents.id,
  66. });
  67. if (!result.ok) event.preventDefault();
  68. else pending.push(result.sandboxId);
  69. });
  70. win.webContents.on("did-attach-webview", (_, guest) =>
  71. sandbox.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! }),
  72. );
  73. const output = await prepareOutputFiles(root);
  74. const service = createGenUiService({
  75. stateRoot: join(root, "state"),
  76. outputRoot: output.outputRoot,
  77. registerSandbox: async (input) => sandbox.registerFromHost(input),
  78. });
  79. const remoteService = createGenUiService({
  80. stateRoot: join(root, "remote-state"),
  81. outputRoot: output.remoteOutputRoot,
  82. });
  83. ipcMain.handle("fixture-remote-read", (_, input) => remoteService.readDocument(input));
  84. service.onStateChanged((value) => win.webContents.send("fixture-state", value));
  85. let latestHandle: any;
  86. ipcMain.handle("fixture-service", async (_, method: keyof typeof service, input: never) => {
  87. const result = await (service[method] as (input: unknown) => unknown)(input);
  88. if (method === "prepareSandbox") latestHandle = result;
  89. return result;
  90. });
  91. ipcMain.handle("fixture-config", (_, remote = false) => ({
  92. root: output.workspacePath,
  93. path: (remote ? output.remotePaths : output.paths).fixture,
  94. paths: remote ? output.remotePaths : output.paths,
  95. }));
  96. // No synthetic native gesture: programmatic follow-up must use confirmation.
  97. ipcMain.handle("fixture-gesture", () => false);
  98. await win.loadFile(join(root, "host.html"));
  99. await win.webContents.executeJavaScript("window.harnessReady");
  100. const currentGuest = () =>
  101. webContents.getAllWebContents().find((contents) => contents.getType() === "webview")!;
  102. let guest = currentGuest();
  103. let frame = guest.mainFrame.frames.find((value) => value.url.includes("/instance/"))!;
  104. assert.ok(frame);
  105. const read = (code: string) => frame.executeJavaScript(code);
  106. await read(
  107. "new Promise(resolve => document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', resolve, {once:true}) : resolve())",
  108. );
  109. await read(
  110. "new Promise(resolve => globalThis.lucide ? resolve() : document.getElementById('zcode-visualization-lucide').addEventListener('load', resolve, {once:true}))",
  111. );
  112. assert.equal(await read("typeof window.openai"), "undefined");
  113. assert.equal(await read("typeof window.require"), "undefined");
  114. await read(
  115. "window.zcode.setWidgetState({modelContent:{count:7},privateContent:{secret:'local'}})",
  116. );
  117. for (let i = 0; i < 6; i++)
  118. await win.webContents.executeJavaScript(`window.switchPage(${i % 2 === 0})`);
  119. assert.equal(currentGuest().id, guest.id);
  120. assert.equal(await read("window.starts"), 1);
  121. assert.equal(await read("window.zcode.widgetState.modelContent.count"), 7);
  122. assert.equal(
  123. await read("getComputedStyle(document.querySelector('.card')).borderWidth"),
  124. "1px",
  125. );
  126. win.focus();
  127. await checkRuntimeWidgets(read);
  128. await checkCalendarAndCarousel(read);
  129. await checkTweakLifecycle(read, win);
  130. await offline.check(read);
  131. assert.equal(await read("fetch('https://example.invalid').then(()=>false,()=>true)"), true);
  132. assert.equal(
  133. await read(
  134. `new Promise(resolve=>{const listen=event=>{if(event.data?.id==='denied-tool'){window.removeEventListener('message',listen);resolve(event.data.error?.code)}};window.addEventListener('message',listen);window.parent.postMessage({jsonrpc:'2.0',id:'denied-tool',method:'tools/call',params:{name:'anything',arguments:{}}},'*')})`,
  135. ),
  136. -32601,
  137. );
  138. await checkCapture(win, guest, latestHandle, root);
  139. await win.webContents.executeJavaScript("window.adjust()");
  140. await read("new Promise(requestAnimationFrame)");
  141. assert.equal(await read("document.querySelector('#preview').style.padding"), "35px");
  142. assert.equal((await win.webContents.executeJavaScript("window.inspect()")).messages.length, 0);
  143. await read("window.zcode.sendFollowUpMessage({prompt:'Explain count',title:'Demo'})");
  144. const sent = await win.webContents.executeJavaScript("window.inspect()");
  145. assert.equal(sent.confirmations, 1);
  146. assert.equal(sent.messages.length, 1);
  147. assert.equal(sent.messages[0].source.kind, "genUi");
  148. await win.webContents.executeJavaScript("window.submit()");
  149. assert.equal((await win.webContents.executeJavaScript("window.inspect()")).messages.length, 2);
  150. await win.webContents.executeJavaScript("document.documentElement.classList.add('dark')");
  151. await read("new Promise(requestAnimationFrame)");
  152. assert.equal(await read("document.documentElement.dataset.theme"), "dark");
  153. await writeFile(join(root, "view.png"), (await win.webContents.capturePage()).toPNG());
  154. await win.webContents.executeJavaScript("window.restore()");
  155. guest = currentGuest();
  156. frame = guest.mainFrame.frames.find((value) => value.url.includes("/instance/"))!;
  157. assert.deepEqual(await read("window.initial"), {
  158. modelContent: { count: 7 },
  159. privateContent: { secret: "local" },
  160. });
  161. await win.webContents.executeJavaScript("window.unbind()");
  162. assert.match(
  163. await read(
  164. "window.zcode.sendFollowUpMessage({prompt:'stale'}).then(()=>'',error=>String(error))",
  165. ),
  166. /read-only|disconnected/,
  167. );
  168. const html = await readFile(output.paths.fixture!, "utf8");
  169. await writeFile(output.paths.fixture!, html.replace("Original heading", "Updated heading"));
  170. await writeFile(
  171. output.remotePaths.fixture,
  172. html.replace("Original heading", "Updated heading"),
  173. );
  174. await win.webContents.executeJavaScript("window.restore()");
  175. guest = currentGuest();
  176. frame = guest.mainFrame.frames.find((value) => value.url.includes("/instance/"))!;
  177. assert.equal(await read("document.querySelector('h1').textContent"), "Updated heading");
  178. await checkStaleCapture(win, guest);
  179. await win.loadFile(join(root, "react.html"));
  180. const waitHost = async (predicate: string) =>
  181. win.webContents.executeJavaScript(
  182. `new Promise((resolve,reject)=>{const end=Date.now()+8000;const tick=()=>{if(${predicate})resolve(true);else if(Date.now()>end)reject(new Error(${JSON.stringify(`React fixture condition timed out: ${predicate}`)}));else requestAnimationFrame(tick)};tick()})`,
  183. );
  184. const clickHost = async (text: string) =>
  185. win.webContents.executeJavaScript(
  186. `(() => { const button = [...document.querySelectorAll('button')].find(node => (node.textContent === ${JSON.stringify(text)} || node.getAttribute("aria-label") === ${JSON.stringify(text)})); if(!button) throw new Error('button not found'); button.click(); })()`,
  187. );
  188. await waitHost(`window.showReply`);
  189. const streaming = await win.webContents.executeJavaScript("window.inspectReact()");
  190. assert.equal(streaming.reads, 0);
  191. assert.equal(streaming.preparations, 0);
  192. assert.equal(
  193. await win.webContents.executeJavaScript("document.querySelectorAll('webview').length"),
  194. 0,
  195. );
  196. await checkLoading(win, waitHost);
  197. await waitHost(`document.querySelector('[data-gen-ui-phase="ready"]')`);
  198. assert.equal(
  199. await win.webContents.executeJavaScript("document.body.textContent.includes('::visualize')"),
  200. false,
  201. );
  202. assert.equal(
  203. await win.webContents.executeJavaScript(
  204. "document.body.textContent.includes('Before view') && document.body.textContent.includes('After view')",
  205. ),
  206. true,
  207. );
  208. guest = currentGuest();
  209. frame = guest.mainFrame.frames.find((value) => value.url.includes("/instance/"))!;
  210. const guestId = guest.id;
  211. await checkExternalLinks(win, guest, read);
  212. await checkFileSummary(win, root, waitHost);
  213. await checkInlineLayout(win, read, root);
  214. await checkCopyButton(win);
  215. const inlineHeight = await win.webContents.executeJavaScript(
  216. "document.querySelector('[data-testid=gen-ui-anchor]').style.height",
  217. );
  218. await clickHost("Expand");
  219. await waitHost(`document.querySelector('[role="dialog"]')`);
  220. await checkCopyButton(win, true);
  221. assert.equal(
  222. await win.webContents.executeJavaScript(
  223. "document.querySelector('[data-testid=gen-ui-anchor]').style.height",
  224. ),
  225. inlineHeight,
  226. );
  227. assert.equal(currentGuest().id, guestId);
  228. assert.ok(
  229. await win.webContents.executeJavaScript(
  230. "document.querySelector('[data-sandbox-page-root]:popover-open')",
  231. ),
  232. );
  233. await read(
  234. "window.modalFollow = window.zcode.sendFollowUpMessage({prompt:'Expanded confirmation'}).then(()=>true,()=>false); 'pending'",
  235. );
  236. await waitHost(`document.querySelector('[role="dialog"] textarea')`);
  237. assert.equal(
  238. await win.webContents.executeJavaScript(
  239. "Boolean(document.querySelector('[data-sandbox-page-root]:popover-open'))",
  240. ),
  241. false,
  242. );
  243. await clickHost("Cancel");
  244. await waitHost(`document.querySelector('[data-sandbox-page-root]:popover-open')`);
  245. await clickHost("Collapse");
  246. await waitHost(`!document.querySelector('[role="dialog"]')`);
  247. assert.equal(currentGuest().id, guestId);
  248. await clickHost("Expand");
  249. await waitHost(`document.querySelector('[data-sandbox-page-root]:popover-open')`);
  250. await read("document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}))");
  251. await waitHost(`!document.querySelector('[data-sandbox-page-root]:popover-open')`);
  252. await clickHost("Expand");
  253. await waitHost(`document.querySelector('[data-testid="gen-ui-backdrop"]')`);
  254. await win.webContents.executeJavaScript(
  255. "document.querySelector('[data-testid=gen-ui-backdrop]').dispatchEvent(new PointerEvent('pointerdown',{bubbles:true}))",
  256. );
  257. await waitHost(`!document.querySelector('[data-sandbox-page-root]:popover-open')`);
  258. await clickHost("Adjust design");
  259. await waitHost(`document.querySelector('[data-testid="gen-ui-tweaks"] input[type="range"]')`);
  260. await waitHost(
  261. `(() => { const anchor=document.querySelector('[data-testid="gen-ui-anchor"]'); const view=document.querySelector('webview'); return anchor && view && Math.abs(anchor.getBoundingClientRect().top-view.getBoundingClientRect().top)<1; })()`,
  262. );
  263. await writeFile(join(root, "react-tweaks.png"), (await win.webContents.capturePage()).toPNG());
  264. await win.webContents.executeJavaScript(`(() => {
  265. const range = document.querySelector('[data-testid=gen-ui-tweaks] input[type=range]');
  266. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(range, '21');
  267. range.dispatchEvent(new Event('input', {bubbles:true}));
  268. range.dispatchEvent(new Event('change', {bubbles:true}));
  269. })()`);
  270. const waitPreview = (value: string) =>
  271. read(
  272. `new Promise(resolve=>{const check=()=>{if(document.querySelector('#preview').style.padding===${JSON.stringify(value)}){observer.disconnect();resolve(true)}};const observer=new MutationObserver(check);observer.observe(document.querySelector('#preview'),{attributes:true});check()})`,
  273. );
  274. await waitPreview("21px");
  275. await clickHost("Preview original");
  276. await waitPreview("20px");
  277. await clickHost("Preview original");
  278. await waitPreview("21px");
  279. await clickHost("Adjust design");
  280. await waitHost(`!document.querySelector('[data-testid="gen-ui-tweaks"]')`);
  281. await clickHost("Adjust design");
  282. await waitHost(
  283. `document.querySelector('[data-testid="gen-ui-tweaks"] input[type="range"]')?.value === '21'`,
  284. );
  285. assert.equal(
  286. await win.webContents.executeJavaScript(
  287. "document.querySelectorAll('[data-testid=gen-ui-tweaks] fieldset').length",
  288. ),
  289. 2,
  290. );
  291. await clickHost("Reset");
  292. await waitPreview("20px");
  293. await clickHost("Submit design changes");
  294. await waitHost(`window.inspectReact().messages.length === 1`);
  295. await read(
  296. "window.followResult=window.zcode.sendFollowUpMessage({prompt:'React confirmation'}).then(()=>true); 'pending'",
  297. );
  298. await waitHost(
  299. `document.querySelector('[role="dialog"] textarea')?.value === "React confirmation"`,
  300. );
  301. await clickHost("Send");
  302. assert.equal(await read("window.followResult"), true);
  303. const actual = await win.webContents.executeJavaScript("window.inspectReact()");
  304. assert.equal(actual.reads, 1);
  305. assert.equal(actual.preparations, 1);
  306. assert.equal(actual.messages.length, 2);
  307. assert.equal(actual.ports, 1);
  308. assert.equal(actual.states, 1);
  309. await read(
  310. "window.staleResult=window.zcode.sendFollowUpMessage({prompt:'stale confirmation'}).then(()=>'',error=>String(error)); 'pending'",
  311. );
  312. await waitHost(
  313. `document.querySelector('[role="dialog"] textarea')?.value === "stale confirmation"`,
  314. );
  315. await win.webContents.executeJavaScript("window.disableSession()");
  316. await clickHost("Send");
  317. assert.match(await read("window.staleResult"), /binding changed/);
  318. assert.equal(
  319. (await win.webContents.executeJavaScript("window.inspectReact()")).messages.length,
  320. 2,
  321. );
  322. await writeFile(join(root, "react-view.png"), (await win.webContents.capturePage()).toPNG());
  323. await win.webContents.executeJavaScript("window.showReply('hidden')");
  324. await waitHost(`document.querySelector('[data-sandbox-page-parking] webview')`);
  325. assert.equal(currentGuest().id, guestId);
  326. await win.webContents.executeJavaScript("window.showReply('complete')");
  327. await waitHost(`document.querySelector('[data-gen-ui-phase="ready"]')`);
  328. assert.equal(
  329. await win.webContents.executeJavaScript("document.querySelectorAll('webview').length"),
  330. 1,
  331. );
  332. assert.equal((await win.webContents.executeJavaScript("window.inspectReact()")).reads, 1);
  333. assert.equal(
  334. (await win.webContents.executeJavaScript("window.inspectReact()")).preparations,
  335. 1,
  336. );
  337. guest = currentGuest();
  338. frame = guest.mainFrame.frames.find((value) => value.url.includes("/instance/"))!;
  339. assert.equal(await read("document.querySelector('h1').textContent"), "Updated heading");
  340. await writeFile(
  341. join(root, "react-replayed.png"),
  342. (await win.webContents.capturePage()).toPNG(),
  343. );
  344. assert.equal(currentGuest().id, guestId);
  345. assert.equal(await read("window.starts"), 1);
  346. await win.webContents.executeJavaScript("window.showTask('second-task')");
  347. await waitHost(
  348. `document.querySelector('[data-gen-ui-phase="ready"]') && window.inspectReact().preparations === 2`,
  349. );
  350. await checkInheritedOutput(win);
  351. assert.equal(
  352. webContents.getAllWebContents().filter((contents) => contents.getType() === "webview").length,
  353. 2,
  354. );
  355. await win.webContents.executeJavaScript("window.showTask('fixture')");
  356. await waitHost(`document.querySelector('[data-gen-ui-phase="ready"]')`);
  357. assert.equal(
  358. await win.webContents.executeJavaScript(
  359. "document.querySelector('[data-testid=gen-ui-anchor] webview').getWebContentsId()",
  360. ),
  361. guestId,
  362. );
  363. assert.equal((await win.webContents.executeJavaScript("window.inspectReact()")).reads, 2);
  364. await win.webContents.executeJavaScript(
  365. "document.querySelector('#gen-ui-scroll').scrollTop=800",
  366. );
  367. await win.webContents.executeJavaScript(
  368. "new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))",
  369. );
  370. await win.webContents.executeJavaScript("window.expireOffscreen()");
  371. await waitHost(`!document.querySelector('webview')`);
  372. await win.webContents.executeJavaScript("document.querySelector('#gen-ui-scroll').scrollTop=0");
  373. await waitHost(
  374. `document.querySelector('[data-gen-ui-phase="ready"]') && window.inspectReact().preparations === 3`,
  375. );
  376. assert.notEqual(
  377. await win.webContents.executeJavaScript(
  378. "document.querySelector('webview').getWebContentsId()",
  379. ),
  380. guestId,
  381. );
  382. await win.webContents.executeJavaScript(
  383. "window.showReply('hidden'); window.deleteTask('fixture'); window.deleteTask('second-task')",
  384. );
  385. await waitHost(
  386. `window.inspectReact().ports === 0 && window.inspectReact().states === 0 && !document.querySelector('webview')`,
  387. );
  388. await checkRemoteOutput(win, service, remoteService, output, root, waitHost);
  389. remoteService.dispose();
  390. service.dispose();
  391. win.destroy();
  392. await checkStandalone(root);
  393. offline.assertNoNetwork();
  394. clearTimeout(deadline);
  395. process.stdout.write(
  396. "Gen UI Electron E2E passed: isolation, state, anchors, external links, styles, tooltip, tabs, icons, calendar, carousel, Tweak lifecycle, follow-up, theme, replay, reload, standalone and historical remount\n",
  397. );
  398. app.exit(0);
  399. })
  400. .catch(async (error) => {
  401. process.stderr.write(String(error.stack ?? error));
  402. const win = BrowserWindow.getAllWindows()[0];
  403. if (win) {
  404. await writeFile(join(root, "failure.png"), (await win.webContents.capturePage()).toPNG());
  405. process.stderr.write(
  406. await win.webContents.executeJavaScript(
  407. `JSON.stringify({scrollY, anchors:[...document.querySelectorAll('[data-testid="gen-ui-anchor"]')].map(node=>node.getBoundingClientRect().toJSON()), views:[...document.querySelectorAll('webview')].map(node=>({rect:node.getBoundingClientRect().toJSON(),style:node.getAttribute('style')}))})`,
  408. ),
  409. );
  410. }
  411. app.exit(1);
  412. });