managed-checks.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 running tool and resource feed until completion",
  100. async () => {
  101. const guest = env.guests.get(win.webContents.id)!;
  102. const result = page("window.callTool('managed-background', true)");
  103. await env.agent.respond(await approval("managed-background"), "allow");
  104. await env.agent.events.wait((e) => e.type === "executed" && e.key === "managed-background");
  105. await ui("window.setAnchors(false, false)");
  106. await notification();
  107. await ui("window.expireOffscreen()");
  108. assert.equal(guest.isDestroyed(), false);
  109. assert.equal(env.countGuests(), 1);
  110. const stopped = new Promise<void>((resolve) => guest.once("destroyed", resolve));
  111. env.agent.release("managed", "managed-background");
  112. assert.ok((await result).result);
  113. await stopped;
  114. await env.agent.events.wait((e) => e.type === "resources/unsubscribe");
  115. assert.equal(env.countGuests(), 0);
  116. assert.equal(executed("managed-background"), 1);
  117. },
  118. );
  119. await check(
  120. "production owner restores snapshot after recycle and retry clears only widgetState",
  121. async () => {
  122. const after = env.events.history.length;
  123. await ui("window.setAnchors(true, false)");
  124. assert.notEqual(
  125. (await ui("window.managedState()")).actual?.phase,
  126. "error",
  127. JSON.stringify(await ui("window.managedState()")),
  128. );
  129. await env.events.wait((e) => e.type === "phase" && e.phase === "running", after);
  130. await page("window.fixtureReady");
  131. assert.deepEqual(await page("window.readWidget()"), { managed: 7 });
  132. await page("window.storageRoundTrip(true)");
  133. const old = env.guests.get(win.webContents.id)!;
  134. const offset = env.events.history.length;
  135. await ui("window.retryManaged()");
  136. await env.events.wait((e) => e.type === "phase" && e.phase === "running", offset);
  137. await page("window.fixtureReady");
  138. assert.equal(old.isDestroyed(), true);
  139. assert.equal(await page("window.readWidget()"), null);
  140. assert.deepEqual(await page("window.storageRoundTrip(false)"), { local: "42", indexed: 42 });
  141. assert.equal((await ui("window.managedState()")).listeners.ports, 1);
  142. },
  143. );
  144. await check(
  145. "inline page stays in the scrolling container without frame-delayed movement",
  146. async () => {
  147. await ui("window.setAnchors(true, false)");
  148. const samples = await ui(`(async () => {
  149. const scroller = document.querySelector('#inline-scroll');
  150. const view = document.querySelector('webview');
  151. if (!view.closest('[data-sandbox-page-container]')) throw new Error('page outside scroll tree');
  152. const initial = view.getBoundingClientRect().top + scroller.scrollTop;
  153. const errors = [];
  154. for (const offset of [0, 40, 180, 60, 260, 0]) {
  155. scroller.scrollTop = offset;
  156. errors.push(Math.abs(view.getBoundingClientRect().top + scroller.scrollTop - initial));
  157. await new Promise(requestAnimationFrame);
  158. errors.push(Math.abs(view.getBoundingClientRect().top + scroller.scrollTop - initial));
  159. }
  160. return errors;
  161. })()`);
  162. assert.ok(
  163. samples.every((error: number) => error < 1),
  164. JSON.stringify(samples),
  165. );
  166. },
  167. );
  168. await check(
  169. "real scroll observation removes inline visibility while sidebar remains protected",
  170. async () => {
  171. await ui(
  172. "document.querySelector('#inline-scroll').scrollTop = 900; new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
  173. );
  174. assert.equal((await ui("window.managedState()")).visible, false);
  175. await ui("window.setAnchors(true, true)");
  176. assert.equal((await ui("window.managedState()")).visible, true);
  177. await ui("window.expireOffscreen()");
  178. assert.equal(env.countGuests(), 1);
  179. },
  180. );
  181. await checkModel(env, win, scope, check);
  182. await check(
  183. "runtime unavailable during approval releases page and rejects late permission",
  184. async () => {
  185. const guest = env.guests.get(win.webContents.id)!;
  186. const result = page("window.callTool('managed-runtime')").catch((error) => ({
  187. error: String(error),
  188. }));
  189. const request = await approval("managed-runtime");
  190. const stopped = new Promise<void>((resolve) => guest.once("destroyed", resolve));
  191. await ui("window.runtimeUnavailable()");
  192. await stopped;
  193. assert.ok((await result).error);
  194. await env.agent.respond(request, "allow");
  195. assert.equal(executed("managed-runtime"), 0);
  196. assert.equal((await ui("window.managedState()")).phase, "error");
  197. await assert.rejects(() =>
  198. env.agent.call("mcp/uiValidateInstance", {
  199. ...scope,
  200. instance: env.handles.get(win.webContents.id).instance,
  201. }),
  202. );
  203. },
  204. );
  205. }