interaction-main.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import { app, protocol } from "electron";
  2. import assert from "node:assert/strict";
  3. import { readFile, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { PLUGIN_SANDBOX_PRIVILEGED_SCHEME } from "../../src/main/pluginSandbox/index.js";
  6. import { managedEnvironment } from "./managed-environment.js";
  7. import { clickHostPoint, checkPagePointerInput } from "./pointer-input.js";
  8. const [root, profile, node, cli] = process.argv.slice(2) as [string, string, string, string];
  9. app.setPath("userData", profile);
  10. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  11. app.on("window-all-closed", () => {});
  12. app
  13. .whenReady()
  14. .then(async () => {
  15. const htmlPath = join(root, "widget.html");
  16. const goodHtml = await readFile(htmlPath, "utf8");
  17. const env = await managedEnvironment(root, node, cli);
  18. try {
  19. // 真实等待握手时限;不伪造 controller 的错误态或直接卸载 webview。
  20. await writeFile(
  21. htmlPath,
  22. '<!doctype html><script>throw new Error("fixture startup failure")</script>',
  23. );
  24. const scope = await env.agent.session(join(root, "interaction-workspace"), "managed");
  25. const creation = env
  26. .createWindow(scope, "background-interaction")
  27. .then(() => "unexpected success", String);
  28. await env.events.wait((event) => event.type === "phase" && event.phase === "mounted");
  29. const win = env.windows[0]!;
  30. const ui = (code: string) => win.webContents.executeJavaScript(code);
  31. await ui("window.setAnchors(false, true)");
  32. assert.match(await creation, /handshake timed out/);
  33. await ui(`new Promise(resolve => {
  34. if (!document.querySelector('webview')) return resolve();
  35. const observer = new MutationObserver(() => {
  36. if (!document.querySelector('webview')) { observer.disconnect(); resolve(); }
  37. });
  38. observer.observe(document.body, {subtree: true, childList: true});
  39. })`);
  40. const point = await ui(`(() => {
  41. const button = document.querySelector('[data-testid=plugin-ui-retry]');
  42. const r = button.getBoundingClientRect();
  43. const x = Math.round(r.x + r.width / 2), y = Math.round(r.y + r.height / 2);
  44. window.retryClickCount = 0;
  45. button.addEventListener('click', () => window.retryClickCount++);
  46. return {x, y, hit: document.elementFromPoint(x, y)?.outerHTML};
  47. })()`);
  48. await writeFile(join(root, "retry-hit-test.json"), JSON.stringify(point, null, 2));
  49. await writeFile(htmlPath, goodHtml);
  50. const offset = env.events.history.length;
  51. await clickHostPoint(win, { x: point.x, y: point.y });
  52. assert.equal(await ui("window.retryClickCount"), 1, JSON.stringify(point));
  53. await env.events.wait((event) => event.type === "phase" && event.phase === "running", offset);
  54. await env.evalPage(win, "window.fixtureReady");
  55. assert.equal((await ui("window.managedState()")).views, 1);
  56. assert.equal(env.events.history.filter((event) => event.type === "registered").length, 2);
  57. const guest = env.guests.get(win.webContents.id)!;
  58. await checkPagePointerInput(win, guest);
  59. await ui("window.setAnchors(true, false)");
  60. await checkPagePointerInput(win, guest);
  61. assert.equal(env.guests.get(win.webContents.id)!.id, guest.id);
  62. await ui("window.setAnchors(false, true)");
  63. const stateBeforeHide = await env.evalPage(
  64. win,
  65. `({
  66. counter: document.querySelector('#counter').textContent,
  67. input: document.querySelector('#input').value
  68. })`,
  69. );
  70. const registrations = env.events.history.filter(
  71. (event) => event.type === "registered",
  72. ).length;
  73. const clickControl = async (selector: string) => {
  74. const point = await ui(`(() => {
  75. const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();
  76. return {x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2)};
  77. })()`);
  78. await clickHostPoint(win, point);
  79. };
  80. // 保留真实 React 卡片与 guest,用宿主鼠标关闭、重开及切换标签,防止只测卸载的假阳性。
  81. for (const theme of ["light", "dark"] as const) {
  82. await ui(`window.setShowcasePresentation(${JSON.stringify(theme)}, 'en', 400)`);
  83. await ui("window.setAnchors(false, true)");
  84. for (const selector of [
  85. "#toggle-sidebar",
  86. "#switch-sidebar-tab",
  87. "#switch-main-page",
  88. "#switch-workspace",
  89. ]) {
  90. await clickControl(selector);
  91. const hidden = await ui(`(() => {
  92. const view = document.querySelector('webview');
  93. const root = view.closest('[data-sandbox-page-root]');
  94. return {
  95. visible: window.managedState().visible,
  96. display: getComputedStyle(root).display,
  97. opacity: getComputedStyle(root).opacity,
  98. inert: root.inert,
  99. width: view.getBoundingClientRect().width,
  100. anchorConnected: document.querySelector('#sidebar-anchor [data-testid="plugin-ui-card"]').isConnected,
  101. hit: document.elementFromPoint(600, 200)?.tagName
  102. };
  103. })()`);
  104. await writeFile(
  105. join(root, `visibility-${theme}-${selector.slice(1)}.json`),
  106. JSON.stringify(hidden, null, 2),
  107. );
  108. await writeFile(
  109. join(root, `visibility-${theme}-${selector.slice(1)}.png`),
  110. (await win.webContents.capturePage()).toPNG(),
  111. );
  112. assert.equal(hidden.visible, false, JSON.stringify(hidden));
  113. assert.equal(hidden.display, "block", JSON.stringify(hidden));
  114. assert.ok(Number(hidden.opacity) <= 0.001, JSON.stringify(hidden));
  115. assert.equal(hidden.inert, true);
  116. assert.ok(hidden.width > 0);
  117. assert.equal(hidden.anchorConnected, true);
  118. assert.notEqual(hidden.hit, "WEBVIEW");
  119. assert.equal(guest.isDestroyed(), false);
  120. // 隐藏不能停帧;用真实后台双帧完成工作,不能只检查 guest 还存在。
  121. assert.equal(
  122. await env.evalPage(
  123. win,
  124. `Promise.race([
  125. new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve('running')))),
  126. new Promise(resolve => setTimeout(() => resolve('stalled'), 5000))
  127. ])`,
  128. ),
  129. "running",
  130. );
  131. await clickControl(selector);
  132. assert.equal((await ui("window.managedState()")).visible, true);
  133. assert.equal(env.guests.get(win.webContents.id)!.id, guest.id);
  134. assert.deepEqual(
  135. await env.evalPage(
  136. win,
  137. `({
  138. counter: document.querySelector('#counter').textContent,
  139. input: document.querySelector('#input').value
  140. })`,
  141. ),
  142. stateBeforeHide,
  143. );
  144. }
  145. await writeFile(
  146. join(root, `visibility-${theme}-restored.png`),
  147. (await win.webContents.capturePage()).toPNG(),
  148. );
  149. }
  150. assert.equal(
  151. env.events.history.filter((event) => event.type === "registered").length,
  152. registrations,
  153. );
  154. await checkPagePointerInput(win, guest);
  155. await writeFile(
  156. join(root, "interaction-results.json"),
  157. JSON.stringify(
  158. {
  159. retryClicks: await ui("window.retryClickCount"),
  160. phase: (await ui("window.managedState()")).phase,
  161. views: (await ui("window.managedState()")).views,
  162. sidebarInput: true,
  163. inlineInput: true,
  164. sidebarHideAndRestore: true,
  165. inactiveTabHideAndRestore: true,
  166. mainPageHideAndRestore: true,
  167. workspaceHideAndRestore: true,
  168. hiddenBackgroundFrames: true,
  169. themes: ["light", "dark"],
  170. },
  171. null,
  172. 2,
  173. ),
  174. );
  175. process.stdout.write(
  176. "PASS real handshake timeout accepts mouse retry and restores interactive sidebar/inline guest\n",
  177. );
  178. } finally {
  179. await writeFile(htmlPath, goodHtml);
  180. await env.close();
  181. }
  182. app.exit(0);
  183. })
  184. .catch((error) => {
  185. process.stderr.write(String(error.stack ?? error) + "\n");
  186. app.exit(1);
  187. });