chain-combinations.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import assert from "node:assert/strict";
  2. import type { BrowserWindow, WebContents } from "electron";
  3. import type { startAgent } from "./agent.js";
  4. export async function checkCombinations(context: {
  5. agent: Awaited<ReturnType<typeof startAgent>>;
  6. win: BrowserWindow;
  7. scope: any;
  8. handles: Map<number, any>;
  9. guests: Map<number, WebContents>;
  10. calls: any[];
  11. bridge: any;
  12. wire(params: any): any;
  13. evalPage(win: BrowserWindow, code: string): Promise<any>;
  14. createWindow(scope: any): Promise<BrowserWindow>;
  15. closeWindow(win: BrowserWindow): Promise<void>;
  16. check(name: string, run: () => Promise<void>): Promise<void>;
  17. }) {
  18. const { agent, win, scope, handles, guests, calls, bridge, wire, evalPage, check } = context;
  19. const approval = (key: string) => agent.approvals.wait((r) => r.params.input?.key === key);
  20. const event = (type: string, key: string) =>
  21. agent.events.wait((e) => e.type === type && e.key === key);
  22. const executions = (key: string) =>
  23. agent.events.history.filter((e) => e.type === "executed" && e.key === key).length;
  24. const cancel = (key: string) => {
  25. const {
  26. toolName: _tool,
  27. arguments: _args,
  28. ...binding
  29. } = calls.find((c) => c.arguments.key === key);
  30. return bridge.cancelToolCall(binding);
  31. };
  32. async function moving(action?: () => Promise<unknown>) {
  33. const identity = handles.get(win.webContents.id);
  34. const guest = guests.get(win.webContents.id)!.id;
  35. const reads = agent.events.history.filter((e) => e.type === "read").length;
  36. const before = new Map<boolean, unknown>();
  37. for (let i = 0; i < 12; i++) {
  38. const move = win.webContents.executeJavaScript(`window.switchPage(${i % 2 === 0})`);
  39. if (i === 5 && action) await action();
  40. const { dispatchMs: _time, ...counts } = await move;
  41. const side = i % 2 === 0;
  42. if (!before.has(side)) before.set(side, counts);
  43. assert.deepEqual(counts, before.get(side));
  44. assert.deepEqual(handles.get(win.webContents.id), identity);
  45. assert.equal(guests.get(win.webContents.id)!.id, guest);
  46. assert.equal(agent.events.history.filter((e) => e.type === "read").length, reads);
  47. }
  48. }
  49. await check(
  50. "approval pending and allow during 12 location changes preserves one invocation",
  51. async () => {
  52. const key = "move-approval";
  53. const result = evalPage(win, `window.callTool('${key}')`);
  54. const request = await approval(key);
  55. await moving(async () => {
  56. assert.equal(executions(key), 0);
  57. await agent.respond(request, "allow");
  58. });
  59. assert.equal((await result).result.structuredContent.key, key);
  60. assert.equal(executions(key), 1);
  61. },
  62. );
  63. await check(
  64. "executing tool and result during 12 location changes preserves target and state",
  65. async () => {
  66. const key = "move-executing";
  67. await evalPage(win, "window.saveWidget({moving: 9})");
  68. const result = evalPage(win, `window.callTool('${key}',true)`);
  69. await agent.respond(await approval(key), "allow");
  70. await event("executed", key);
  71. await moving(async () => {
  72. agent.release("source-a", key);
  73. await event("released", key);
  74. });
  75. assert.equal((await result).result.structuredContent.key, key);
  76. assert.equal(executions(key), 1);
  77. assert.deepEqual(await win.webContents.executeJavaScript("window.savedWidget()"), {
  78. moving: 9,
  79. });
  80. assert.equal(
  81. agent.events.history.some((e) => e.type === "cancelled" && e.key === key),
  82. false,
  83. );
  84. },
  85. );
  86. await check(
  87. "tool input and result notifications arrive during movement without remount",
  88. async () => {
  89. await moving(async () => {
  90. for (let n = 0; n < 5; n++) {
  91. await win.webContents.executeJavaScript(`window.deliverFeed(${n})`);
  92. await evalPage(win, `window.waitFeed(${n})`);
  93. }
  94. });
  95. assert.deepEqual(await evalPage(win, "window.receivedFeed"), {
  96. input: [0, 1, 2, 3, 4],
  97. result: [0, 1, 2, 3, 4],
  98. });
  99. },
  100. );
  101. for (const ordering of ["result-first", "cancel-first", "concurrent"]) {
  102. await check(`cancel/result race ${ordering} has one terminal and no replay`, async () => {
  103. const key = `race-${ordering}`;
  104. const result = evalPage(win, `window.callTool('${key}',true)`);
  105. await agent.respond(await approval(key), "allow");
  106. await event("executed", key);
  107. if (ordering === "result-first") {
  108. agent.release("source-a", key);
  109. assert.ok((await result).result);
  110. assert.equal((await cancel(key)).cancelled, false);
  111. } else if (ordering === "cancel-first") {
  112. assert.equal((await cancel(key)).cancelled, true);
  113. await event("cancelled", key);
  114. assert.ok((await result).error);
  115. agent.release("source-a", key);
  116. } else {
  117. // 同一轮发出,允许任一合法赢家;以 Agent 的取消接纳结果核对页面终态。
  118. const cancellation = cancel(key);
  119. agent.release("source-a", key);
  120. const [ack, response] = await Promise.all([cancellation, result]);
  121. assert.equal(Boolean(response.error), ack.cancelled);
  122. assert.equal(Boolean(response.result), !ack.cancelled);
  123. }
  124. await event("released", key);
  125. assert.equal((await cancel(key)).cancelled, false);
  126. await assert.rejects(() =>
  127. agent.call("mcp/uiCallTool", wire(calls.find((c) => c.arguments.key === key))),
  128. );
  129. assert.equal(executions(key), 1);
  130. assert.equal(await win.webContents.executeJavaScript("window.pageBusy()"), false);
  131. });
  132. }
  133. await check("raw MCP error and mixed content preserve result semantics", async () => {
  134. const key = "raw-error";
  135. const result = evalPage(win, `window.callTool('${key}')`);
  136. await agent.respond(await approval(key), "allow");
  137. const response = await result;
  138. assert.equal(response.error, undefined);
  139. assert.deepEqual(response.result, {
  140. isError: true,
  141. content: [
  142. { type: "text", text: "fixture error" },
  143. { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
  144. {
  145. type: "resource",
  146. resource: { uri: "fixture://error", mimeType: "text/plain", text: "details" },
  147. },
  148. ],
  149. structuredContent: { key, source: "source-a" },
  150. _meta: { fixture: true },
  151. });
  152. assert.equal(executions(key), 1);
  153. });
  154. await check(
  155. "two windows executing: cross-owner dispose and cancellation cannot touch peer",
  156. async () => {
  157. const second = await context.createWindow(scope);
  158. try {
  159. const firstResult = evalPage(win, "window.callTool('peer-first',true)");
  160. const secondResult = evalPage(second, "window.callTool('peer-second',true)");
  161. await agent.respond(await approval("peer-first"), "allow");
  162. await agent.respond(await approval("peer-second"), "allow");
  163. await Promise.all([event("executed", "peer-first"), event("executed", "peer-second")]);
  164. const other = handles.get(second.webContents.id);
  165. await win.webContents.executeJavaScript(
  166. `window.harness.dispose(${JSON.stringify(other.sandboxId)},${other.initId})`,
  167. );
  168. assert.ok(!guests.get(second.webContents.id)!.isDestroyed());
  169. assert.equal((await cancel("peer-first")).cancelled, true);
  170. assert.ok((await firstResult).error);
  171. await win.webContents.executeJavaScript("window.disposePage()");
  172. assert.equal(await second.webContents.executeJavaScript("window.pageBusy()"), true);
  173. agent.release("source-a", "peer-second");
  174. assert.equal((await secondResult).result.structuredContent.key, "peer-second");
  175. assert.equal(executions("peer-first"), 1);
  176. assert.equal(executions("peer-second"), 1);
  177. assert.equal((await cancel("peer-second")).cancelled, false);
  178. await win.webContents.executeJavaScript("window.restorePage(false)");
  179. await evalPage(win, "window.fixtureReady");
  180. } finally {
  181. await context.closeWindow(second);
  182. }
  183. },
  184. );
  185. await check("stable same-origin guest cannot load another instance script resource", async () => {
  186. const second = await context.createWindow(scope);
  187. try {
  188. const ownUrl = await evalPage(win, "location.href");
  189. const peerUrl = await evalPage(second, "location.href");
  190. assert.equal(new URL(ownUrl).host, new URL(peerUrl).host);
  191. assert.notEqual(ownUrl, peerUrl);
  192. // 使用 CSP 本来允许的 self script:避免 connect-src none 让正负样本都失败,掩盖 guest 校验。
  193. const ownAsset = new URL("__zcode__/alias.js", ownUrl).href;
  194. const peerAsset = new URL("__zcode__/alias.js", peerUrl).href;
  195. const loadAsset = (target: BrowserWindow, url: string) =>
  196. evalPage(
  197. target,
  198. `new Promise(resolve => { const s = document.createElement('script'); s.src = ${JSON.stringify(url)}; s.onload = () => { s.remove(); resolve(true); }; s.onerror = () => { s.remove(); resolve(false); }; document.head.append(s); })`,
  199. );
  200. assert.equal(await loadAsset(win, ownAsset), true);
  201. assert.equal(
  202. await loadAsset(win, `${peerAsset}?uncached=${crypto.randomUUID()}`),
  203. false,
  204. "uncached cross-guest request must be denied before checking the shared cache",
  205. );
  206. assert.equal(await loadAsset(win, peerAsset), false);
  207. assert.equal(await loadAsset(second, peerAsset), true);
  208. } finally {
  209. await context.closeWindow(second);
  210. }
  211. });
  212. await check(
  213. "forged credential fields are rejected by real Agent without revoking valid instance",
  214. async () => {
  215. const instance = handles.get(win.webContents.id).instance;
  216. for (const patch of [
  217. { token: crypto.randomUUID() },
  218. { runtimeId: "forged" },
  219. { generation: instance.generation + 100 },
  220. { appIdentity: "b".repeat(64) },
  221. ]) {
  222. await assert.rejects(() =>
  223. agent.call("mcp/uiValidateInstance", { ...scope, instance: { ...instance, ...patch } }),
  224. );
  225. await agent.call("mcp/uiValidateInstance", { ...scope, instance });
  226. }
  227. },
  228. );
  229. }