managed-checks.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import assert from "node:assert/strict";
  2. import type { BrowserWindow } from "electron";
  3. import type { managedEnvironment } from "./managed-environment.js";
  4. import { checkModel } from "./managed-model-checks.js";
  5. type Environment = Awaited<ReturnType<typeof managedEnvironment>>;
  6. export async function checkManaged(
  7. env: Environment,
  8. win: BrowserWindow,
  9. scope: any,
  10. check: (name: string, run: () => Promise<void>) => Promise<void>,
  11. ) {
  12. const ui = (code: string) => win.webContents.executeJavaScript(code);
  13. const page = (code: string) => env.evalPage(win, code);
  14. const approval = (key: string) => env.agent.approvals.wait((r) => r.params.input?.key === key);
  15. const executed = (key: string) =>
  16. env.agent.events.history.filter((e) => e.type === "executed" && e.key === key).length;
  17. let updates = 0;
  18. async function notification() {
  19. env.agent.notify("managed", "fixture://state");
  20. await page(`window.waitResources(${++updates})`);
  21. }
  22. await check("resource subscriptions deduplicate through SDK, real Agent and MCP", async () => {
  23. await page("Promise.all([window.subscribeFixture(), window.subscribeFixture()])");
  24. assert.equal(
  25. env.agent.events.history.filter((e) => e.type === "resources/subscribe").length,
  26. 1,
  27. );
  28. await notification();
  29. assert.deepEqual(await page("window.resourceEvents"), ["fixture://state"]);
  30. });
  31. await check(
  32. "pending approval survives React inline unmount and keeps real resource feed in sidebar",
  33. async () => {
  34. const guest = env.guests.get(win.webContents.id)!;
  35. const before = await ui("window.managedState()");
  36. await page("window.saveWidget({managed:7})");
  37. const result = page("window.callTool('managed-approval')");
  38. const request = await approval("managed-approval");
  39. for (let n = 0; n < 6; n++) {
  40. await ui(`window.setAnchors(true, ${n % 2 === 0})`);
  41. await notification();
  42. }
  43. await ui("window.setAnchors(false, true)");
  44. await notification();
  45. assert.equal((await ui("window.managedState()")).busy, true);
  46. await env.agent.respond(request, "allow");
  47. assert.ok((await result).result);
  48. assert.equal(executed("managed-approval"), 1);
  49. const after = await ui("window.managedState()");
  50. assert.equal(after.handle.sandboxId, before.handle.sandboxId);
  51. assert.equal(env.guests.get(win.webContents.id)!.id, guest.id);
  52. assert.deepEqual(after.widget, { managed: 7 });
  53. assert.equal(after.listeners.frame, 1);
  54. assert.equal(env.events.history.filter((e) => e.type === "subscribed").length, 1);
  55. assert.equal(env.agent.events.history.filter((e) => e.type === "read").length, 1);
  56. },
  57. );
  58. await check(
  59. "PDF and SVG resources cross the real SDK, Agent and MCP with MIME guards intact",
  60. async () => {
  61. const pdfUri = "fixture://document.pdf";
  62. const pdf = await page(`window.readResourceFixture(${JSON.stringify(pdfUri)})`);
  63. assert.deepEqual(
  64. pdf.result?.contents,
  65. [
  66. {
  67. uri: pdfUri,
  68. mimeType: "application/pdf",
  69. blob: Buffer.from("%PDF-1.7\n%%EOF\n").toString("base64"),
  70. },
  71. ],
  72. JSON.stringify(pdf),
  73. );
  74. const rejected = await page("window.readResourceFixture('fixture://unsupported.bin')");
  75. // 测试 IPC 的异常只保留 message,页面侧核对拒绝原因;结构化 reason 由 Agent 单测覆盖。
  76. assert.match(rejected.error ?? "", /application\/x-msdownload.*not allowed/);
  77. const svg = await page("window.readResourceFixture('fixture://vector.svg')");
  78. assert.deepEqual(
  79. svg.result?.contents,
  80. [
  81. {
  82. uri: "fixture://vector.svg",
  83. mimeType: "image/svg+xml",
  84. text: '<svg xmlns="http://www.w3.org/2000/svg"/>',
  85. },
  86. ],
  87. JSON.stringify(svg),
  88. );
  89. assert.equal((await ui("window.managedState()")).phase, "running");
  90. for (const uri of [pdfUri, "fixture://unsupported.bin", "fixture://vector.svg"]) {
  91. assert.equal(
  92. env.agent.events.history.filter((e) => e.type === "read" && e.uri === uri).length,
  93. 1,
  94. );
  95. }
  96. },
  97. );
  98. await check(
  99. "all anchors unmounted plus expired retention keeps MCP guest and resource feed after completion",
  100. async () => {
  101. const step = (stage: string) => env.events.emit({ type: "retention-step", stage });
  102. const guest = env.guests.get(win.webContents.id)!;
  103. const result = page("window.callTool('managed-background', true)");
  104. await env.agent.respond(await approval("managed-background"), "allow");
  105. await env.agent.events.wait((e) => e.type === "executed" && e.key === "managed-background");
  106. step("tool-running");
  107. await ui("window.setAnchors(false, false)");
  108. step("anchors-unmounted");
  109. await notification();
  110. step("background-notification");
  111. await ui("window.expireOffscreen()");
  112. assert.equal(guest.isDestroyed(), false);
  113. assert.equal(env.countGuests(), 1);
  114. env.agent.release("managed", "managed-background");
  115. assert.ok((await result).result);
  116. step("tool-completed");
  117. assert.equal(await ui("window.suspendManaged()"), false);
  118. assert.equal(guest.isDestroyed(), false);
  119. await notification();
  120. step("idle-notification");
  121. assert.equal(env.countGuests(), 1);
  122. assert.equal(executed("managed-background"), 1);
  123. },
  124. );
  125. await check(
  126. "production owner retains snapshot and guest after idle and retry clears only widgetState",
  127. async () => {
  128. const retained = env.guests.get(win.webContents.id)!;
  129. await ui("window.setAnchors(true, false)");
  130. assert.notEqual(
  131. (await ui("window.managedState()")).actual?.phase,
  132. "error",
  133. JSON.stringify(await ui("window.managedState()")),
  134. );
  135. assert.equal(env.guests.get(win.webContents.id), retained);
  136. await page("window.fixtureReady");
  137. // guest 没有重建,初始化 hostContext 不会重发;保存快照仍由宿主内存 store 持有。
  138. assert.deepEqual((await ui("window.managedState()")).widget, { managed: 7 });
  139. await page("window.storageRoundTrip(true)");
  140. const old = env.guests.get(win.webContents.id)!;
  141. const offset = env.events.history.length;
  142. await ui("window.retryManaged()");
  143. await env.events.wait((e) => e.type === "phase" && e.phase === "running", offset);
  144. await page("window.fixtureReady");
  145. assert.equal(old.isDestroyed(), true);
  146. assert.equal(await page("window.readWidget()"), null);
  147. assert.deepEqual(await page("window.storageRoundTrip(false)"), { local: "42", indexed: 42 });
  148. assert.equal((await ui("window.managedState()")).listeners.ports, 1);
  149. },
  150. );
  151. await check(
  152. "inline page stays in the scrolling container without frame-delayed movement",
  153. async () => {
  154. await ui("window.setAnchors(true, false)");
  155. const samples = await ui(`(async () => {
  156. const scroller = document.querySelector('#inline-scroll');
  157. const view = document.querySelector('webview');
  158. if (!view.closest('[data-sandbox-page-container]')) throw new Error('page outside scroll tree');
  159. const initial = view.getBoundingClientRect().top + scroller.scrollTop;
  160. const errors = [];
  161. for (const offset of [0, 40, 180, 60, 260, 0]) {
  162. scroller.scrollTop = offset;
  163. errors.push(Math.abs(view.getBoundingClientRect().top + scroller.scrollTop - initial));
  164. await new Promise(requestAnimationFrame);
  165. errors.push(Math.abs(view.getBoundingClientRect().top + scroller.scrollTop - initial));
  166. }
  167. return errors;
  168. })()`);
  169. assert.ok(
  170. samples.every((error: number) => error < 1),
  171. JSON.stringify(samples),
  172. );
  173. },
  174. );
  175. await check(
  176. "real scroll observation removes inline visibility while sidebar remains protected",
  177. async () => {
  178. await ui(
  179. "document.querySelector('#inline-scroll').scrollTop = 900; new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
  180. );
  181. assert.equal((await ui("window.managedState()")).visible, false);
  182. await ui("window.setAnchors(true, true)");
  183. assert.equal((await ui("window.managedState()")).visible, true);
  184. await ui("window.expireOffscreen()");
  185. assert.equal(env.countGuests(), 1);
  186. },
  187. );
  188. await checkModel(env, win, scope, check);
  189. await check(
  190. "runtime unavailable during approval releases page and rejects late permission",
  191. async () => {
  192. const guest = env.guests.get(win.webContents.id)!;
  193. const result = page("window.callTool('managed-runtime')").catch((error) => ({
  194. error: String(error),
  195. }));
  196. const request = await approval("managed-runtime");
  197. const stopped = new Promise<void>((resolve) => guest.once("destroyed", resolve));
  198. await ui("window.runtimeUnavailable()");
  199. await stopped;
  200. assert.ok((await result).error);
  201. await env.agent.respond(request, "allow");
  202. assert.equal(executed("managed-runtime"), 0);
  203. assert.equal((await ui("window.managedState()")).phase, "error");
  204. await assert.rejects(() =>
  205. env.agent.call("mcp/uiValidateInstance", {
  206. ...scope,
  207. instance: env.handles.get(win.webContents.id).instance,
  208. }),
  209. );
  210. },
  211. );
  212. }